From c9fb65d2f5757f389383f8b9007baf6a5e26f45a Mon Sep 17 00:00:00 2001 From: Lubos Date: Tue, 4 Nov 2025 06:58:49 +0800 Subject: [PATCH] feat: remove legacy clients and plugins --- .changeset/seven-walls-return.md | 5 + dev/openapi-ts.config.ts | 16 +- dev/package.json | 28 - eslint.config.js | 2 - packages/openapi-ts-tests/main/package.json | 1 - .../test/generated/v2/core/ApiError.ts.snap | 21 - .../v2/core/ApiRequestOptions.ts.snap | 21 - .../test/generated/v2/core/ApiResult.ts.snap | 7 - .../v2/core/CancelablePromise.ts.snap | 126 -- .../test/generated/v2/core/OpenAPI.ts.snap | 56 - .../test/generated/v2/core/request.ts.snap | 350 --- .../test/generated/v2/index.ts.snap | 6 - .../test/generated/v2/schemas.gen.ts.snap | 669 ------ .../test/generated/v2/sdk.gen.ts.snap | 635 ------ .../test/generated/v2/types.gen.ts.snap | 777 ------- .../v3-schemas-form/schemas.gen.ts.snap | 1834 --------------- .../v3-schemas-json/schemas.gen.ts.snap | 1994 ---------------- .../v3-schemas-name/schemas.gen.ts.snap | 1994 ---------------- .../v3-types-PascalCase/index.ts.snap | 3 - .../v3-types-PascalCase/types.gen.ts.snap | 1996 ----------------- .../test/generated/v3/core/ApiError.ts.snap | 21 - .../v3/core/ApiRequestOptions.ts.snap | 21 - .../test/generated/v3/core/ApiResult.ts.snap | 7 - .../v3/core/CancelablePromise.ts.snap | 126 -- .../test/generated/v3/core/OpenAPI.ts.snap | 56 - .../test/generated/v3/core/request.ts.snap | 350 --- .../test/generated/v3/index.ts.snap | 6 - .../test/generated/v3/sdk.gen.ts.snap | 890 -------- .../test/generated/v3/types.gen.ts.snap | 1549 ------------- .../v3_angular/core/ApiError.ts.snap | 21 - .../v3_angular/core/ApiRequestOptions.ts.snap | 21 - .../v3_angular/core/ApiResult.ts.snap | 7 - .../generated/v3_angular/core/OpenAPI.ts.snap | 55 - .../generated/v3_angular/core/request.ts.snap | 337 --- .../test/generated/v3_angular/index.ts.snap | 5 - .../test/generated/v3_angular/sdk.gen.ts.snap | 1007 --------- .../generated/v3_angular/types.gen.ts.snap | 1469 ------------ .../core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../core/ApiResult.ts.snap | 7 - .../v3_angular_transform/core/OpenAPI.ts.snap | 55 - .../v3_angular_transform/core/request.ts.snap | 337 --- .../v3_angular_transform/index.ts.snap | 5 - .../v3_angular_transform/sdk.gen.ts.snap | 86 - .../v3_angular_transform/types.gen.ts.snap | 106 - .../core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../core/ApiResult.ts.snap | 7 - .../core/OpenAPI.ts.snap | 55 - .../core/request.ts.snap | 337 --- .../v3_angular_tree_shakeable/index.ts.snap | 5 - .../v3_angular_tree_shakeable/sdk.gen.ts.snap | 801 ------- .../types.gen.ts.snap | 1469 ------------ .../core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../core/ApiResult.ts.snap | 7 - .../core/OpenAPI.ts.snap | 55 - .../core/request.ts.snap | 337 --- .../index.ts.snap | 5 - .../sdk.gen.ts.snap | 79 - .../types.gen.ts.snap | 106 - .../generated/v3_axios/core/ApiError.ts.snap | 21 - .../v3_axios/core/ApiRequestOptions.ts.snap | 21 - .../generated/v3_axios/core/ApiResult.ts.snap | 7 - .../v3_axios/core/CancelablePromise.ts.snap | 126 -- .../generated/v3_axios/core/OpenAPI.ts.snap | 57 - .../generated/v3_axios/core/request.ts.snap | 347 --- .../test/generated/v3_axios/index.ts.snap | 6 - .../test/generated/v3_axios/sdk.gen.ts.snap | 890 -------- .../test/generated/v3_axios/types.gen.ts.snap | 1549 ------------- .../v3_axios_transform/core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../v3_axios_transform/core/ApiResult.ts.snap | 7 - .../core/CancelablePromise.ts.snap | 126 -- .../v3_axios_transform/core/OpenAPI.ts.snap | 57 - .../v3_axios_transform/core/request.ts.snap | 347 --- .../v3_axios_transform/index.ts.snap | 6 - .../v3_axios_transform/sdk.gen.ts.snap | 79 - .../v3_axios_transform/types.gen.ts.snap | 106 - .../generated/v3_client/ApiClient.ts.snap | 101 - .../generated/v3_client/core/ApiError.ts.snap | 21 - .../v3_client/core/ApiRequestOptions.ts.snap | 21 - .../v3_client/core/ApiResult.ts.snap | 7 - .../v3_client/core/BaseHttpRequest.ts.snap | 10 - .../v3_client/core/CancelablePromise.ts.snap | 126 -- .../v3_client/core/FetchHttpRequest.ts.snap | 22 - .../generated/v3_client/core/OpenAPI.ts.snap | 56 - .../generated/v3_client/core/request.ts.snap | 350 --- .../test/generated/v3_client/index.ts.snap | 8 - .../test/generated/v3_client/sdk.gen.ts.snap | 935 -------- .../generated/v3_client/types.gen.ts.snap | 1469 ------------ .../v3_client_transform/ApiClient.ts.snap | 35 - .../v3_client_transform/core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../core/ApiResult.ts.snap | 7 - .../core/BaseHttpRequest.ts.snap | 10 - .../core/CancelablePromise.ts.snap | 126 -- .../core/FetchHttpRequest.ts.snap | 22 - .../v3_client_transform/core/OpenAPI.ts.snap | 56 - .../v3_client_transform/core/request.ts.snap | 350 --- .../v3_client_transform/index.ts.snap | 8 - .../v3_client_transform/sdk.gen.ts.snap | 80 - .../v3_client_transform/types.gen.ts.snap | 106 - .../test/generated/v3_date/index.ts.snap | 2 - .../test/generated/v3_date/types.gen.ts.snap | 1022 --------- .../v3_enums_typescript/core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../core/ApiResult.ts.snap | 7 - .../core/CancelablePromise.ts.snap | 126 -- .../v3_enums_typescript/core/OpenAPI.ts.snap | 56 - .../v3_enums_typescript/core/request.ts.snap | 350 --- .../v3_enums_typescript/index.ts.snap | 6 - .../v3_enums_typescript/sdk.gen.ts.snap | 890 -------- .../v3_enums_typescript/types.gen.ts.snap | 1524 ------------- .../core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../core/ApiResult.ts.snap | 7 - .../core/CancelablePromise.ts.snap | 126 -- .../core/OpenAPI.ts.snap | 56 - .../core/request.ts.snap | 350 --- .../v3_legacy_positional_args/index.ts.snap | 6 - .../v3_legacy_positional_args/sdk.gen.ts.snap | 84 - .../types.gen.ts.snap | 102 - .../generated/v3_no_index/client.gen.ts.snap | 18 - .../v3_no_index/client/client.gen.ts.snap | 268 --- .../v3_no_index/client/index.ts.snap | 26 - .../v3_no_index/client/types.gen.ts.snap | 268 --- .../v3_no_index/client/utils.gen.ts.snap | 332 --- .../v3_no_index/core/auth.gen.ts.snap | 42 - .../core/bodySerializer.gen.ts.snap | 100 - .../v3_no_index/core/params.gen.ts.snap | 176 -- .../core/pathSerializer.gen.ts.snap | 181 -- .../core/queryKeySerializer.gen.ts.snap | 136 -- .../core/serverSentEvents.gen.ts.snap | 264 --- .../v3_no_index/core/types.gen.ts.snap | 118 - .../v3_no_index/core/utils.gen.ts.snap | 143 -- .../generated/v3_no_index/types.gen.ts.snap | 1996 ----------------- .../generated/v3_node/core/ApiError.ts.snap | 21 - .../v3_node/core/ApiRequestOptions.ts.snap | 21 - .../generated/v3_node/core/ApiResult.ts.snap | 7 - .../v3_node/core/CancelablePromise.ts.snap | 126 -- .../generated/v3_node/core/OpenAPI.ts.snap | 57 - .../generated/v3_node/core/request.ts.snap | 350 --- .../test/generated/v3_node/index.ts.snap | 6 - .../test/generated/v3_node/sdk.gen.ts.snap | 890 -------- .../test/generated/v3_node/types.gen.ts.snap | 1549 ------------- .../v3_node_transform/core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../v3_node_transform/core/ApiResult.ts.snap | 7 - .../core/CancelablePromise.ts.snap | 126 -- .../v3_node_transform/core/OpenAPI.ts.snap | 57 - .../v3_node_transform/core/request.ts.snap | 350 --- .../generated/v3_node_transform/index.ts.snap | 6 - .../v3_node_transform/sdk.gen.ts.snap | 79 - .../v3_node_transform/types.gen.ts.snap | 106 - .../v3_options/core/ApiError.ts.snap | 21 - .../v3_options/core/ApiRequestOptions.ts.snap | 21 - .../v3_options/core/ApiResult.ts.snap | 7 - .../v3_options/core/CancelablePromise.ts.snap | 126 -- .../generated/v3_options/core/OpenAPI.ts.snap | 56 - .../generated/v3_options/core/request.ts.snap | 350 --- .../test/generated/v3_options/index.ts.snap | 6 - .../test/generated/v3_options/sdk.gen.ts.snap | 83 - .../generated/v3_options/types.gen.ts.snap | 102 - .../v3_services_filter/index.ts.snap | 3 - .../v3_services_filter/sdk.gen.ts.snap | 75 - .../v3_services_filter/types.gen.ts.snap | 1102 --------- .../generated/v3_services_name/index.ts.snap | 3 - .../v3_services_name/sdk.gen.ts.snap | 220 -- .../v3_services_name/types.gen.ts.snap | 1207 ---------- .../v3_transform/core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../v3_transform/core/ApiResult.ts.snap | 7 - .../core/CancelablePromise.ts.snap | 126 -- .../v3_transform/core/OpenAPI.ts.snap | 56 - .../v3_transform/core/request.ts.snap | 350 --- .../test/generated/v3_transform/index.ts.snap | 6 - .../generated/v3_transform/sdk.gen.ts.snap | 79 - .../generated/v3_transform/types.gen.ts.snap | 106 - .../generated/v3_tree_shakeable/index.ts.snap | 3 - .../v3_tree_shakeable/sdk.gen.ts.snap | 799 ------- .../v3_tree_shakeable/types.gen.ts.snap | 1549 ------------- .../test/generated/v3_types/index.ts.snap | 3 - .../test/generated/v3_types/types.gen.ts.snap | 1996 ----------------- .../generated/v3_types_no_tree/index.ts.snap | 3 - .../v3_types_no_tree/types.gen.ts.snap | 1996 ----------------- .../generated/v3_xhr/core/ApiError.ts.snap | 21 - .../v3_xhr/core/ApiRequestOptions.ts.snap | 21 - .../generated/v3_xhr/core/ApiResult.ts.snap | 7 - .../v3_xhr/core/CancelablePromise.ts.snap | 126 -- .../generated/v3_xhr/core/OpenAPI.ts.snap | 56 - .../generated/v3_xhr/core/request.ts.snap | 350 --- .../test/generated/v3_xhr/index.ts.snap | 6 - .../test/generated/v3_xhr/sdk.gen.ts.snap | 890 -------- .../test/generated/v3_xhr/types.gen.ts.snap | 1549 ------------- .../v3_xhr_transform/core/ApiError.ts.snap | 21 - .../core/ApiRequestOptions.ts.snap | 21 - .../v3_xhr_transform/core/ApiResult.ts.snap | 7 - .../core/CancelablePromise.ts.snap | 126 -- .../v3_xhr_transform/core/OpenAPI.ts.snap | 56 - .../v3_xhr_transform/core/request.ts.snap | 350 --- .../generated/v3_xhr_transform/index.ts.snap | 6 - .../v3_xhr_transform/sdk.gen.ts.snap | 79 - .../v3_xhr_transform/types.gen.ts.snap | 106 - .../openapi-ts-tests/main/test/index.test.ts | 507 +---- .../main/test/plugins.test.ts | 4 - packages/openapi-ts/package.json | 3 - packages/openapi-ts/src/__tests__/cli.test.ts | 26 - packages/openapi-ts/src/cli.ts | 28 +- packages/openapi-ts/src/config/init.ts | 44 +- packages/openapi-ts/src/config/plugins.ts | 3 +- packages/openapi-ts/src/createClient.ts | 38 +- packages/openapi-ts/src/generate.ts | 15 +- .../src/generate/__tests__/class.test.ts | 143 -- .../src/generate/__tests__/core.test.ts | 441 ---- .../src/generate/__tests__/file.test.ts | 35 - .../src/generate/__tests__/mocks.ts | 39 - packages/openapi-ts/src/generate/class.ts | 47 - packages/openapi-ts/src/generate/client.ts | 34 +- packages/openapi-ts/src/generate/core.ts | 113 - packages/openapi-ts/src/generate/file.ts | 223 -- .../generate/legacy/__tests__/index.test.ts | 156 -- .../generate/legacy/__tests__/output.test.ts | 161 -- .../src/generate/legacy/indexFile.ts | 83 - .../openapi-ts/src/generate/legacy/output.ts | 127 -- packages/openapi-ts/src/generate/output.ts | 5 +- packages/openapi-ts/src/generate/utils.ts | 33 - packages/openapi-ts/src/index.ts | 2 - .../src/legacy/handlebars/compiled/client.js | 457 ---- .../handlebars/compiled/core/ApiError.js | 7 - .../compiled/core/ApiRequestOptions.js | 7 - .../handlebars/compiled/core/ApiResult.js | 7 - .../compiled/core/BaseHttpRequest.js | 109 - .../compiled/core/CancelablePromise.js | 7 - .../handlebars/compiled/core/HttpRequest.js | 147 -- .../handlebars/compiled/core/OpenAPI.js | 275 --- .../compiled/core/angular/getHeaders.js | 7 - .../compiled/core/angular/getRequestBody.js | 7 - .../compiled/core/angular/getResponseBody.js | 7 - .../core/angular/getResponseHeader.js | 7 - .../compiled/core/angular/request.js | 230 -- .../compiled/core/angular/sendRequest.js | 7 - .../compiled/core/axios/getHeaders.js | 7 - .../compiled/core/axios/getRequestBody.js | 7 - .../compiled/core/axios/getResponseBody.js | 7 - .../compiled/core/axios/getResponseHeader.js | 7 - .../handlebars/compiled/core/axios/request.js | 311 --- .../compiled/core/axios/sendRequest.js | 7 - .../compiled/core/fetch/getHeaders.js | 7 - .../compiled/core/fetch/getRequestBody.js | 7 - .../compiled/core/fetch/getResponseBody.js | 7 - .../compiled/core/fetch/getResponseHeader.js | 7 - .../handlebars/compiled/core/fetch/request.js | 321 --- .../compiled/core/fetch/sendRequest.js | 47 - .../compiled/core/functions/base64.js | 7 - .../core/functions/catchErrorCodes.js | 7 - .../compiled/core/functions/getFormData.js | 7 - .../compiled/core/functions/getQueryString.js | 7 - .../compiled/core/functions/getUrl.js | 7 - .../compiled/core/functions/isBlob.js | 7 - .../compiled/core/functions/isFormData.js | 7 - .../compiled/core/functions/isString.js | 7 - .../core/functions/isStringWithValue.js | 7 - .../compiled/core/functions/isSuccess.js | 7 - .../compiled/core/functions/resolve.js | 7 - .../handlebars/compiled/core/request.js | 225 -- .../compiled/core/xhr/getHeaders.js | 7 - .../compiled/core/xhr/getRequestBody.js | 7 - .../compiled/core/xhr/getResponseBody.js | 7 - .../compiled/core/xhr/getResponseHeader.js | 7 - .../handlebars/compiled/core/xhr/request.js | 311 --- .../compiled/core/xhr/sendRequest.js | 7 - .../src/legacy/handlebars/handlebars.cjs | 72 - .../legacy/handlebars/templates/client.hbs | 87 - .../handlebars/templates/core/ApiError.hbs | 21 - .../templates/core/ApiRequestOptions.hbs | 21 - .../handlebars/templates/core/ApiResult.hbs | 7 - .../templates/core/BaseHttpRequest.hbs | 29 - .../templates/core/CancelablePromise.hbs | 126 -- .../handlebars/templates/core/HttpRequest.hbs | 59 - .../handlebars/templates/core/OpenAPI.hbs | 84 - .../templates/core/angular/getHeaders.hbs | 48 - .../templates/core/angular/getRequestBody.hbs | 12 - .../core/angular/getResponseBody.hbs | 6 - .../core/angular/getResponseHeader.hbs | 9 - .../templates/core/angular/request.hbs | 114 - .../templates/core/angular/sendRequest.hbs | 16 - .../templates/core/axios/getHeaders.hbs | 50 - .../templates/core/axios/getRequestBody.hbs | 6 - .../templates/core/axios/getResponseBody.hbs | 6 - .../core/axios/getResponseHeader.hbs | 9 - .../templates/core/axios/request.hbs | 106 - .../templates/core/axios/sendRequest.hbs | 37 - .../templates/core/fetch/getHeaders.hbs | 46 - .../templates/core/fetch/getRequestBody.hbs | 12 - .../templates/core/fetch/getResponseBody.hbs | 22 - .../core/fetch/getResponseHeader.hbs | 9 - .../templates/core/fetch/request.hbs | 104 - .../templates/core/fetch/sendRequest.hbs | 32 - .../templates/core/functions/base64.hbs | 8 - .../core/functions/catchErrorCodes.hbs | 68 - .../templates/core/functions/getFormData.hbs | 26 - .../core/functions/getQueryString.hbs | 27 - .../templates/core/functions/getUrl.hbs | 15 - .../templates/core/functions/isBlob.hbs | 3 - .../templates/core/functions/isFormData.hbs | 3 - .../templates/core/functions/isString.hbs | 3 - .../core/functions/isStringWithValue.hbs | 3 - .../templates/core/functions/isSuccess.hbs | 3 - .../templates/core/functions/resolve.hbs | 8 - .../handlebars/templates/core/request.hbs | 5 - .../templates/core/xhr/getHeaders.hbs | 46 - .../templates/core/xhr/getRequestBody.hbs | 12 - .../templates/core/xhr/getResponseBody.hbs | 17 - .../templates/core/xhr/getResponseHeader.hbs | 9 - .../handlebars/templates/core/xhr/request.hbs | 102 - .../templates/core/xhr/sendRequest.hbs | 31 - .../src/openApi/__tests__/index.test.ts | 82 +- .../openApi/common/interfaces/Dictionary.ts | 3 - .../src/openApi/common/interfaces/OpenApi.ts | 4 - .../src/openApi/common/interfaces/Type.ts | 8 - .../common/interfaces/WithEnumExtension.ts | 6 - .../src/openApi/common/interfaces/client.ts | 171 -- .../parser/__tests__/getPattern.test.ts | 22 - .../common/parser/__tests__/getRef.test.ts | 95 - .../common/parser/__tests__/operation.test.ts | 18 - .../common/parser/__tests__/sanitize.test.ts | 38 +- .../common/parser/__tests__/service.test.ts | 13 - .../common/parser/__tests__/sort.test.ts | 37 - .../parser/__tests__/stripNamespace.test.ts | 23 - .../common/parser/__tests__/type.test.ts | 157 -- .../src/openApi/common/parser/getDefault.ts | 42 - .../src/openApi/common/parser/getEnums.ts | 32 - .../src/openApi/common/parser/getPattern.ts | 12 - .../src/openApi/common/parser/getRef.ts | 35 - .../src/openApi/common/parser/operation.ts | 243 -- .../src/openApi/common/parser/sanitize.ts | 16 - .../src/openApi/common/parser/service.ts | 20 - .../src/openApi/common/parser/sort.ts | 15 - .../openApi/common/parser/stripNamespace.ts | 20 - .../src/openApi/common/parser/type.ts | 171 -- packages/openapi-ts/src/openApi/index.ts | 52 +- packages/openapi-ts/src/openApi/v2/index.ts | 27 - .../Extensions/WithNullableExtension.ts | 3 - .../src/openApi/v2/interfaces/Model.ts | 14 - .../src/openApi/v2/interfaces/OpenApi.ts | 32 - .../openApi/v2/interfaces/OpenApiContact.ts | 8 - .../openApi/v2/interfaces/OpenApiExample.ts | 6 - .../v2/interfaces/OpenApiExternalDocs.ts | 7 - .../openApi/v2/interfaces/OpenApiHeader.ts | 38 - .../src/openApi/v2/interfaces/OpenApiInfo.ts | 14 - .../src/openApi/v2/interfaces/OpenApiItems.ts | 35 - .../openApi/v2/interfaces/OpenApiLicense.ts | 7 - .../openApi/v2/interfaces/OpenApiOperation.ts | 22 - .../openApi/v2/interfaces/OpenApiParameter.ts | 49 - .../src/openApi/v2/interfaces/OpenApiPath.ts | 19 - .../openApi/v2/interfaces/OpenApiReference.ts | 6 - .../openApi/v2/interfaces/OpenApiResponse.ts | 16 - .../openApi/v2/interfaces/OpenApiResponses.ts | 12 - .../openApi/v2/interfaces/OpenApiSchema.ts | 56 - .../interfaces/OpenApiSecurityRequirement.ts | 6 - .../v2/interfaces/OpenApiSecurityScheme.ts | 15 - .../src/openApi/v2/interfaces/OpenApiTag.ts | 10 - .../src/openApi/v2/interfaces/OpenApiXml.ts | 10 - .../v2/parser/__tests__/getServer.test.ts | 21 - .../src/openApi/v2/parser/getModel.ts | 190 -- .../openApi/v2/parser/getModelComposition.ts | 108 - .../openApi/v2/parser/getModelProperties.ts | 104 - .../src/openApi/v2/parser/getModels.ts | 41 - .../v2/parser/getOperationParameter.ts | 186 -- .../v2/parser/getOperationParameters.ts | 94 - .../openApi/v2/parser/getOperationResponse.ts | 113 - .../v2/parser/getOperationResponses.ts | 45 - .../src/openApi/v2/parser/getOperations.ts | 75 - .../getRequiredPropertiesFromComposition.ts | 42 - .../src/openApi/v2/parser/getServer.ts | 13 - .../src/openApi/v2/parser/operation.ts | 116 - packages/openapi-ts/src/openApi/v3/index.ts | 27 - .../src/openApi/v3/interfaces/Model.ts | 20 - .../src/openApi/v3/interfaces/OpenApi.ts | 21 - .../openApi/v3/interfaces/OpenApiCallback.ts | 11 - .../v3/interfaces/OpenApiComponents.ts | 26 - .../openApi/v3/interfaces/OpenApiContact.ts | 8 - .../v3/interfaces/OpenApiDiscriminator.ts | 9 - .../openApi/v3/interfaces/OpenApiEncoding.ts | 14 - .../openApi/v3/interfaces/OpenApiExample.ts | 11 - .../v3/interfaces/OpenApiExternalDocs.ts | 7 - .../openApi/v3/interfaces/OpenApiHeader.ts | 21 - .../src/openApi/v3/interfaces/OpenApiInfo.ts | 14 - .../openApi/v3/interfaces/OpenApiLicense.ts | 7 - .../src/openApi/v3/interfaces/OpenApiLink.ts | 16 - .../openApi/v3/interfaces/OpenApiMediaType.ts | 16 - .../openApi/v3/interfaces/OpenApiOAuthFlow.ts | 11 - .../v3/interfaces/OpenApiOAuthFlows.ts | 11 - .../openApi/v3/interfaces/OpenApiOperation.ts | 27 - .../openApi/v3/interfaces/OpenApiParameter.ts | 44 - .../src/openApi/v3/interfaces/OpenApiPath.ts | 22 - .../src/openApi/v3/interfaces/OpenApiPaths.ts | 8 - .../openApi/v3/interfaces/OpenApiReference.ts | 6 - .../v3/interfaces/OpenApiRequestBody.ts | 15 - .../openApi/v3/interfaces/OpenApiResponse.ts | 16 - .../openApi/v3/interfaces/OpenApiResponses.ts | 14 - .../openApi/v3/interfaces/OpenApiSchema.ts | 61 - .../interfaces/OpenApiSecurityRequirement.ts | 6 - .../v3/interfaces/OpenApiSecurityScheme.ts | 16 - .../openApi/v3/interfaces/OpenApiServer.ts | 12 - .../v3/interfaces/OpenApiServerVariable.ts | 10 - .../src/openApi/v3/interfaces/OpenApiTag.ts | 10 - .../src/openApi/v3/interfaces/OpenApiXml.ts | 10 - .../v3/parser/__tests__/getModel.test.ts | 142 -- .../v3/parser/__tests__/getServer.test.ts | 49 - .../src/openApi/v3/parser/discriminator.ts | 54 - .../src/openApi/v3/parser/getContent.ts | 55 - .../src/openApi/v3/parser/getModel.ts | 325 --- .../openApi/v3/parser/getModelComposition.ts | 179 -- .../openApi/v3/parser/getModelProperties.ts | 211 -- .../src/openApi/v3/parser/getModels.ts | 62 - .../v3/parser/getOperationParameter.ts | 130 -- .../v3/parser/getOperationParameters.ts | 97 - .../v3/parser/getOperationRequestBody.ts | 112 - .../openApi/v3/parser/getOperationResponse.ts | 118 - .../v3/parser/getOperationResponses.ts | 46 - .../src/openApi/v3/parser/getOperations.ts | 75 - .../getRequiredPropertiesFromComposition.ts | 73 - .../src/openApi/v3/parser/getServer.ts | 11 - .../src/openApi/v3/parser/inferType.ts | 29 - .../src/openApi/v3/parser/operation.ts | 182 -- .../src/openApi/v3/parser/parameter.ts | 25 - .../plugins/@hey-api/legacy-angular/config.ts | 16 - .../plugins/@hey-api/legacy-angular/index.ts | 2 - .../@hey-api/legacy-angular/types.d.ts | 7 - .../plugins/@hey-api/legacy-axios/config.ts | 16 - .../plugins/@hey-api/legacy-axios/index.ts | 2 - .../plugins/@hey-api/legacy-axios/types.d.ts | 7 - .../plugins/@hey-api/legacy-fetch/config.ts | 16 - .../plugins/@hey-api/legacy-fetch/index.ts | 2 - .../plugins/@hey-api/legacy-fetch/types.d.ts | 7 - .../plugins/@hey-api/legacy-node/config.ts | 16 - .../src/plugins/@hey-api/legacy-node/index.ts | 2 - .../plugins/@hey-api/legacy-node/types.d.ts | 7 - .../src/plugins/@hey-api/legacy-xhr/config.ts | 16 - .../src/plugins/@hey-api/legacy-xhr/index.ts | 2 - .../plugins/@hey-api/legacy-xhr/types.d.ts | 7 - .../schemas/__tests__/schemas.test.ts | 348 --- .../src/plugins/@hey-api/schemas/config.ts | 2 - .../plugins/@hey-api/schemas/plugin-legacy.ts | 122 - .../src/plugins/@hey-api/schemas/types.d.ts | 3 - .../@hey-api/sdk/__tests__/plugin.test.ts | 738 ------ .../src/plugins/@hey-api/sdk/config.ts | 2 - .../src/plugins/@hey-api/sdk/plugin-legacy.ts | 942 -------- .../plugins/@hey-api/sdk/shared/functions.ts | 26 +- .../plugins/@hey-api/sdk/shared/operation.ts | 2 +- .../src/plugins/@hey-api/sdk/types.d.ts | 9 +- .../plugins/@hey-api/transformers/config.ts | 2 - .../@hey-api/transformers/plugin-legacy.ts | 356 --- .../typescript/__tests__/plugin.test.ts | 208 -- .../src/plugins/@hey-api/typescript/config.ts | 2 - .../@hey-api/typescript/plugin-legacy.ts | 637 ------ .../angular-query-experimental/config.ts | 2 - .../@tanstack/query-core/plugin-legacy.ts | 1324 ----------- .../plugins/@tanstack/react-query/config.ts | 2 - .../plugins/@tanstack/solid-query/config.ts | 2 - .../plugins/@tanstack/svelte-query/config.ts | 2 - .../src/plugins/@tanstack/vue-query/config.ts | 2 - packages/openapi-ts/src/plugins/config.ts | 20 - packages/openapi-ts/src/plugins/types.d.ts | 22 +- packages/openapi-ts/src/tsc/utils.ts | 7 +- packages/openapi-ts/src/types/client.d.ts | 23 - packages/openapi-ts/src/types/config.d.ts | 98 +- packages/openapi-ts/src/types/types.d.ts | 6 - packages/openapi-ts/src/types/utils.d.ts | 5 - .../src/utils/__tests__/enum.test.ts | 25 - .../src/utils/__tests__/handlebars.test.ts | 257 --- .../src/utils/__tests__/parse.test.ts | 400 ---- .../src/utils/__tests__/postprocess.test.ts | 100 - .../src/utils/__tests__/sort.test.ts | 111 - .../src/utils/__tests__/type.test.ts | 62 - .../src/utils/__tests__/unique.test.ts | 28 - packages/openapi-ts/src/utils/config.ts | 34 - packages/openapi-ts/src/utils/const.ts | 3 - packages/openapi-ts/src/utils/enum.ts | 77 - .../src/utils/getHttpRequestName.ts | 22 - packages/openapi-ts/src/utils/handlebars.ts | 343 --- packages/openapi-ts/src/utils/meta.ts | 42 - packages/openapi-ts/src/utils/postprocess.ts | 130 -- packages/openapi-ts/src/utils/sort.ts | 12 - packages/openapi-ts/src/utils/transform.ts | 35 - packages/openapi-ts/src/utils/type.ts | 351 --- packages/openapi-ts/src/utils/unique.ts | 3 - pnpm-lock.yaml | 442 +--- 490 files changed, 217 insertions(+), 74419 deletions(-) create mode 100644 .changeset/seven-walls-return.md delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/schemas.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-form/schemas.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-json/schemas.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-name/schemas.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/ApiClient.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/BaseHttpRequest.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/FetchHttpRequest.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/ApiClient.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/BaseHttpRequest.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/FetchHttpRequest.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/client.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/utils.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/auth.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/bodySerializer.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/params.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/pathSerializer.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/queryKeySerializer.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/serverSentEvents.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/utils.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/types.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiError.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiRequestOptions.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiResult.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/CancelablePromise.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/OpenAPI.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/request.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/index.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/sdk.gen.ts.snap delete mode 100644 packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/types.gen.ts.snap delete mode 100644 packages/openapi-ts/src/generate/__tests__/class.test.ts delete mode 100644 packages/openapi-ts/src/generate/__tests__/core.test.ts delete mode 100644 packages/openapi-ts/src/generate/__tests__/file.test.ts delete mode 100644 packages/openapi-ts/src/generate/__tests__/mocks.ts delete mode 100644 packages/openapi-ts/src/generate/class.ts delete mode 100644 packages/openapi-ts/src/generate/core.ts delete mode 100644 packages/openapi-ts/src/generate/file.ts delete mode 100644 packages/openapi-ts/src/generate/legacy/__tests__/index.test.ts delete mode 100644 packages/openapi-ts/src/generate/legacy/__tests__/output.test.ts delete mode 100644 packages/openapi-ts/src/generate/legacy/indexFile.ts delete mode 100644 packages/openapi-ts/src/generate/legacy/output.ts delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/client.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiError.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiRequestOptions.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiResult.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/BaseHttpRequest.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/CancelablePromise.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/HttpRequest.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/OpenAPI.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getHeaders.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getRequestBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseHeader.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/request.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/sendRequest.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getHeaders.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getRequestBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseHeader.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/request.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/sendRequest.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getHeaders.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getRequestBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseHeader.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/request.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/sendRequest.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/base64.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/catchErrorCodes.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getFormData.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getQueryString.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getUrl.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isBlob.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isFormData.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isString.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isStringWithValue.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isSuccess.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/resolve.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/request.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getHeaders.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getRequestBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseBody.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseHeader.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/request.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/sendRequest.js delete mode 100644 packages/openapi-ts/src/legacy/handlebars/handlebars.cjs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/client.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/ApiError.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/ApiRequestOptions.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/ApiResult.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/BaseHttpRequest.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/CancelablePromise.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/HttpRequest.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/OpenAPI.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getHeaders.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getRequestBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseHeader.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/angular/request.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/angular/sendRequest.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getHeaders.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getRequestBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseHeader.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/axios/request.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/axios/sendRequest.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getHeaders.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getRequestBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseHeader.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/request.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/sendRequest.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/base64.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/catchErrorCodes.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getFormData.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getQueryString.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getUrl.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isBlob.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isFormData.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isString.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isStringWithValue.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isSuccess.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/functions/resolve.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/request.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getHeaders.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getRequestBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseBody.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseHeader.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/request.hbs delete mode 100644 packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/sendRequest.hbs delete mode 100644 packages/openapi-ts/src/openApi/common/interfaces/Dictionary.ts delete mode 100644 packages/openapi-ts/src/openApi/common/interfaces/OpenApi.ts delete mode 100644 packages/openapi-ts/src/openApi/common/interfaces/Type.ts delete mode 100644 packages/openapi-ts/src/openApi/common/interfaces/WithEnumExtension.ts delete mode 100644 packages/openapi-ts/src/openApi/common/interfaces/client.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/__tests__/getPattern.test.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/__tests__/getRef.test.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/__tests__/operation.test.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/__tests__/service.test.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/__tests__/sort.test.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/__tests__/stripNamespace.test.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/__tests__/type.test.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/getDefault.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/getEnums.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/getPattern.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/getRef.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/operation.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/service.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/sort.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/stripNamespace.ts delete mode 100644 packages/openapi-ts/src/openApi/common/parser/type.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/index.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/Extensions/WithNullableExtension.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/Model.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApi.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiContact.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExample.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExternalDocs.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiHeader.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiInfo.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiItems.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiLicense.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiOperation.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiParameter.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiPath.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiReference.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponse.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponses.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSchema.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityRequirement.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityScheme.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiTag.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/interfaces/OpenApiXml.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/__tests__/getServer.test.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getModel.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getModelComposition.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getModelProperties.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getModels.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getOperationParameter.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getOperationParameters.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getOperationResponse.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getOperationResponses.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getOperations.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getRequiredPropertiesFromComposition.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/getServer.ts delete mode 100644 packages/openapi-ts/src/openApi/v2/parser/operation.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/index.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/Model.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApi.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiCallback.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiComponents.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiContact.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiDiscriminator.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiEncoding.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExample.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExternalDocs.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiHeader.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiInfo.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLicense.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLink.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiMediaType.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlow.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlows.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOperation.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiParameter.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPath.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPaths.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiReference.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiRequestBody.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponse.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponses.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSchema.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityRequirement.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityScheme.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServer.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServerVariable.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiTag.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/interfaces/OpenApiXml.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/__tests__/getModel.test.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/__tests__/getServer.test.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/discriminator.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getContent.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getModel.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getModelComposition.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getModelProperties.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getModels.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getOperationParameter.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getOperationParameters.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getOperationRequestBody.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getOperationResponse.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getOperationResponses.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getOperations.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getRequiredPropertiesFromComposition.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/getServer.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/inferType.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/operation.ts delete mode 100644 packages/openapi-ts/src/openApi/v3/parser/parameter.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-angular/config.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-angular/index.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-angular/types.d.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-axios/config.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-axios/index.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-axios/types.d.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/config.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/index.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/types.d.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-node/config.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-node/index.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-node/types.d.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/config.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/index.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/types.d.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/schemas/__tests__/schemas.test.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/schemas/plugin-legacy.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/sdk/__tests__/plugin.test.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/sdk/plugin-legacy.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/transformers/plugin-legacy.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/typescript/__tests__/plugin.test.ts delete mode 100644 packages/openapi-ts/src/plugins/@hey-api/typescript/plugin-legacy.ts delete mode 100644 packages/openapi-ts/src/plugins/@tanstack/query-core/plugin-legacy.ts delete mode 100644 packages/openapi-ts/src/types/client.d.ts delete mode 100644 packages/openapi-ts/src/utils/__tests__/enum.test.ts delete mode 100644 packages/openapi-ts/src/utils/__tests__/handlebars.test.ts delete mode 100644 packages/openapi-ts/src/utils/__tests__/parse.test.ts delete mode 100644 packages/openapi-ts/src/utils/__tests__/postprocess.test.ts delete mode 100644 packages/openapi-ts/src/utils/__tests__/sort.test.ts delete mode 100644 packages/openapi-ts/src/utils/__tests__/type.test.ts delete mode 100644 packages/openapi-ts/src/utils/__tests__/unique.test.ts delete mode 100644 packages/openapi-ts/src/utils/config.ts delete mode 100644 packages/openapi-ts/src/utils/const.ts delete mode 100644 packages/openapi-ts/src/utils/enum.ts delete mode 100644 packages/openapi-ts/src/utils/getHttpRequestName.ts delete mode 100644 packages/openapi-ts/src/utils/handlebars.ts delete mode 100644 packages/openapi-ts/src/utils/meta.ts delete mode 100644 packages/openapi-ts/src/utils/postprocess.ts delete mode 100644 packages/openapi-ts/src/utils/sort.ts delete mode 100644 packages/openapi-ts/src/utils/type.ts delete mode 100644 packages/openapi-ts/src/utils/unique.ts diff --git a/.changeset/seven-walls-return.md b/.changeset/seven-walls-return.md new file mode 100644 index 000000000..02f2b9bbd --- /dev/null +++ b/.changeset/seven-walls-return.md @@ -0,0 +1,5 @@ +--- +'@hey-api/openapi-ts': minor +--- + +feat: remove legacy clients and plugins diff --git a/dev/openapi-ts.config.ts b/dev/openapi-ts.config.ts index b9023d7d8..c919e1ed0 100644 --- a/dev/openapi-ts.config.ts +++ b/dev/openapi-ts.config.ts @@ -36,15 +36,15 @@ export default defineConfig(() => { // }, path: path.resolve( getSpecsPath(), - '3.0.x', - // '3.1.x', + // '3.0.x', + '3.1.x', // 'circular.yaml', // 'dutchie.json', // 'invalid', // 'openai.yaml', // 'full.yaml', - // 'opencode.yaml', - 'sdk-circular-bug.yaml', + 'opencode.yaml', + // 'sdk-circular-bug.yaml', // 'sdk-instance.yaml', // 'string-with-format.yaml', // 'transformers.json', @@ -265,14 +265,14 @@ export default defineConfig(() => { instance: true, name: '@hey-api/sdk', // operationId: false, - // paramsStructure: 'flat', + paramsStructure: 'flat', // responseStyle: 'data', // signature: 'auto', // signature: 'client', // signature: 'object', // transformer: '@hey-api/transformers', - transformer: true, - validator: true, + // transformer: true, + // validator: true, // validator: { // request: 'zod', // response: 'zod', @@ -294,7 +294,7 @@ export default defineConfig(() => { { // bigInt: true, // dates: true, - name: '@hey-api/transformers', + // name: '@hey-api/transformers', }, { // name: 'fastify', diff --git a/dev/package.json b/dev/package.json index 7ba556089..83230c8a4 100644 --- a/dev/package.json +++ b/dev/package.json @@ -7,20 +7,7 @@ "node": ">=20.19.0" }, "devDependencies": { - "@angular-devkit/build-angular": "19.2.19", - "@angular/animations": "19.2.15", - "@angular/cli": "19.2.19", - "@angular/common": "19.2.15", - "@angular/compiler": "19.2.15", - "@angular/compiler-cli": "19.2.15", - "@angular/core": "19.2.15", - "@angular/forms": "19.2.15", - "@angular/platform-browser": "19.2.15", - "@angular/platform-browser-dynamic": "19.2.15", - "@angular/router": "19.2.15", - "@config/vite-base": "workspace:*", "@hey-api/codegen-core": "workspace:*", - "@hey-api/custom-client": "workspace:*", "@hey-api/openapi-ts": "workspace:*", "@pinia/colada": "0.17.7", "@tanstack/angular-query-experimental": "5.73.3", @@ -28,24 +15,9 @@ "@tanstack/solid-query": "5.73.3", "@tanstack/svelte-query": "5.73.3", "@tanstack/vue-query": "5.73.3", - "@types/cross-spawn": "6.0.6", - "ajv": "8.17.1", "arktype": "2.1.25", - "axios": "1.8.2", - "cross-spawn": "7.0.6", - "eslint": "9.17.0", - "fastify": "5.2.0", - "glob": "11.0.3", - "node-fetch": "3.3.2", - "nuxt": "3.14.1592", - "ofetch": "1.4.1", - "prettier": "3.4.2", - "rxjs": "7.8.2", - "ts-node": "10.9.2", - "tslib": "2.8.1", "typescript": "5.9.3", "valibot": "1.1.0", - "vue": "3.5.13", "zod": "4.1.12" } } diff --git a/eslint.config.js b/eslint.config.js index 712bfb461..f8bd50bcf 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -66,8 +66,6 @@ export default tseslint.config( 'temp/', 'dev/.gen/', 'examples/openapi-ts-openai/src/client/**/*.ts', - 'packages/openapi-ts/src/legacy/handlebars/compiled/**/*.js', - 'packages/openapi-ts/src/legacy/handlebars/templates/**/*.hbs', '**/test/generated/', '**/__snapshots__/', '**/.next/', diff --git a/packages/openapi-ts-tests/main/package.json b/packages/openapi-ts-tests/main/package.json index 9e4f4afbc..924e5113a 100644 --- a/packages/openapi-ts-tests/main/package.json +++ b/packages/openapi-ts-tests/main/package.json @@ -43,7 +43,6 @@ "cross-spawn": "7.0.6", "eslint": "9.17.0", "fastify": "5.2.0", - "glob": "11.0.3", "node-fetch": "3.3.2", "nuxt": "3.14.1592", "ofetch": "1.4.1", diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/schemas.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/schemas.gen.ts.snap deleted file mode 100644 index 8d4a5df9d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/schemas.gen.ts.snap +++ /dev/null @@ -1,669 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export const CommentWithBreaksSchema = { - description: `Testing multiline comments in string: First line -Second line - -Fourth line`, - type: 'integer' -} as const; - -export const CommentWithBackticksSchema = { - description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work', - type: 'integer' -} as const; - -export const CommentWithBackticksAndQuotesSchema = { - description: `Testing backticks and quotes in string: \`backticks\`, 'quotes', "double quotes" and \`\`\`multiple backticks\`\`\` should work`, - type: 'integer' -} as const; - -export const CommentWithSlashesSchema = { - description: 'Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work', - type: 'integer' -} as const; - -export const CommentWithExpressionPlaceholdersSchema = { - description: 'Testing expression placeholders in string: ${expression} should work', - type: 'integer' -} as const; - -export const CommentWithQuotesSchema = { - description: `Testing quotes in string: 'single quote''' and "double quotes""" should work`, - type: 'integer' -} as const; - -export const CommentWithReservedCharactersSchema = { - description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work', - type: 'integer' -} as const; - -export const SimpleIntegerSchema = { - description: 'This is a simple number', - type: 'integer' -} as const; - -export const SimpleBooleanSchema = { - description: 'This is a simple boolean', - type: 'boolean' -} as const; - -export const SimpleStringSchema = { - description: 'This is a simple string', - type: 'string' -} as const; - -export const NonAsciiStringæøåÆØÅöôêÊ字符串Schema = { - description: 'A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串)', - type: 'string' -} as const; - -export const SimpleFileSchema = { - description: 'This is a simple file', - type: 'file' -} as const; - -export const SimpleReferenceSchema = { - description: 'This is a simple reference', - '$ref': '#/definitions/ModelWithString' -} as const; - -export const SimpleStringWithPatternSchema = { - description: 'This is a simple string', - type: 'string', - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$' -} as const; - -export const EnumWithStringsSchema = { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', "'Single Quote'", '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串'] -} as const; - -export const EnumWithNumbersSchema = { - description: 'This is a simple enum with numbers', - enum: [1, 2, 3, 1.1, 1.2, 1.3, 100, 200, 300, -100, -200, -300, -1.1, -1.2, -1.3] -} as const; - -export const EnumFromDescriptionSchema = { - description: 'Success=1,Warning=2,Error=3', - type: 'number' -} as const; - -export const EnumWithExtensionsSchema = { - description: 'This is a simple enum with numbers', - enum: [200, 400, 500], - 'x-enum-varnames': ['CUSTOM_SUCCESS', 'CUSTOM_WARNING', 'CUSTOM_ERROR'], - 'x-enum-descriptions': ['Used when the status of something is successful', 'Used when the status of something has a warning', 'Used when the status of something has an error'] -} as const; - -export const ArrayWithNumbersSchema = { - description: 'This is a simple array with numbers', - type: 'array', - items: { - type: 'integer' - } -} as const; - -export const ArrayWithBooleansSchema = { - description: 'This is a simple array with booleans', - type: 'array', - items: { - type: 'boolean' - } -} as const; - -export const ArrayWithStringsSchema = { - description: 'This is a simple array with strings', - type: 'array', - items: { - type: 'string' - } -} as const; - -export const ArrayWithReferencesSchema = { - description: 'This is a simple array with references', - type: 'array', - items: { - '$ref': '#/definitions/ModelWithString' - } -} as const; - -export const ArrayWithArraySchema = { - description: 'This is a simple array containing an array', - type: 'array', - items: { - type: 'array', - items: { - '$ref': '#/definitions/ModelWithString' - } - } -} as const; - -export const ArrayWithPropertiesSchema = { - description: 'This is a simple array with properties', - type: 'array', - items: { - type: 'object', - properties: { - foo: { - type: 'string' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const DictionaryWithStringSchema = { - description: 'This is a string dictionary', - type: 'object', - additionalProperties: { - type: 'string' - } -} as const; - -export const DictionaryWithReferenceSchema = { - description: 'This is a string reference', - type: 'object', - additionalProperties: { - '$ref': '#/definitions/ModelWithString' - } -} as const; - -export const DictionaryWithArraySchema = { - description: 'This is a complex dictionary', - type: 'object', - additionalProperties: { - type: 'array', - items: { - '$ref': '#/definitions/ModelWithString' - } - } -} as const; - -export const DictionaryWithDictionarySchema = { - description: 'This is a string dictionary', - type: 'object', - additionalProperties: { - type: 'object', - additionalProperties: { - type: 'string' - } - } -} as const; - -export const DictionaryWithPropertiesSchema = { - description: 'This is a complex dictionary', - type: 'object', - additionalProperties: { - type: 'object', - properties: { - foo: { - type: 'string' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const DateSchema = { - description: 'This is a type-only model that defines Date as a string', - type: 'string' -} as const; - -export const ModelWithIntegerSchema = { - description: 'This is a model with one number property', - type: 'object', - properties: { - prop: { - description: 'This is a simple number property', - type: 'integer' - } - } -} as const; - -export const ModelWithBooleanSchema = { - description: 'This is a model with one boolean property', - type: 'object', - properties: { - prop: { - description: 'This is a simple boolean property', - type: 'boolean' - } - } -} as const; - -export const ModelWithStringSchema = { - description: 'This is a model with one string property', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - } -} as const; - -export const ModelWithStringErrorSchema = { - description: 'This is a model with one string property', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - } -} as const; - -export const ModelWithNullableStringSchema = { - description: 'This is a model with one string property', - type: 'object', - required: ['nullableRequiredProp'], - properties: { - nullableProp: { - description: 'This is a simple string property', - type: 'string', - 'x-nullable': true - }, - nullableRequiredProp: { - description: 'This is a simple string property', - type: 'string', - 'x-nullable': true - } - } -} as const; - -export const ModelWithEnumSchema = { - description: 'This is a model with one enum', - type: 'object', - properties: { - test: { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - }, - statusCode: { - description: 'These are the HTTP error code enums', - enum: ['100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar'] - }, - bool: { - description: 'Simple boolean enum', - type: 'boolean', - enum: [true] - } - } -} as const; - -export const ModelWithEnumFromDescriptionSchema = { - description: 'This is a model with one enum', - type: 'object', - properties: { - test: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - } -} as const; - -export const ModelWithNestedEnumsSchema = { - description: 'This is a model with nested enums', - type: 'object', - properties: { - dictionaryWithEnum: { - type: 'object', - additionalProperties: { - enum: ['Success', 'Warning', 'Error'] - } - }, - dictionaryWithEnumFromDescription: { - type: 'object', - additionalProperties: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - }, - arrayWithEnum: { - type: 'array', - items: { - enum: ['Success', 'Warning', 'Error'] - } - }, - arrayWithDescription: { - type: 'array', - items: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - } - } -} as const; - -export const ModelWithReferenceSchema = { - description: 'This is a model with one property containing a reference', - type: 'object', - properties: { - prop: { - '$ref': '#/definitions/ModelWithProperties' - } - } -} as const; - -export const ModelWithArraySchema = { - description: 'This is a model with one property containing an array', - type: 'object', - properties: { - prop: { - type: 'array', - items: { - '$ref': '#/definitions/ModelWithString' - } - }, - propWithFile: { - type: 'array', - items: { - type: 'file' - } - }, - propWithNumber: { - type: 'array', - items: { - type: 'number' - } - } - } -} as const; - -export const ModelWithDictionarySchema = { - description: 'This is a model with one property containing a dictionary', - type: 'object', - properties: { - prop: { - type: 'object', - additionalProperties: { - type: 'string' - } - } - } -} as const; - -export const ModelWithCircularReferenceSchema = { - description: 'This is a model with one property containing a circular reference', - type: 'object', - properties: { - prop: { - '$ref': '#/definitions/ModelWithCircularReference' - } - } -} as const; - -export const ModelWithPropertiesSchema = { - description: 'This is a model with one nested property', - type: 'object', - required: ['required', 'requiredAndReadOnly'], - properties: { - required: { - type: 'string' - }, - requiredAndReadOnly: { - type: 'string', - readOnly: true - }, - string: { - type: 'string' - }, - number: { - type: 'number' - }, - boolean: { - type: 'boolean' - }, - reference: { - '$ref': '#/definitions/ModelWithString' - }, - 'property with space': { - type: 'string' - }, - default: { - type: 'string' - }, - try: { - type: 'string' - }, - '@namespace.string': { - type: 'string', - readOnly: true - }, - '@namespace.integer': { - type: 'integer', - readOnly: true - } - } -} as const; - -export const ModelWithNestedPropertiesSchema = { - description: 'This is a model with one nested property', - type: 'object', - required: ['first'], - properties: { - first: { - type: 'object', - required: ['second'], - readOnly: true, - properties: { - second: { - type: 'object', - required: ['third'], - readOnly: true, - properties: { - third: { - type: 'string', - readOnly: true - } - } - } - } - } - } -} as const; - -export const ModelWithDuplicatePropertiesSchema = { - description: 'This is a model with duplicated properties', - type: 'object', - properties: { - prop: { - '$ref': '#/definitions/ModelWithString' - } - } -} as const; - -export const ModelWithOrderedPropertiesSchema = { - description: 'This is a model with ordered properties', - type: 'object', - properties: { - zebra: { - type: 'string' - }, - apple: { - type: 'string' - }, - hawaii: { - type: 'string' - } - } -} as const; - -export const ModelWithDuplicateImportsSchema = { - description: 'This is a model with duplicated imports', - type: 'object', - properties: { - propA: { - '$ref': '#/definitions/ModelWithString' - }, - propB: { - '$ref': '#/definitions/ModelWithString' - }, - propC: { - '$ref': '#/definitions/ModelWithString' - } - } -} as const; - -export const ModelThatExtendsSchema = { - description: 'This is a model that extends another model', - type: 'object', - allOf: [ - { - '$ref': '#/definitions/ModelWithString' - }, - { - type: 'object', - properties: { - propExtendsA: { - type: 'string' - }, - propExtendsB: { - '$ref': '#/definitions/ModelWithString' - } - } - } - ] -} as const; - -export const ModelThatExtendsExtendsSchema = { - description: 'This is a model that extends another model', - type: 'object', - allOf: [ - { - '$ref': '#/definitions/ModelWithString' - }, - { - '$ref': '#/definitions/ModelThatExtends' - }, - { - type: 'object', - properties: { - propExtendsC: { - type: 'string' - }, - propExtendsD: { - '$ref': '#/definitions/ModelWithString' - } - } - } - ] -} as const; - -export const defaultSchema = { - type: 'object', - properties: { - name: { - type: 'string' - } - } -} as const; - -export const ModelWithPatternSchema = { - description: 'This is a model that contains a some patterns', - type: 'object', - required: ['key', 'name'], - properties: { - key: { - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$', - type: 'string' - }, - name: { - maxLength: 255, - type: 'string' - }, - enabled: { - type: 'boolean', - readOnly: true - }, - modified: { - type: 'string', - format: 'date-time', - readOnly: true - }, - id: { - type: 'string', - pattern: '^\\d{2}-\\d{3}-\\d{4}$' - }, - text: { - type: 'string', - pattern: '^\\w+$' - }, - patternWithSingleQuotes: { - type: 'string', - pattern: "^[a-zA-Z0-9']*$" - }, - patternWithNewline: { - type: 'string', - pattern: 'aaa\\nbbb' - }, - patternWithBacktick: { - type: 'string', - pattern: 'aaa`bbb' - } - } -} as const; - -export const parameter_ActivityParamsSchema = { - type: 'object', - properties: { - description: { - type: 'string' - }, - graduate_id: { - type: 'integer' - }, - organization_id: { - type: 'integer' - }, - parent_activity: { - type: 'integer' - }, - post_id: { - type: 'integer' - } - } -} as const; - -export const response_PostActivityResponseSchema = { - type: 'object', - properties: { - description: { - type: 'string' - }, - graduate_id: { - type: 'integer' - }, - organization_id: { - type: 'integer' - }, - parent_activity_id: { - type: 'integer' - }, - post_id: { - type: 'integer' - } - } -} as const; - -export const failure_FailureSchema = { - type: 'object', - properties: { - error: { - type: 'string' - }, - message: { - type: 'string' - }, - reference_code: { - type: 'string' - } - } -} as const; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/sdk.gen.ts.snap deleted file mode 100644 index ea2b89213..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/sdk.gen.ts.snap +++ /dev/null @@ -1,635 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, PatchApiNoTagResponse, FooWowResponse, PostApiBodyData, PostApiBodyResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, CallWithResultFromHeaderResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, CallWithParametersData, CallWithWeirdParameterNamesData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, TypesData, TypesResponse } from './types.gen'; - -export class CollectionFormat { - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public static collectionFormat(data: CollectionFormatData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -export class Complex { - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public static complexTypes(data: ComplexTypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class Default { - /** - * @throws ApiError - */ - public static serviceWithEmptyTag(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static patchApiNoTag(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static fooWow(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * Body should not be unknown - * Body should not be unknown - * @param data The data for the request. - * @param data.request Body should not be unknown - * @returns response_PostActivityResponse OK - * @throws ApiError - */ - public static postApiBody(data: PostApiBodyData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/body', - body: data.request, - errors: { - 400: 'Bad Request', - 500: 'Internal Server Error' - } - }); - } -} - -export class Defaults { - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(data: CallWithDefaultParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -export class Descriptions { - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public static callWithDescriptions(data: CallWithDescriptionsData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -export class Duplicate { - /** - * @throws ApiError - */ - public static duplicateName(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName1(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName2(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName3(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -export class Error { - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public static testErrorCode(data: TestErrorCodeData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -export class Header { - /** - * @returns string Successful response - * @throws ApiError - */ - public static callWithResultFromHeader(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class MultipleTags1 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags2 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags3 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class NoContent { - /** - * @returns void Success - * @throws ApiError - */ - public static callWithNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns unknown Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -export class NonAsciiÆøåÆøÅöôêÊ { - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public static nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } -} - -export class Parameters { - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.parameterQuery This is the parameter that goes into the query params - * @param data.parameterForm This is the parameter that goes into the form data - * @param data.parameterPath This is the parameter that goes into the path - * @throws ApiError - */ - public static callWithParameters(data: CallWithParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - parameterQuery: data.parameterQuery - }, - formData: { - parameterForm: data.parameterForm - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterBody This is the parameter that is sent as request body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public static callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.parameterBody - }); - } -} - -export class Response { - /** - * @returns unknown Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns ModelWithString Message for default response - * @throws ApiError - */ - public static callWithResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public static callWithDuplicateResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public static callWithResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -export class Simple { - /** - * @throws ApiError - */ - public static getCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static putCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static postCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static deleteCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static optionsCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static headCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static patchCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -export class Types { - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public static types(data: TypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum - } - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/types.gen.ts.snap deleted file mode 100644 index 9c4bd8d19..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v2/types.gen.ts.snap +++ /dev/null @@ -1,777 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _default = { - name?: string; -}; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - foo?: string; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a type-only model that defines Date as a string - */ -export type Date = string; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type failure_Failure = { - error?: string; - message?: string; - reference_code?: string; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - test?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum test { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: string; - }; - }; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp: (string) | null; -}; - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -export type parameter_ActivityParams = { - description?: string; - graduate_id?: number; - organization_id?: number; - parent_activity?: number; - post_id?: number; -}; - -export type response_PostActivityResponse = { - description?: string; - graduate_id?: number; - organization_id?: number; - parent_activity_id?: number; - post_id?: number; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = string; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type PatchApiNoTagResponse = (unknown); - -export type FooWowResponse = (unknown); - -export type PostApiBodyData = { - /** - * Body should not be unknown - */ - request: parameter_ActivityParams; -}; - -export type PostApiBodyResponse = (response_PostActivityResponse); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean: boolean; - /** - * This is a simple enum with default value - */ - parameterEnum: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel: ModelWithString; - /** - * This is a simple number with default value - */ - parameterNumber: number; - /** - * This is a simple string with default value - */ - parameterString: string; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: string; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: string; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: string; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: string; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: string; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: string; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: string; -}; - -export type TestErrorCodeResponse = (unknown); - -export type CallWithResultFromHeaderResponse = (string); - -export type DummyAResponse = (void); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (unknown | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (NonAsciiStringæøåÆØÅöôêÊ字符串); - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the form data - */ - parameterForm: string; - /** - * This is the parameter that goes into the header - */ - parameterHeader: string; - /** - * This is the parameter that goes into the path - */ - parameterPath: string; - /** - * This is the parameter that goes into the query params - */ - parameterQuery: string; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that is sent as request body - */ - parameterBody: string; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: string; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: string; -}; - -export type CallWithResponseResponse = (ModelWithString); - -export type CallWithDuplicateResponsesResponse = (ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array; - /** - * This is a boolean parameter - */ - parameterBoolean: boolean; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: string; - }; - /** - * This is an enum parameter - */ - parameterEnum: 'Success' | 'Warning' | 'Error'; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: unknown; - /** - * This is a string parameter - */ - parameterString: string; -}; - -export type TypesResponse = (number | string | boolean | unknown); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-form/schemas.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-form/schemas.gen.ts.snap deleted file mode 100644 index 97c0d8811..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-form/schemas.gen.ts.snap +++ /dev/null @@ -1,1834 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export const _400Schema = { - type: 'string' -} as const; - -export const camelCaseCommentWithBreaksSchema = { - type: 'integer' -} as const; - -export const CommentWithBreaksSchema = { - type: 'integer' -} as const; - -export const CommentWithBackticksSchema = { - type: 'integer' -} as const; - -export const CommentWithBackticksAndQuotesSchema = { - type: 'integer' -} as const; - -export const CommentWithSlashesSchema = { - type: 'integer' -} as const; - -export const CommentWithExpressionPlaceholdersSchema = { - type: 'integer' -} as const; - -export const CommentWithQuotesSchema = { - type: 'integer' -} as const; - -export const CommentWithReservedCharactersSchema = { - type: 'integer' -} as const; - -export const SimpleIntegerSchema = { - type: 'integer' -} as const; - -export const SimpleBooleanSchema = { - type: 'boolean' -} as const; - -export const SimpleStringSchema = { - type: 'string' -} as const; - -export const NonAsciiStringæøåÆØÅöôêÊ字符串Schema = { - type: 'string' -} as const; - -export const SimpleFileSchema = { - type: 'file' -} as const; - -export const SimpleReferenceSchema = { - '$ref': '#/components/schemas/ModelWithString' -} as const; - -export const SimpleStringWithPatternSchema = { - type: 'string', - nullable: true, - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$' -} as const; - -export const EnumWithStringsSchema = { - enum: ['Success', 'Warning', 'Error', "'Single Quote'", '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串'] -} as const; - -export const EnumWithReplacedCharactersSchema = { - enum: ["'Single Quote'", '"Double Quotes"', 'øæåôöØÆÅÔÖ字符串', 3.1, ''], - type: 'string' -} as const; - -export const EnumWithNumbersSchema = { - enum: [1, 2, 3, 1.1, 1.2, 1.3, 100, 200, 300, -100, -200, -300, -1.1, -1.2, -1.3], - default: 200 -} as const; - -export const EnumFromDescriptionSchema = { - type: 'number' -} as const; - -export const EnumWithExtensionsSchema = { - enum: [200, 400, 500] -} as const; - -export const EnumWithXEnumNamesSchema = { - enum: [0, 1, 2] -} as const; - -export const ArrayWithNumbersSchema = { - type: 'array', - items: { - type: 'integer' - } -} as const; - -export const ArrayWithBooleansSchema = { - type: 'array', - items: { - type: 'boolean' - } -} as const; - -export const ArrayWithStringsSchema = { - type: 'array', - items: { - type: 'string' - }, - default: ['test'] -} as const; - -export const ArrayWithReferencesSchema = { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } -} as const; - -export const ArrayWithArraySchema = { - type: 'array', - items: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const ArrayWithPropertiesSchema = { - type: 'array', - items: { - type: 'object', - properties: { - '16x16': { - '$ref': '#/components/schemas/camelCaseCommentWithBreaks' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const ArrayWithAnyOfPropertiesSchema = { - type: 'array', - items: { - anyOf: [ - { - type: 'object', - properties: { - foo: { - type: 'string', - default: 'test' - } - } - }, - { - type: 'object', - properties: { - bar: { - type: 'string' - } - } - } - ] - } -} as const; - -export const AnyOfAnyAndNullSchema = { - type: 'object', - properties: { - data: { - anyOf: [ - {}, - { - type: 'null' - } - ] - } - } -} as const; - -export const AnyOfArraysSchema = { - type: 'object', - properties: { - results: { - items: { - anyOf: [ - { - type: 'object', - properties: { - foo: { - type: 'string' - } - } - }, - { - type: 'object', - properties: { - bar: { - type: 'string' - } - } - } - ] - }, - type: 'array' - } - } -} as const; - -export const DictionaryWithStringSchema = { - type: 'object', - additionalProperties: { - type: 'string' - } -} as const; - -export const DictionaryWithPropertiesAndAdditionalPropertiesSchema = { - type: 'object', - properties: { - foo: { - type: 'number' - }, - bar: { - type: 'boolean' - } - }, - additionalProperties: { - type: 'string' - } -} as const; - -export const DictionaryWithReferenceSchema = { - type: 'object', - additionalProperties: { - '$ref': '#/components/schemas/ModelWithString' - } -} as const; - -export const DictionaryWithArraySchema = { - type: 'object', - additionalProperties: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const DictionaryWithDictionarySchema = { - type: 'object', - additionalProperties: { - type: 'object', - additionalProperties: { - type: 'string' - } - } -} as const; - -export const DictionaryWithPropertiesSchema = { - type: 'object', - additionalProperties: { - type: 'object', - properties: { - foo: { - type: 'string' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const ModelWithIntegerSchema = { - type: 'object', - properties: { - prop: { - type: 'integer' - } - } -} as const; - -export const ModelWithBooleanSchema = { - type: 'object', - properties: { - prop: { - type: 'boolean' - } - } -} as const; - -export const ModelWithStringSchema = { - type: 'object', - properties: { - prop: { - type: 'string' - } - } -} as const; - -export const ModelWithStringErrorSchema = { - type: 'object', - properties: { - prop: { - type: 'string' - } - } -} as const; - -export const Model_From_ZendeskSchema = { - type: 'string' -} as const; - -export const ModelWithNullableStringSchema = { - type: 'object', - required: ['nullableRequiredProp1', 'nullableRequiredProp2'], - properties: { - nullableProp1: { - type: 'string', - nullable: true - }, - nullableRequiredProp1: { - type: 'string', - nullable: true - }, - nullableProp2: { - type: ['string', 'null'] - }, - nullableRequiredProp2: { - type: ['string', 'null'] - }, - 'foo_bar-enum': { - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - } - } -} as const; - -export const ModelWithEnumSchema = { - type: 'object', - properties: { - 'foo_bar-enum': { - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - }, - statusCode: { - enum: ['100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar'] - }, - bool: { - type: 'boolean', - enum: [true] - } - } -} as const; - -export const ModelWithEnumWithHyphenSchema = { - type: 'object', - properties: { - 'foo-bar-baz-qux': { - type: 'string', - enum: ['3.0'], - default: '3.0' - } - } -} as const; - -export const ModelWithEnumFromDescriptionSchema = { - type: 'object', - properties: { - test: { - type: 'integer' - } - } -} as const; - -export const ModelWithNestedEnumsSchema = { - type: 'object', - properties: { - dictionaryWithEnum: { - type: 'object', - additionalProperties: { - enum: ['Success', 'Warning', 'Error'] - } - }, - dictionaryWithEnumFromDescription: { - type: 'object', - additionalProperties: { - type: 'integer' - } - }, - arrayWithEnum: { - type: 'array', - items: { - enum: ['Success', 'Warning', 'Error'] - } - }, - arrayWithDescription: { - type: 'array', - items: { - type: 'integer' - } - }, - 'foo_bar-enum': { - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - } - } -} as const; - -export const ModelWithReferenceSchema = { - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithProperties' - } - } -} as const; - -export const ModelWithArrayReadOnlyAndWriteOnlySchema = { - type: 'object', - properties: { - prop: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithReadOnlyAndWriteOnly' - } - }, - propWithFile: { - type: 'array', - items: { - type: 'file' - } - }, - propWithNumber: { - type: 'array', - items: { - type: 'number' - } - } - } -} as const; - -export const ModelWithArraySchema = { - type: 'object', - properties: { - prop: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - }, - propWithFile: { - type: 'array', - items: { - type: 'file' - } - }, - propWithNumber: { - type: 'array', - items: { - type: 'number' - } - } - } -} as const; - -export const ModelWithDictionarySchema = { - type: 'object', - properties: { - prop: { - type: 'object', - additionalProperties: { - type: 'string' - } - } - } -} as const; - -export const DeprecatedModelSchema = { - deprecated: true, - type: 'object', - properties: { - prop: { - deprecated: true, - type: 'string' - } - } -} as const; - -export const ModelWithCircularReferenceSchema = { - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithCircularReference' - } - } -} as const; - -export const CompositionWithOneOfSchema = { - type: 'object', - properties: { - propA: { - type: 'object', - oneOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithOneOfAnonymousSchema = { - type: 'object', - properties: { - propA: { - type: 'object', - oneOf: [ - { - type: 'object', - properties: { - propA: { - type: 'string' - } - } - }, - { - type: 'string' - }, - { - type: 'integer' - } - ] - } - } -} as const; - -export const ModelCircleSchema = { - type: 'object', - required: ['kind'], - properties: { - kind: { - type: 'string' - }, - radius: { - type: 'number' - } - } -} as const; - -export const ModelSquareSchema = { - type: 'object', - required: ['kind'], - properties: { - kind: { - type: 'string' - }, - sideLength: { - type: 'number' - } - } -} as const; - -export const CompositionWithOneOfDiscriminatorSchema = { - type: 'object', - oneOf: [ - { - '$ref': '#/components/schemas/ModelCircle' - }, - { - '$ref': '#/components/schemas/ModelSquare' - } - ], - discriminator: { - propertyName: 'kind', - mapping: { - circle: '#/components/schemas/ModelCircle', - square: '#/components/schemas/ModelSquare' - } - } -} as const; - -export const CompositionWithAnyOfSchema = { - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithAnyOfAnonymousSchema = { - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - type: 'object', - properties: { - propA: { - type: 'string' - } - } - }, - { - type: 'string' - }, - { - type: 'integer' - } - ] - } - } -} as const; - -export const CompositionWithNestedAnyAndTypeNullSchema = { - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithDictionary' - }, - { - type: 'null' - } - ] - }, - type: 'array' - }, - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - type: 'null' - } - ] - }, - type: 'array' - } - ] - } - } -} as const; - -export const _3e_num_1ПериодSchema = { - enum: ['Bird', 'Dog'], - type: 'string' -} as const; - -export const ConstValueSchema = { - type: 'string', - const: 'ConstValue' -} as const; - -export const CompositionWithNestedAnyOfAndNullSchema = { - type: 'object', - properties: { - propA: { - anyOf: [ - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/3e-num_1Период' - }, - { - '$ref': '#/components/schemas/ConstValue' - } - ] - }, - type: 'array' - }, - { - type: 'null' - } - ] - } - } -} as const; - -export const CompositionWithOneOfAndNullableSchema = { - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - oneOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithOneOfAndSimpleDictionarySchema = { - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'number' - } - } - ] - } - } -} as const; - -export const CompositionWithOneOfAndSimpleArrayDictionarySchema = { - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'array', - items: { - type: 'boolean' - } - } - } - ] - } - } -} as const; - -export const CompositionWithOneOfAndComplexArrayDictionarySchema = { - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - } - } - } - ] - } - } -} as const; - -export const CompositionWithAllOfAndNullableSchema = { - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - allOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithAnyOfAndNullableSchema = { - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - anyOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionBaseModelSchema = { - type: 'object', - properties: { - firstName: { - type: 'string' - }, - lastname: { - type: 'string' - } - } -} as const; - -export const CompositionExtendedModelSchema = { - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/CompositionBaseModel' - } - ], - properties: { - age: { - type: 'number' - } - }, - required: ['firstName', 'lastname', 'age'] -} as const; - -export const ModelWithPropertiesSchema = { - type: 'object', - required: ['required', 'requiredAndReadOnly', 'requiredAndNullable'], - properties: { - required: { - type: 'string' - }, - requiredAndReadOnly: { - type: 'string', - readOnly: true - }, - requiredAndNullable: { - type: 'string', - nullable: true - }, - string: { - type: 'string' - }, - number: { - type: 'number' - }, - boolean: { - type: 'boolean' - }, - reference: { - '$ref': '#/components/schemas/ModelWithString' - }, - 'property with space': { - type: 'string' - }, - default: { - type: 'string' - }, - try: { - type: 'string' - }, - '@namespace.string': { - type: 'string', - readOnly: true - }, - '@namespace.integer': { - type: 'integer', - readOnly: true - } - } -} as const; - -export const ModelWithNestedPropertiesSchema = { - type: 'object', - required: ['first'], - properties: { - first: { - type: 'object', - required: ['second'], - readOnly: true, - nullable: true, - properties: { - second: { - type: 'object', - required: ['third'], - readOnly: true, - nullable: true, - properties: { - third: { - type: 'string', - required: true, - readOnly: true, - nullable: true - } - } - } - } - } - } -} as const; - -export const ModelWithDuplicatePropertiesSchema = { - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const ModelWithOrderedPropertiesSchema = { - type: 'object', - properties: { - zebra: { - type: 'string' - }, - apple: { - type: 'string' - }, - hawaii: { - type: 'string' - } - } -} as const; - -export const ModelWithDuplicateImportsSchema = { - type: 'object', - properties: { - propA: { - '$ref': '#/components/schemas/ModelWithString' - }, - propB: { - '$ref': '#/components/schemas/ModelWithString' - }, - propC: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const ModelThatExtendsSchema = { - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - type: 'object', - properties: { - propExtendsA: { - type: 'string' - }, - propExtendsB: { - '$ref': '#/components/schemas/ModelWithString' - } - } - } - ] -} as const; - -export const ModelThatExtendsExtendsSchema = { - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelThatExtends' - }, - { - type: 'object', - properties: { - propExtendsC: { - type: 'string' - }, - propExtendsD: { - '$ref': '#/components/schemas/ModelWithString' - } - } - } - ] -} as const; - -export const ModelWithPatternSchema = { - type: 'object', - required: ['key', 'name'], - properties: { - key: { - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$', - type: 'string' - }, - name: { - maxLength: 255, - type: 'string' - }, - enabled: { - type: 'boolean', - readOnly: true - }, - modified: { - type: 'string', - format: 'date-time', - readOnly: true - }, - id: { - type: 'string', - pattern: '^\\d{2}-\\d{3}-\\d{4}$' - }, - text: { - type: 'string', - pattern: '^\\w+$' - }, - patternWithSingleQuotes: { - type: 'string', - pattern: "^[a-zA-Z0-9']*$" - }, - patternWithNewline: { - type: 'string', - pattern: 'aaa\\nbbb' - }, - patternWithBacktick: { - type: 'string', - pattern: 'aaa`bbb' - } - } -} as const; - -export const FileSchema = { - required: ['mime'], - type: 'object', - properties: { - id: { - type: 'string', - readOnly: true, - minLength: 1 - }, - updated_at: { - type: 'string', - format: 'date-time', - readOnly: true - }, - created_at: { - type: 'string', - format: 'date-time', - readOnly: true - }, - mime: { - type: 'string', - maxLength: 24, - minLength: 1 - }, - file: { - type: 'string', - readOnly: true, - format: 'uri' - } - } -} as const; - -export const defaultSchema = { - type: 'object', - properties: { - name: { - type: 'string' - } - } -} as const; - -export const PageableSchema = { - type: 'object', - properties: { - page: { - minimum: 0, - type: 'integer', - format: 'int32', - default: 0 - }, - size: { - minimum: 1, - type: 'integer', - format: 'int32' - }, - sort: { - type: 'array', - items: { - type: 'string' - } - } - } -} as const; - -export const FreeFormObjectWithoutAdditionalPropertiesSchema = { - type: 'object' -} as const; - -export const FreeFormObjectWithAdditionalPropertiesEqTrueSchema = { - type: 'object', - additionalProperties: true -} as const; - -export const FreeFormObjectWithAdditionalPropertiesEqEmptyObjectSchema = { - type: 'object', - additionalProperties: {} -} as const; - -export const ModelWithConstSchema = { - type: 'object', - properties: { - String: { - const: 'String' - }, - number: { - const: 0 - }, - null: { - const: null - }, - withType: { - type: 'string', - const: 'Some string' - } - } -} as const; - -export const ModelWithAdditionalPropertiesEqTrueSchema = { - type: 'object', - properties: { - prop: { - type: 'string' - } - }, - additionalProperties: true -} as const; - -export const NestedAnyOfArraysNullableSchema = { - properties: { - nullableArray: { - anyOf: [ - { - items: { - anyOf: [ - { - type: 'string' - }, - { - type: 'boolean' - } - ] - }, - type: 'array' - }, - { - type: 'null' - } - ] - } - }, - type: 'object' -} as const; - -export const CompositionWithOneOfAndPropertiesSchema = { - type: 'object', - oneOf: [ - { - type: 'object', - required: ['foo'], - properties: { - foo: { - '$ref': '#/components/parameters/SimpleParameter' - } - }, - additionalProperties: false - }, - { - type: 'object', - required: ['bar'], - properties: { - bar: { - '$ref': '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' - } - }, - additionalProperties: false - } - ], - required: ['baz', 'qux'], - properties: { - baz: { - type: 'integer', - format: 'uint16', - minimum: 0, - nullable: true - }, - qux: { - type: 'integer', - format: 'uint8', - minimum: 0 - } - } -} as const; - -export const NullableObjectSchema = { - type: ['object', 'null'], - properties: { - foo: { - type: 'string' - } - }, - default: null -} as const; - -export const CharactersInDescriptionSchema = { - type: 'string' -} as const; - -export const ModelWithNullableObjectSchema = { - type: 'object', - properties: { - data: { - '$ref': '#/components/schemas/NullableObject' - } - } -} as const; - -export const ModelWithOneOfEnumSchema = { - oneOf: [ - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Bar'] - } - } - }, - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Baz'] - } - } - }, - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Qux'] - } - } - }, - { - type: 'object', - required: ['content', 'foo'], - properties: { - content: { - type: 'string', - format: 'date-time' - }, - foo: { - type: 'string', - enum: ['Quux'] - } - } - }, - { - type: 'object', - required: ['content', 'foo'], - properties: { - content: { - type: 'array', - items: [ - { - type: 'string', - format: 'date-time' - }, - { - type: 'string' - } - ], - maxItems: 2, - minItems: 2 - }, - foo: { - type: 'string', - enum: ['Corge'] - } - } - } - ] -} as const; - -export const ModelWithNestedArrayEnumsDataFooSchema = { - enum: ['foo', 'bar'], - type: 'string' -} as const; - -export const ModelWithNestedArrayEnumsDataBarSchema = { - enum: ['baz', 'qux'], - type: 'string' -} as const; - -export const ModelWithNestedArrayEnumsDataSchema = { - type: 'object', - properties: { - foo: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' - } - }, - bar: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataBar' - } - } - } -} as const; - -export const ModelWithNestedArrayEnumsSchema = { - type: 'object', - properties: { - array_strings: { - type: 'array', - items: { - type: 'string' - } - }, - data: { - allOf: [ - { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsData' - } - ] - } - } -} as const; - -export const ModelWithNestedCompositionEnumsSchema = { - type: 'object', - properties: { - foo: { - allOf: [ - { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' - } - ] - } - } -} as const; - -export const ModelWithReadOnlyAndWriteOnlySchema = { - type: 'object', - required: ['foo', 'bar', 'baz'], - properties: { - foo: { - type: 'string' - }, - bar: { - readOnly: true, - type: 'string' - }, - baz: { - type: 'string', - writeOnly: true - } - } -} as const; - -export const ModelWithConstantSizeArraySchema = { - type: 'array', - items: { - type: 'number' - }, - minItems: 2, - maxItems: 2 -} as const; - -export const ModelWithAnyOfConstantSizeArraySchema = { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - minItems: 3, - maxItems: 3 -} as const; - -export const ModelWithPrefixItemsConstantSizeArraySchema = { - type: 'array', - prefixItems: [ - { - '$ref': '#/components/schemas/ModelWithInteger' - }, - { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - { - type: 'string' - } - ] -} as const; - -export const ModelWithAnyOfConstantSizeArrayNullableSchema = { - type: ['array'], - items: { - oneOf: [ - { - type: 'number', - nullable: true - }, - { - type: 'string' - } - ] - }, - minItems: 3, - maxItems: 3 -} as const; - -export const ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsSchema = { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - '$ref': '#/components/schemas/import' - } - ] - }, - minItems: 2, - maxItems: 2 -} as const; - -export const ModelWithAnyOfConstantSizeArrayAndIntersectSchema = { - type: 'array', - items: { - allOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - minItems: 2, - maxItems: 2 -} as const; - -export const ModelWithNumericEnumUnionSchema = { - type: 'object', - properties: { - value: { - type: 'number', - enum: [-10, -1, 0, 1, 3, 6, 12] - } - } -} as const; - -export const ModelWithBackticksInDescriptionSchema = { - type: 'object', - properties: { - template: { - type: 'string' - } - } -} as const; - -export const ModelWithOneOfAndPropertiesSchema = { - type: 'object', - oneOf: [ - { - '$ref': '#/components/parameters/SimpleParameter' - }, - { - '$ref': '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' - } - ], - required: ['baz', 'qux'], - properties: { - baz: { - type: 'integer', - format: 'uint16', - minimum: 0, - nullable: true - }, - qux: { - type: 'integer', - format: 'uint8', - minimum: 0 - } - } -} as const; - -export const ParameterSimpleParameterUnusedSchema = { - type: 'string' -} as const; - -export const PostServiceWithEmptyTagResponseSchema = { - type: 'string' -} as const; - -export const PostServiceWithEmptyTagResponse2Schema = { - type: 'string' -} as const; - -export const DeleteFooDataSchema = { - type: 'string' -} as const; - -export const DeleteFooData2Schema = { - type: 'string' -} as const; - -export const importSchema = { - type: 'string' -} as const; - -export const SchemaWithFormRestrictedKeysSchema = { - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - }, - object: { - type: 'object', - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - } - } - }, - array: { - type: 'array', - items: [ - { - type: 'object', - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - } - } - } - ] - } - } -} as const; - -export const io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptionsSchema = { - properties: { - preconditions: { - allOf: [ - { - '$ref': '#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions' - } - ] - } - }, - type: 'object' -} as const; - -export const io_k8s_apimachinery_pkg_apis_meta_v1_PreconditionsSchema = { - properties: { - resourceVersion: { - type: 'string' - }, - uid: { - type: 'string' - } - }, - type: 'object' -} as const; - -export const AdditionalPropertiesUnknownIssueSchema = { - type: 'object', - properties: {}, - additionalProperties: { - anyOf: [ - { - type: 'string' - }, - { - type: 'number' - } - ] - } -} as const; - -export const AdditionalPropertiesUnknownIssue2Schema = { - type: 'object', - additionalProperties: { - anyOf: [ - { - type: 'string' - }, - { - type: 'number' - } - ] - } -} as const; - -export const AdditionalPropertiesUnknownIssue3Schema = { - type: 'object', - allOf: [ - { - type: 'string' - }, - { - type: 'object', - required: ['entries'], - properties: { - entries: { - additionalProperties: { - '$ref': '#/components/schemas/AdditionalPropertiesUnknownIssue' - } - } - } - } - ] -} as const; - -export const AdditionalPropertiesIntegerIssueSchema = { - type: 'object', - required: ['value'], - properties: { - value: { - type: 'integer' - } - }, - additionalProperties: { - type: 'integer' - } -} as const; - -export const OneOfAllOfIssueSchema = { - oneOf: [ - { - allOf: [ - { - oneOf: [ - { - '$ref': '#/components/schemas/ConstValue' - }, - { - '$ref': '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' - } - ] - }, - { - '$ref': '#/components/schemas/3e-num_1Период' - } - ] - }, - { - '$ref': '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' - } - ] -} as const; - -export const Generic_Schema_Duplicate_Issue_1_System_Boolean_Schema = { - type: 'object', - properties: { - item: { - type: 'boolean' - }, - error: { - type: 'string', - nullable: true - }, - hasError: { - type: 'boolean', - readOnly: true - }, - data: { - type: 'object', - properties: {}, - additionalProperties: false - } - }, - additionalProperties: false -} as const; - -export const Generic_Schema_Duplicate_Issue_1_System_String_Schema = { - type: 'object', - properties: { - item: { - type: 'string', - nullable: true - }, - error: { - type: 'string', - nullable: true - }, - hasError: { - type: 'boolean', - readOnly: true - } - }, - additionalProperties: false -} as const; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-json/schemas.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-json/schemas.gen.ts.snap deleted file mode 100644 index 0bba7f05c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-json/schemas.gen.ts.snap +++ /dev/null @@ -1,1994 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export const _400Schema = { - description: 'Model with number-only name', - type: 'string' -} as const; - -export const camelCaseCommentWithBreaksSchema = { - description: `Testing multiline comments in string: First line -Second line - -Fourth line`, - type: 'integer' -} as const; - -export const CommentWithBreaksSchema = { - description: `Testing multiline comments in string: First line -Second line - -Fourth line`, - type: 'integer' -} as const; - -export const CommentWithBackticksSchema = { - description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work', - type: 'integer' -} as const; - -export const CommentWithBackticksAndQuotesSchema = { - description: `Testing backticks and quotes in string: \`backticks\`, 'quotes', "double quotes" and \`\`\`multiple backticks\`\`\` should work`, - type: 'integer' -} as const; - -export const CommentWithSlashesSchema = { - description: 'Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work', - type: 'integer' -} as const; - -export const CommentWithExpressionPlaceholdersSchema = { - description: 'Testing expression placeholders in string: ${expression} should work', - type: 'integer' -} as const; - -export const CommentWithQuotesSchema = { - description: `Testing quotes in string: 'single quote''' and "double quotes""" should work`, - type: 'integer' -} as const; - -export const CommentWithReservedCharactersSchema = { - description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work', - type: 'integer' -} as const; - -export const SimpleIntegerSchema = { - description: 'This is a simple number', - type: 'integer' -} as const; - -export const SimpleBooleanSchema = { - description: 'This is a simple boolean', - type: 'boolean' -} as const; - -export const SimpleStringSchema = { - description: 'This is a simple string', - type: 'string' -} as const; - -export const NonAsciiStringæøåÆØÅöôêÊ字符串Schema = { - description: 'A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串)', - type: 'string' -} as const; - -export const SimpleFileSchema = { - description: 'This is a simple file', - type: 'file' -} as const; - -export const SimpleReferenceSchema = { - description: 'This is a simple reference', - '$ref': '#/components/schemas/ModelWithString' -} as const; - -export const SimpleStringWithPatternSchema = { - description: 'This is a simple string', - type: 'string', - nullable: true, - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$' -} as const; - -export const EnumWithStringsSchema = { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', "'Single Quote'", '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串'] -} as const; - -export const EnumWithReplacedCharactersSchema = { - enum: ["'Single Quote'", '"Double Quotes"', 'øæåôöØÆÅÔÖ字符串', 3.1, ''], - type: 'string' -} as const; - -export const EnumWithNumbersSchema = { - description: 'This is a simple enum with numbers', - enum: [1, 2, 3, 1.1, 1.2, 1.3, 100, 200, 300, -100, -200, -300, -1.1, -1.2, -1.3], - default: 200 -} as const; - -export const EnumFromDescriptionSchema = { - description: 'Success=1,Warning=2,Error=3', - type: 'number' -} as const; - -export const EnumWithExtensionsSchema = { - description: 'This is a simple enum with numbers', - enum: [200, 400, 500], - 'x-enum-varnames': ['CUSTOM_SUCCESS', 'CUSTOM_WARNING', 'CUSTOM_ERROR'], - 'x-enum-descriptions': ['Used when the status of something is successful', 'Used when the status of something has a warning', 'Used when the status of something has an error'] -} as const; - -export const EnumWithXEnumNamesSchema = { - enum: [0, 1, 2], - 'x-enumNames': ['zero', 'one', 'two'] -} as const; - -export const ArrayWithNumbersSchema = { - description: 'This is a simple array with numbers', - type: 'array', - items: { - type: 'integer' - } -} as const; - -export const ArrayWithBooleansSchema = { - description: 'This is a simple array with booleans', - type: 'array', - items: { - type: 'boolean' - } -} as const; - -export const ArrayWithStringsSchema = { - description: 'This is a simple array with strings', - type: 'array', - items: { - type: 'string' - }, - default: ['test'] -} as const; - -export const ArrayWithReferencesSchema = { - description: 'This is a simple array with references', - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } -} as const; - -export const ArrayWithArraySchema = { - description: 'This is a simple array containing an array', - type: 'array', - items: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const ArrayWithPropertiesSchema = { - description: 'This is a simple array with properties', - type: 'array', - items: { - type: 'object', - properties: { - '16x16': { - '$ref': '#/components/schemas/camelCaseCommentWithBreaks' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const ArrayWithAnyOfPropertiesSchema = { - description: 'This is a simple array with any of properties', - type: 'array', - items: { - anyOf: [ - { - type: 'object', - properties: { - foo: { - type: 'string', - default: 'test' - } - } - }, - { - type: 'object', - properties: { - bar: { - type: 'string' - } - } - } - ] - } -} as const; - -export const AnyOfAnyAndNullSchema = { - type: 'object', - properties: { - data: { - anyOf: [ - {}, - { - type: 'null' - } - ] - } - } -} as const; - -export const AnyOfArraysSchema = { - description: 'This is a simple array with any of properties', - type: 'object', - properties: { - results: { - items: { - anyOf: [ - { - type: 'object', - properties: { - foo: { - type: 'string' - } - } - }, - { - type: 'object', - properties: { - bar: { - type: 'string' - } - } - } - ] - }, - type: 'array' - } - } -} as const; - -export const DictionaryWithStringSchema = { - description: 'This is a string dictionary', - type: 'object', - additionalProperties: { - type: 'string' - } -} as const; - -export const DictionaryWithPropertiesAndAdditionalPropertiesSchema = { - type: 'object', - properties: { - foo: { - type: 'number' - }, - bar: { - type: 'boolean' - } - }, - additionalProperties: { - type: 'string' - } -} as const; - -export const DictionaryWithReferenceSchema = { - description: 'This is a string reference', - type: 'object', - additionalProperties: { - '$ref': '#/components/schemas/ModelWithString' - } -} as const; - -export const DictionaryWithArraySchema = { - description: 'This is a complex dictionary', - type: 'object', - additionalProperties: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const DictionaryWithDictionarySchema = { - description: 'This is a string dictionary', - type: 'object', - additionalProperties: { - type: 'object', - additionalProperties: { - type: 'string' - } - } -} as const; - -export const DictionaryWithPropertiesSchema = { - description: 'This is a complex dictionary', - type: 'object', - additionalProperties: { - type: 'object', - properties: { - foo: { - type: 'string' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const ModelWithIntegerSchema = { - description: 'This is a model with one number property', - type: 'object', - properties: { - prop: { - description: 'This is a simple number property', - type: 'integer' - } - } -} as const; - -export const ModelWithBooleanSchema = { - description: 'This is a model with one boolean property', - type: 'object', - properties: { - prop: { - description: 'This is a simple boolean property', - type: 'boolean' - } - } -} as const; - -export const ModelWithStringSchema = { - description: 'This is a model with one string property', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - } -} as const; - -export const ModelWithStringErrorSchema = { - description: 'This is a model with one string property', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - } -} as const; - -export const Model_From_ZendeskSchema = { - description: `\`Comment\` or \`VoiceComment\`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets)`, - type: 'string' -} as const; - -export const ModelWithNullableStringSchema = { - description: 'This is a model with one string property', - type: 'object', - required: ['nullableRequiredProp1', 'nullableRequiredProp2'], - properties: { - nullableProp1: { - description: 'This is a simple string property', - type: 'string', - nullable: true - }, - nullableRequiredProp1: { - description: 'This is a simple string property', - type: 'string', - nullable: true - }, - nullableProp2: { - description: 'This is a simple string property', - type: ['string', 'null'] - }, - nullableRequiredProp2: { - description: 'This is a simple string property', - type: ['string', 'null'] - }, - 'foo_bar-enum': { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - } - } -} as const; - -export const ModelWithEnumSchema = { - description: 'This is a model with one enum', - type: 'object', - properties: { - 'foo_bar-enum': { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - }, - statusCode: { - description: 'These are the HTTP error code enums', - enum: ['100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar'] - }, - bool: { - description: 'Simple boolean enum', - type: 'boolean', - enum: [true] - } - } -} as const; - -export const ModelWithEnumWithHyphenSchema = { - description: 'This is a model with one enum with escaped name', - type: 'object', - properties: { - 'foo-bar-baz-qux': { - type: 'string', - enum: ['3.0'], - title: 'Foo-Bar-Baz-Qux', - default: '3.0' - } - } -} as const; - -export const ModelWithEnumFromDescriptionSchema = { - description: 'This is a model with one enum', - type: 'object', - properties: { - test: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - } -} as const; - -export const ModelWithNestedEnumsSchema = { - description: 'This is a model with nested enums', - type: 'object', - properties: { - dictionaryWithEnum: { - type: 'object', - additionalProperties: { - enum: ['Success', 'Warning', 'Error'] - } - }, - dictionaryWithEnumFromDescription: { - type: 'object', - additionalProperties: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - }, - arrayWithEnum: { - type: 'array', - items: { - enum: ['Success', 'Warning', 'Error'] - } - }, - arrayWithDescription: { - type: 'array', - items: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - }, - 'foo_bar-enum': { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - } - } -} as const; - -export const ModelWithReferenceSchema = { - description: 'This is a model with one property containing a reference', - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithProperties' - } - } -} as const; - -export const ModelWithArrayReadOnlyAndWriteOnlySchema = { - description: 'This is a model with one property containing an array', - type: 'object', - properties: { - prop: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithReadOnlyAndWriteOnly' - } - }, - propWithFile: { - type: 'array', - items: { - type: 'file' - } - }, - propWithNumber: { - type: 'array', - items: { - type: 'number' - } - } - } -} as const; - -export const ModelWithArraySchema = { - description: 'This is a model with one property containing an array', - type: 'object', - properties: { - prop: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - }, - propWithFile: { - type: 'array', - items: { - type: 'file' - } - }, - propWithNumber: { - type: 'array', - items: { - type: 'number' - } - } - } -} as const; - -export const ModelWithDictionarySchema = { - description: 'This is a model with one property containing a dictionary', - type: 'object', - properties: { - prop: { - type: 'object', - additionalProperties: { - type: 'string' - } - } - } -} as const; - -export const DeprecatedModelSchema = { - deprecated: true, - description: 'This is a deprecated model with a deprecated property', - type: 'object', - properties: { - prop: { - deprecated: true, - description: 'This is a deprecated property', - type: 'string' - } - } -} as const; - -export const ModelWithCircularReferenceSchema = { - description: 'This is a model with one property containing a circular reference', - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithCircularReference' - } - } -} as const; - -export const CompositionWithOneOfSchema = { - description: "This is a model with one property with a 'one of' relationship", - type: 'object', - properties: { - propA: { - type: 'object', - oneOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithOneOfAnonymousSchema = { - description: "This is a model with one property with a 'one of' relationship where the options are not $ref", - type: 'object', - properties: { - propA: { - type: 'object', - oneOf: [ - { - description: 'Anonymous object type', - type: 'object', - properties: { - propA: { - type: 'string' - } - } - }, - { - description: 'Anonymous string type', - type: 'string' - }, - { - description: 'Anonymous integer type', - type: 'integer' - } - ] - } - } -} as const; - -export const ModelCircleSchema = { - description: 'Circle', - type: 'object', - required: ['kind'], - properties: { - kind: { - type: 'string' - }, - radius: { - type: 'number' - } - } -} as const; - -export const ModelSquareSchema = { - description: 'Square', - type: 'object', - required: ['kind'], - properties: { - kind: { - type: 'string' - }, - sideLength: { - type: 'number' - } - } -} as const; - -export const CompositionWithOneOfDiscriminatorSchema = { - description: "This is a model with one property with a 'one of' relationship where the options are not $ref", - type: 'object', - oneOf: [ - { - '$ref': '#/components/schemas/ModelCircle' - }, - { - '$ref': '#/components/schemas/ModelSquare' - } - ], - discriminator: { - propertyName: 'kind', - mapping: { - circle: '#/components/schemas/ModelCircle', - square: '#/components/schemas/ModelSquare' - } - } -} as const; - -export const CompositionWithAnyOfSchema = { - description: "This is a model with one property with a 'any of' relationship", - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithAnyOfAnonymousSchema = { - description: "This is a model with one property with a 'any of' relationship where the options are not $ref", - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - description: 'Anonymous object type', - type: 'object', - properties: { - propA: { - type: 'string' - } - } - }, - { - description: 'Anonymous string type', - type: 'string' - }, - { - description: 'Anonymous integer type', - type: 'integer' - } - ] - } - } -} as const; - -export const CompositionWithNestedAnyAndTypeNullSchema = { - description: "This is a model with nested 'any of' property with a type null", - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithDictionary' - }, - { - type: 'null' - } - ] - }, - type: 'array' - }, - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - type: 'null' - } - ] - }, - type: 'array' - } - ] - } - } -} as const; - -export const _3e_num_1ПериодSchema = { - enum: ['Bird', 'Dog'], - type: 'string' -} as const; - -export const ConstValueSchema = { - type: 'string', - const: 'ConstValue' -} as const; - -export const CompositionWithNestedAnyOfAndNullSchema = { - description: "This is a model with one property with a 'any of' relationship where the options are not $ref", - type: 'object', - properties: { - propA: { - anyOf: [ - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/3e-num_1Период' - }, - { - '$ref': '#/components/schemas/ConstValue' - } - ] - }, - type: 'array' - }, - { - type: 'null' - } - ], - title: 'Scopes' - } - } -} as const; - -export const CompositionWithOneOfAndNullableSchema = { - description: "This is a model with one property with a 'one of' relationship", - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - oneOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithOneOfAndSimpleDictionarySchema = { - description: 'This is a model that contains a simple dictionary within composition', - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'number' - } - } - ] - } - } -} as const; - -export const CompositionWithOneOfAndSimpleArrayDictionarySchema = { - description: 'This is a model that contains a dictionary of simple arrays within composition', - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'array', - items: { - type: 'boolean' - } - } - } - ] - } - } -} as const; - -export const CompositionWithOneOfAndComplexArrayDictionarySchema = { - description: 'This is a model that contains a dictionary of complex arrays (composited) within composition', - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - } - } - } - ] - } - } -} as const; - -export const CompositionWithAllOfAndNullableSchema = { - description: "This is a model with one property with a 'all of' relationship", - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - allOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionWithAnyOfAndNullableSchema = { - description: "This is a model with one property with a 'any of' relationship", - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - anyOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const CompositionBaseModelSchema = { - description: 'This is a base model with two simple optional properties', - type: 'object', - properties: { - firstName: { - type: 'string' - }, - lastname: { - type: 'string' - } - } -} as const; - -export const CompositionExtendedModelSchema = { - description: 'This is a model that extends the base model', - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/CompositionBaseModel' - } - ], - properties: { - age: { - type: 'number' - } - }, - required: ['firstName', 'lastname', 'age'] -} as const; - -export const ModelWithPropertiesSchema = { - description: 'This is a model with one nested property', - type: 'object', - required: ['required', 'requiredAndReadOnly', 'requiredAndNullable'], - properties: { - required: { - type: 'string' - }, - requiredAndReadOnly: { - type: 'string', - readOnly: true - }, - requiredAndNullable: { - type: 'string', - nullable: true - }, - string: { - type: 'string' - }, - number: { - type: 'number' - }, - boolean: { - type: 'boolean' - }, - reference: { - '$ref': '#/components/schemas/ModelWithString' - }, - 'property with space': { - type: 'string' - }, - default: { - type: 'string' - }, - try: { - type: 'string' - }, - '@namespace.string': { - type: 'string', - readOnly: true - }, - '@namespace.integer': { - type: 'integer', - readOnly: true - } - } -} as const; - -export const ModelWithNestedPropertiesSchema = { - description: 'This is a model with one nested property', - type: 'object', - required: ['first'], - properties: { - first: { - type: 'object', - required: ['second'], - readOnly: true, - nullable: true, - properties: { - second: { - type: 'object', - required: ['third'], - readOnly: true, - nullable: true, - properties: { - third: { - type: 'string', - required: true, - readOnly: true, - nullable: true - } - } - } - } - } - } -} as const; - -export const ModelWithDuplicatePropertiesSchema = { - description: 'This is a model with duplicated properties', - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const ModelWithOrderedPropertiesSchema = { - description: 'This is a model with ordered properties', - type: 'object', - properties: { - zebra: { - type: 'string' - }, - apple: { - type: 'string' - }, - hawaii: { - type: 'string' - } - } -} as const; - -export const ModelWithDuplicateImportsSchema = { - description: 'This is a model with duplicated imports', - type: 'object', - properties: { - propA: { - '$ref': '#/components/schemas/ModelWithString' - }, - propB: { - '$ref': '#/components/schemas/ModelWithString' - }, - propC: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const ModelThatExtendsSchema = { - description: 'This is a model that extends another model', - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - type: 'object', - properties: { - propExtendsA: { - type: 'string' - }, - propExtendsB: { - '$ref': '#/components/schemas/ModelWithString' - } - } - } - ] -} as const; - -export const ModelThatExtendsExtendsSchema = { - description: 'This is a model that extends another model', - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelThatExtends' - }, - { - type: 'object', - properties: { - propExtendsC: { - type: 'string' - }, - propExtendsD: { - '$ref': '#/components/schemas/ModelWithString' - } - } - } - ] -} as const; - -export const ModelWithPatternSchema = { - description: 'This is a model that contains a some patterns', - type: 'object', - required: ['key', 'name'], - properties: { - key: { - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$', - type: 'string' - }, - name: { - maxLength: 255, - type: 'string' - }, - enabled: { - type: 'boolean', - readOnly: true - }, - modified: { - type: 'string', - format: 'date-time', - readOnly: true - }, - id: { - type: 'string', - pattern: '^\\d{2}-\\d{3}-\\d{4}$' - }, - text: { - type: 'string', - pattern: '^\\w+$' - }, - patternWithSingleQuotes: { - type: 'string', - pattern: "^[a-zA-Z0-9']*$" - }, - patternWithNewline: { - type: 'string', - pattern: 'aaa\\nbbb' - }, - patternWithBacktick: { - type: 'string', - pattern: 'aaa`bbb' - } - } -} as const; - -export const FileSchema = { - required: ['mime'], - type: 'object', - properties: { - id: { - title: 'Id', - type: 'string', - readOnly: true, - minLength: 1 - }, - updated_at: { - title: 'Updated at', - type: 'string', - format: 'date-time', - readOnly: true - }, - created_at: { - title: 'Created at', - type: 'string', - format: 'date-time', - readOnly: true - }, - mime: { - title: 'Mime', - type: 'string', - maxLength: 24, - minLength: 1 - }, - file: { - title: 'File', - type: 'string', - readOnly: true, - format: 'uri' - } - } -} as const; - -export const defaultSchema = { - type: 'object', - properties: { - name: { - type: 'string' - } - } -} as const; - -export const PageableSchema = { - type: 'object', - properties: { - page: { - minimum: 0, - type: 'integer', - format: 'int32', - default: 0 - }, - size: { - minimum: 1, - type: 'integer', - format: 'int32' - }, - sort: { - type: 'array', - items: { - type: 'string' - } - } - } -} as const; - -export const FreeFormObjectWithoutAdditionalPropertiesSchema = { - description: 'This is a free-form object without additionalProperties.', - type: 'object' -} as const; - -export const FreeFormObjectWithAdditionalPropertiesEqTrueSchema = { - description: 'This is a free-form object with additionalProperties: true.', - type: 'object', - additionalProperties: true -} as const; - -export const FreeFormObjectWithAdditionalPropertiesEqEmptyObjectSchema = { - description: 'This is a free-form object with additionalProperties: {}.', - type: 'object', - additionalProperties: {} -} as const; - -export const ModelWithConstSchema = { - type: 'object', - properties: { - String: { - const: 'String' - }, - number: { - const: 0 - }, - null: { - const: null - }, - withType: { - type: 'string', - const: 'Some string' - } - } -} as const; - -export const ModelWithAdditionalPropertiesEqTrueSchema = { - description: 'This is a model with one property and additionalProperties: true', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - }, - additionalProperties: true -} as const; - -export const NestedAnyOfArraysNullableSchema = { - properties: { - nullableArray: { - anyOf: [ - { - items: { - anyOf: [ - { - type: 'string' - }, - { - type: 'boolean' - } - ] - }, - type: 'array' - }, - { - type: 'null' - } - ] - } - }, - type: 'object' -} as const; - -export const CompositionWithOneOfAndPropertiesSchema = { - type: 'object', - oneOf: [ - { - type: 'object', - required: ['foo'], - properties: { - foo: { - '$ref': '#/components/parameters/SimpleParameter' - } - }, - additionalProperties: false - }, - { - type: 'object', - required: ['bar'], - properties: { - bar: { - '$ref': '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' - } - }, - additionalProperties: false - } - ], - required: ['baz', 'qux'], - properties: { - baz: { - type: 'integer', - format: 'uint16', - minimum: 0, - nullable: true - }, - qux: { - type: 'integer', - format: 'uint8', - minimum: 0 - } - } -} as const; - -export const NullableObjectSchema = { - type: ['object', 'null'], - description: 'An object that can be null', - properties: { - foo: { - type: 'string' - } - }, - default: null -} as const; - -export const CharactersInDescriptionSchema = { - type: 'string', - description: 'Some % character' -} as const; - -export const ModelWithNullableObjectSchema = { - type: 'object', - properties: { - data: { - '$ref': '#/components/schemas/NullableObject' - } - } -} as const; - -export const ModelWithOneOfEnumSchema = { - oneOf: [ - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Bar'] - } - } - }, - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Baz'] - } - } - }, - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Qux'] - } - } - }, - { - type: 'object', - required: ['content', 'foo'], - properties: { - content: { - type: 'string', - format: 'date-time' - }, - foo: { - type: 'string', - enum: ['Quux'] - } - } - }, - { - type: 'object', - required: ['content', 'foo'], - properties: { - content: { - type: 'array', - items: [ - { - type: 'string', - format: 'date-time' - }, - { - type: 'string' - } - ], - maxItems: 2, - minItems: 2 - }, - foo: { - type: 'string', - enum: ['Corge'] - } - } - } - ] -} as const; - -export const ModelWithNestedArrayEnumsDataFooSchema = { - enum: ['foo', 'bar'], - type: 'string' -} as const; - -export const ModelWithNestedArrayEnumsDataBarSchema = { - enum: ['baz', 'qux'], - type: 'string' -} as const; - -export const ModelWithNestedArrayEnumsDataSchema = { - type: 'object', - properties: { - foo: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' - } - }, - bar: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataBar' - } - } - } -} as const; - -export const ModelWithNestedArrayEnumsSchema = { - type: 'object', - properties: { - array_strings: { - type: 'array', - items: { - type: 'string' - } - }, - data: { - allOf: [ - { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsData' - } - ] - } - } -} as const; - -export const ModelWithNestedCompositionEnumsSchema = { - type: 'object', - properties: { - foo: { - allOf: [ - { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' - } - ] - } - } -} as const; - -export const ModelWithReadOnlyAndWriteOnlySchema = { - type: 'object', - required: ['foo', 'bar', 'baz'], - properties: { - foo: { - type: 'string' - }, - bar: { - readOnly: true, - type: 'string' - }, - baz: { - type: 'string', - writeOnly: true - } - } -} as const; - -export const ModelWithConstantSizeArraySchema = { - type: 'array', - items: { - type: 'number' - }, - minItems: 2, - maxItems: 2 -} as const; - -export const ModelWithAnyOfConstantSizeArraySchema = { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - minItems: 3, - maxItems: 3 -} as const; - -export const ModelWithPrefixItemsConstantSizeArraySchema = { - type: 'array', - prefixItems: [ - { - '$ref': '#/components/schemas/ModelWithInteger' - }, - { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - { - type: 'string' - } - ] -} as const; - -export const ModelWithAnyOfConstantSizeArrayNullableSchema = { - type: ['array'], - items: { - oneOf: [ - { - type: 'number', - nullable: true - }, - { - type: 'string' - } - ] - }, - minItems: 3, - maxItems: 3 -} as const; - -export const ModelWithAnyOfConstantSizeArrayWithNSizeAndOptionsSchema = { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - '$ref': '#/components/schemas/import' - } - ] - }, - minItems: 2, - maxItems: 2 -} as const; - -export const ModelWithAnyOfConstantSizeArrayAndIntersectSchema = { - type: 'array', - items: { - allOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - minItems: 2, - maxItems: 2 -} as const; - -export const ModelWithNumericEnumUnionSchema = { - type: 'object', - properties: { - value: { - type: 'number', - description: 'Период', - enum: [-10, -1, 0, 1, 3, 6, 12] - } - } -} as const; - -export const ModelWithBackticksInDescriptionSchema = { - description: 'Some description with `back ticks`', - type: 'object', - properties: { - template: { - type: 'string', - description: `The template \`that\` should be used for parsing and importing the contents of the CSV file. - -

There is one placeholder currently supported:

  • \${x} - refers to the n-th column in the CSV file, e.g. \${1}, \${2}, ...)

Example of a correct JSON template:

-
-[
-  {
-    "resourceType": "Asset",
-    "identifier": {
-      "name": "\${1}",
-      "domain": {
-        "name": "\${2}",
-        "community": {
-          "name": "Some Community"
-        }
-      }
-    },
-    "attributes" : {
-      "00000000-0000-0000-0000-000000003115" : [ {
-        "value" : "\${3}" 
-      } ],
-      "00000000-0000-0000-0000-000000000222" : [ {
-        "value" : "\${4}"
-      } ]
-    }
-  }
-]
-
` - } - } -} as const; - -export const ModelWithOneOfAndPropertiesSchema = { - type: 'object', - oneOf: [ - { - '$ref': '#/components/parameters/SimpleParameter' - }, - { - '$ref': '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' - } - ], - required: ['baz', 'qux'], - properties: { - baz: { - type: 'integer', - format: 'uint16', - minimum: 0, - nullable: true - }, - qux: { - type: 'integer', - format: 'uint8', - minimum: 0 - } - } -} as const; - -export const ParameterSimpleParameterUnusedSchema = { - description: 'Model used to test deduplication strategy (unused)', - type: 'string' -} as const; - -export const PostServiceWithEmptyTagResponseSchema = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const PostServiceWithEmptyTagResponse2Schema = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const DeleteFooDataSchema = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const DeleteFooData2Schema = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const importSchema = { - description: 'Model with restricted keyword name', - type: 'string' -} as const; - -export const SchemaWithFormRestrictedKeysSchema = { - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - }, - object: { - type: 'object', - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - } - } - }, - array: { - type: 'array', - items: [ - { - type: 'object', - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - } - } - } - ] - } - } -} as const; - -export const io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptionsSchema = { - description: 'This schema was giving PascalCase transformations a hard time', - properties: { - preconditions: { - allOf: [ - { - '$ref': '#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions' - } - ], - description: 'Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.' - } - }, - type: 'object' -} as const; - -export const io_k8s_apimachinery_pkg_apis_meta_v1_PreconditionsSchema = { - description: 'This schema was giving PascalCase transformations a hard time', - properties: { - resourceVersion: { - description: 'Specifies the target ResourceVersion', - type: 'string' - }, - uid: { - description: 'Specifies the target UID.', - type: 'string' - } - }, - type: 'object' -} as const; - -export const AdditionalPropertiesUnknownIssueSchema = { - type: 'object', - properties: {}, - additionalProperties: { - anyOf: [ - { - type: 'string' - }, - { - type: 'number' - } - ] - } -} as const; - -export const AdditionalPropertiesUnknownIssue2Schema = { - type: 'object', - additionalProperties: { - anyOf: [ - { - type: 'string' - }, - { - type: 'number' - } - ] - } -} as const; - -export const AdditionalPropertiesUnknownIssue3Schema = { - type: 'object', - allOf: [ - { - type: 'string' - }, - { - type: 'object', - required: ['entries'], - properties: { - entries: { - additionalProperties: { - '$ref': '#/components/schemas/AdditionalPropertiesUnknownIssue' - } - } - } - } - ] -} as const; - -export const AdditionalPropertiesIntegerIssueSchema = { - type: 'object', - required: ['value'], - properties: { - value: { - type: 'integer' - } - }, - additionalProperties: { - type: 'integer' - } -} as const; - -export const OneOfAllOfIssueSchema = { - oneOf: [ - { - allOf: [ - { - oneOf: [ - { - '$ref': '#/components/schemas/ConstValue' - }, - { - '$ref': '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' - } - ] - }, - { - '$ref': '#/components/schemas/3e-num_1Период' - } - ] - }, - { - '$ref': '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' - } - ] -} as const; - -export const Generic_Schema_Duplicate_Issue_1_System_Boolean_Schema = { - type: 'object', - properties: { - item: { - type: 'boolean' - }, - error: { - type: 'string', - nullable: true - }, - hasError: { - type: 'boolean', - readOnly: true - }, - data: { - type: 'object', - properties: {}, - additionalProperties: false - } - }, - additionalProperties: false -} as const; - -export const Generic_Schema_Duplicate_Issue_1_System_String_Schema = { - type: 'object', - properties: { - item: { - type: 'string', - nullable: true - }, - error: { - type: 'string', - nullable: true - }, - hasError: { - type: 'boolean', - readOnly: true - } - }, - additionalProperties: false -} as const; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-name/schemas.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-name/schemas.gen.ts.snap deleted file mode 100644 index af93bb248..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-schemas-name/schemas.gen.ts.snap +++ /dev/null @@ -1,1994 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export const $400 = { - description: 'Model with number-only name', - type: 'string' -} as const; - -export const $camelCaseCommentWithBreaks = { - description: `Testing multiline comments in string: First line -Second line - -Fourth line`, - type: 'integer' -} as const; - -export const $CommentWithBreaks = { - description: `Testing multiline comments in string: First line -Second line - -Fourth line`, - type: 'integer' -} as const; - -export const $CommentWithBackticks = { - description: 'Testing backticks in string: `backticks` and ```multiple backticks``` should work', - type: 'integer' -} as const; - -export const $CommentWithBackticksAndQuotes = { - description: `Testing backticks and quotes in string: \`backticks\`, 'quotes', "double quotes" and \`\`\`multiple backticks\`\`\` should work`, - type: 'integer' -} as const; - -export const $CommentWithSlashes = { - description: 'Testing slashes in string: \\backwards\\\\\\ and /forwards/// should work', - type: 'integer' -} as const; - -export const $CommentWithExpressionPlaceholders = { - description: 'Testing expression placeholders in string: ${expression} should work', - type: 'integer' -} as const; - -export const $CommentWithQuotes = { - description: `Testing quotes in string: 'single quote''' and "double quotes""" should work`, - type: 'integer' -} as const; - -export const $CommentWithReservedCharacters = { - description: 'Testing reserved characters in string: /* inline */ and /** inline **/ should work', - type: 'integer' -} as const; - -export const $SimpleInteger = { - description: 'This is a simple number', - type: 'integer' -} as const; - -export const $SimpleBoolean = { - description: 'This is a simple boolean', - type: 'boolean' -} as const; - -export const $SimpleString = { - description: 'This is a simple string', - type: 'string' -} as const; - -export const $NonAsciiStringæøåÆØÅöôêÊ字符串 = { - description: 'A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串)', - type: 'string' -} as const; - -export const $SimpleFile = { - description: 'This is a simple file', - type: 'file' -} as const; - -export const $SimpleReference = { - description: 'This is a simple reference', - '$ref': '#/components/schemas/ModelWithString' -} as const; - -export const $SimpleStringWithPattern = { - description: 'This is a simple string', - type: 'string', - nullable: true, - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$' -} as const; - -export const $EnumWithStrings = { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', "'Single Quote'", '"Double Quotes"', 'Non-ascii: øæåôöØÆÅÔÖ字符串'] -} as const; - -export const $EnumWithReplacedCharacters = { - enum: ["'Single Quote'", '"Double Quotes"', 'øæåôöØÆÅÔÖ字符串', 3.1, ''], - type: 'string' -} as const; - -export const $EnumWithNumbers = { - description: 'This is a simple enum with numbers', - enum: [1, 2, 3, 1.1, 1.2, 1.3, 100, 200, 300, -100, -200, -300, -1.1, -1.2, -1.3], - default: 200 -} as const; - -export const $EnumFromDescription = { - description: 'Success=1,Warning=2,Error=3', - type: 'number' -} as const; - -export const $EnumWithExtensions = { - description: 'This is a simple enum with numbers', - enum: [200, 400, 500], - 'x-enum-varnames': ['CUSTOM_SUCCESS', 'CUSTOM_WARNING', 'CUSTOM_ERROR'], - 'x-enum-descriptions': ['Used when the status of something is successful', 'Used when the status of something has a warning', 'Used when the status of something has an error'] -} as const; - -export const $EnumWithXEnumNames = { - enum: [0, 1, 2], - 'x-enumNames': ['zero', 'one', 'two'] -} as const; - -export const $ArrayWithNumbers = { - description: 'This is a simple array with numbers', - type: 'array', - items: { - type: 'integer' - } -} as const; - -export const $ArrayWithBooleans = { - description: 'This is a simple array with booleans', - type: 'array', - items: { - type: 'boolean' - } -} as const; - -export const $ArrayWithStrings = { - description: 'This is a simple array with strings', - type: 'array', - items: { - type: 'string' - }, - default: ['test'] -} as const; - -export const $ArrayWithReferences = { - description: 'This is a simple array with references', - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } -} as const; - -export const $ArrayWithArray = { - description: 'This is a simple array containing an array', - type: 'array', - items: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const $ArrayWithProperties = { - description: 'This is a simple array with properties', - type: 'array', - items: { - type: 'object', - properties: { - '16x16': { - '$ref': '#/components/schemas/camelCaseCommentWithBreaks' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const $ArrayWithAnyOfProperties = { - description: 'This is a simple array with any of properties', - type: 'array', - items: { - anyOf: [ - { - type: 'object', - properties: { - foo: { - type: 'string', - default: 'test' - } - } - }, - { - type: 'object', - properties: { - bar: { - type: 'string' - } - } - } - ] - } -} as const; - -export const $AnyOfAnyAndNull = { - type: 'object', - properties: { - data: { - anyOf: [ - {}, - { - type: 'null' - } - ] - } - } -} as const; - -export const $AnyOfArrays = { - description: 'This is a simple array with any of properties', - type: 'object', - properties: { - results: { - items: { - anyOf: [ - { - type: 'object', - properties: { - foo: { - type: 'string' - } - } - }, - { - type: 'object', - properties: { - bar: { - type: 'string' - } - } - } - ] - }, - type: 'array' - } - } -} as const; - -export const $DictionaryWithString = { - description: 'This is a string dictionary', - type: 'object', - additionalProperties: { - type: 'string' - } -} as const; - -export const $DictionaryWithPropertiesAndAdditionalProperties = { - type: 'object', - properties: { - foo: { - type: 'number' - }, - bar: { - type: 'boolean' - } - }, - additionalProperties: { - type: 'string' - } -} as const; - -export const $DictionaryWithReference = { - description: 'This is a string reference', - type: 'object', - additionalProperties: { - '$ref': '#/components/schemas/ModelWithString' - } -} as const; - -export const $DictionaryWithArray = { - description: 'This is a complex dictionary', - type: 'object', - additionalProperties: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const $DictionaryWithDictionary = { - description: 'This is a string dictionary', - type: 'object', - additionalProperties: { - type: 'object', - additionalProperties: { - type: 'string' - } - } -} as const; - -export const $DictionaryWithProperties = { - description: 'This is a complex dictionary', - type: 'object', - additionalProperties: { - type: 'object', - properties: { - foo: { - type: 'string' - }, - bar: { - type: 'string' - } - } - } -} as const; - -export const $ModelWithInteger = { - description: 'This is a model with one number property', - type: 'object', - properties: { - prop: { - description: 'This is a simple number property', - type: 'integer' - } - } -} as const; - -export const $ModelWithBoolean = { - description: 'This is a model with one boolean property', - type: 'object', - properties: { - prop: { - description: 'This is a simple boolean property', - type: 'boolean' - } - } -} as const; - -export const $ModelWithString = { - description: 'This is a model with one string property', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - } -} as const; - -export const $ModelWithStringError = { - description: 'This is a model with one string property', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - } -} as const; - -export const $Model_From_Zendesk = { - description: `\`Comment\` or \`VoiceComment\`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets)`, - type: 'string' -} as const; - -export const $ModelWithNullableString = { - description: 'This is a model with one string property', - type: 'object', - required: ['nullableRequiredProp1', 'nullableRequiredProp2'], - properties: { - nullableProp1: { - description: 'This is a simple string property', - type: 'string', - nullable: true - }, - nullableRequiredProp1: { - description: 'This is a simple string property', - type: 'string', - nullable: true - }, - nullableProp2: { - description: 'This is a simple string property', - type: ['string', 'null'] - }, - nullableRequiredProp2: { - description: 'This is a simple string property', - type: ['string', 'null'] - }, - 'foo_bar-enum': { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - } - } -} as const; - -export const $ModelWithEnum = { - description: 'This is a model with one enum', - type: 'object', - properties: { - 'foo_bar-enum': { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - }, - statusCode: { - description: 'These are the HTTP error code enums', - enum: ['100', '200 FOO', '300 FOO_BAR', '400 foo-bar', '500 foo.bar', '600 foo&bar'] - }, - bool: { - description: 'Simple boolean enum', - type: 'boolean', - enum: [true] - } - } -} as const; - -export const $ModelWithEnumWithHyphen = { - description: 'This is a model with one enum with escaped name', - type: 'object', - properties: { - 'foo-bar-baz-qux': { - type: 'string', - enum: ['3.0'], - title: 'Foo-Bar-Baz-Qux', - default: '3.0' - } - } -} as const; - -export const $ModelWithEnumFromDescription = { - description: 'This is a model with one enum', - type: 'object', - properties: { - test: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - } -} as const; - -export const $ModelWithNestedEnums = { - description: 'This is a model with nested enums', - type: 'object', - properties: { - dictionaryWithEnum: { - type: 'object', - additionalProperties: { - enum: ['Success', 'Warning', 'Error'] - } - }, - dictionaryWithEnumFromDescription: { - type: 'object', - additionalProperties: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - }, - arrayWithEnum: { - type: 'array', - items: { - enum: ['Success', 'Warning', 'Error'] - } - }, - arrayWithDescription: { - type: 'array', - items: { - type: 'integer', - description: 'Success=1,Warning=2,Error=3' - } - }, - 'foo_bar-enum': { - description: 'This is a simple enum with strings', - enum: ['Success', 'Warning', 'Error', 'ØÆÅ字符串'] - } - } -} as const; - -export const $ModelWithReference = { - description: 'This is a model with one property containing a reference', - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithProperties' - } - } -} as const; - -export const $ModelWithArrayReadOnlyAndWriteOnly = { - description: 'This is a model with one property containing an array', - type: 'object', - properties: { - prop: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithReadOnlyAndWriteOnly' - } - }, - propWithFile: { - type: 'array', - items: { - type: 'file' - } - }, - propWithNumber: { - type: 'array', - items: { - type: 'number' - } - } - } -} as const; - -export const $ModelWithArray = { - description: 'This is a model with one property containing an array', - type: 'object', - properties: { - prop: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithString' - } - }, - propWithFile: { - type: 'array', - items: { - type: 'file' - } - }, - propWithNumber: { - type: 'array', - items: { - type: 'number' - } - } - } -} as const; - -export const $ModelWithDictionary = { - description: 'This is a model with one property containing a dictionary', - type: 'object', - properties: { - prop: { - type: 'object', - additionalProperties: { - type: 'string' - } - } - } -} as const; - -export const $DeprecatedModel = { - deprecated: true, - description: 'This is a deprecated model with a deprecated property', - type: 'object', - properties: { - prop: { - deprecated: true, - description: 'This is a deprecated property', - type: 'string' - } - } -} as const; - -export const $ModelWithCircularReference = { - description: 'This is a model with one property containing a circular reference', - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithCircularReference' - } - } -} as const; - -export const $CompositionWithOneOf = { - description: "This is a model with one property with a 'one of' relationship", - type: 'object', - properties: { - propA: { - type: 'object', - oneOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const $CompositionWithOneOfAnonymous = { - description: "This is a model with one property with a 'one of' relationship where the options are not $ref", - type: 'object', - properties: { - propA: { - type: 'object', - oneOf: [ - { - description: 'Anonymous object type', - type: 'object', - properties: { - propA: { - type: 'string' - } - } - }, - { - description: 'Anonymous string type', - type: 'string' - }, - { - description: 'Anonymous integer type', - type: 'integer' - } - ] - } - } -} as const; - -export const $ModelCircle = { - description: 'Circle', - type: 'object', - required: ['kind'], - properties: { - kind: { - type: 'string' - }, - radius: { - type: 'number' - } - } -} as const; - -export const $ModelSquare = { - description: 'Square', - type: 'object', - required: ['kind'], - properties: { - kind: { - type: 'string' - }, - sideLength: { - type: 'number' - } - } -} as const; - -export const $CompositionWithOneOfDiscriminator = { - description: "This is a model with one property with a 'one of' relationship where the options are not $ref", - type: 'object', - oneOf: [ - { - '$ref': '#/components/schemas/ModelCircle' - }, - { - '$ref': '#/components/schemas/ModelSquare' - } - ], - discriminator: { - propertyName: 'kind', - mapping: { - circle: '#/components/schemas/ModelCircle', - square: '#/components/schemas/ModelSquare' - } - } -} as const; - -export const $CompositionWithAnyOf = { - description: "This is a model with one property with a 'any of' relationship", - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const $CompositionWithAnyOfAnonymous = { - description: "This is a model with one property with a 'any of' relationship where the options are not $ref", - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - description: 'Anonymous object type', - type: 'object', - properties: { - propA: { - type: 'string' - } - } - }, - { - description: 'Anonymous string type', - type: 'string' - }, - { - description: 'Anonymous integer type', - type: 'integer' - } - ] - } - } -} as const; - -export const $CompositionWithNestedAnyAndTypeNull = { - description: "This is a model with nested 'any of' property with a type null", - type: 'object', - properties: { - propA: { - type: 'object', - anyOf: [ - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithDictionary' - }, - { - type: 'null' - } - ] - }, - type: 'array' - }, - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - type: 'null' - } - ] - }, - type: 'array' - } - ] - } - } -} as const; - -export const $3e_num_1Период = { - enum: ['Bird', 'Dog'], - type: 'string' -} as const; - -export const $ConstValue = { - type: 'string', - const: 'ConstValue' -} as const; - -export const $CompositionWithNestedAnyOfAndNull = { - description: "This is a model with one property with a 'any of' relationship where the options are not $ref", - type: 'object', - properties: { - propA: { - anyOf: [ - { - items: { - anyOf: [ - { - '$ref': '#/components/schemas/3e-num_1Период' - }, - { - '$ref': '#/components/schemas/ConstValue' - } - ] - }, - type: 'array' - }, - { - type: 'null' - } - ], - title: 'Scopes' - } - } -} as const; - -export const $CompositionWithOneOfAndNullable = { - description: "This is a model with one property with a 'one of' relationship", - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - oneOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const $CompositionWithOneOfAndSimpleDictionary = { - description: 'This is a model that contains a simple dictionary within composition', - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'number' - } - } - ] - } - } -} as const; - -export const $CompositionWithOneOfAndSimpleArrayDictionary = { - description: 'This is a model that contains a dictionary of simple arrays within composition', - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'array', - items: { - type: 'boolean' - } - } - } - ] - } - } -} as const; - -export const $CompositionWithOneOfAndComplexArrayDictionary = { - description: 'This is a model that contains a dictionary of complex arrays (composited) within composition', - type: 'object', - properties: { - propA: { - oneOf: [ - { - type: 'boolean' - }, - { - type: 'object', - additionalProperties: { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - } - } - } - ] - } - } -} as const; - -export const $CompositionWithAllOfAndNullable = { - description: "This is a model with one property with a 'all of' relationship", - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - allOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const $CompositionWithAnyOfAndNullable = { - description: "This is a model with one property with a 'any of' relationship", - type: 'object', - properties: { - propA: { - nullable: true, - type: 'object', - anyOf: [ - { - type: 'object', - properties: { - boolean: { - type: 'boolean' - } - } - }, - { - '$ref': '#/components/schemas/ModelWithEnum' - }, - { - '$ref': '#/components/schemas/ModelWithArray' - }, - { - '$ref': '#/components/schemas/ModelWithDictionary' - } - ] - } - } -} as const; - -export const $CompositionBaseModel = { - description: 'This is a base model with two simple optional properties', - type: 'object', - properties: { - firstName: { - type: 'string' - }, - lastname: { - type: 'string' - } - } -} as const; - -export const $CompositionExtendedModel = { - description: 'This is a model that extends the base model', - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/CompositionBaseModel' - } - ], - properties: { - age: { - type: 'number' - } - }, - required: ['firstName', 'lastname', 'age'] -} as const; - -export const $ModelWithProperties = { - description: 'This is a model with one nested property', - type: 'object', - required: ['required', 'requiredAndReadOnly', 'requiredAndNullable'], - properties: { - required: { - type: 'string' - }, - requiredAndReadOnly: { - type: 'string', - readOnly: true - }, - requiredAndNullable: { - type: 'string', - nullable: true - }, - string: { - type: 'string' - }, - number: { - type: 'number' - }, - boolean: { - type: 'boolean' - }, - reference: { - '$ref': '#/components/schemas/ModelWithString' - }, - 'property with space': { - type: 'string' - }, - default: { - type: 'string' - }, - try: { - type: 'string' - }, - '@namespace.string': { - type: 'string', - readOnly: true - }, - '@namespace.integer': { - type: 'integer', - readOnly: true - } - } -} as const; - -export const $ModelWithNestedProperties = { - description: 'This is a model with one nested property', - type: 'object', - required: ['first'], - properties: { - first: { - type: 'object', - required: ['second'], - readOnly: true, - nullable: true, - properties: { - second: { - type: 'object', - required: ['third'], - readOnly: true, - nullable: true, - properties: { - third: { - type: 'string', - required: true, - readOnly: true, - nullable: true - } - } - } - } - } - } -} as const; - -export const $ModelWithDuplicateProperties = { - description: 'This is a model with duplicated properties', - type: 'object', - properties: { - prop: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const $ModelWithOrderedProperties = { - description: 'This is a model with ordered properties', - type: 'object', - properties: { - zebra: { - type: 'string' - }, - apple: { - type: 'string' - }, - hawaii: { - type: 'string' - } - } -} as const; - -export const $ModelWithDuplicateImports = { - description: 'This is a model with duplicated imports', - type: 'object', - properties: { - propA: { - '$ref': '#/components/schemas/ModelWithString' - }, - propB: { - '$ref': '#/components/schemas/ModelWithString' - }, - propC: { - '$ref': '#/components/schemas/ModelWithString' - } - } -} as const; - -export const $ModelThatExtends = { - description: 'This is a model that extends another model', - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - type: 'object', - properties: { - propExtendsA: { - type: 'string' - }, - propExtendsB: { - '$ref': '#/components/schemas/ModelWithString' - } - } - } - ] -} as const; - -export const $ModelThatExtendsExtends = { - description: 'This is a model that extends another model', - type: 'object', - allOf: [ - { - '$ref': '#/components/schemas/ModelWithString' - }, - { - '$ref': '#/components/schemas/ModelThatExtends' - }, - { - type: 'object', - properties: { - propExtendsC: { - type: 'string' - }, - propExtendsD: { - '$ref': '#/components/schemas/ModelWithString' - } - } - } - ] -} as const; - -export const $ModelWithPattern = { - description: 'This is a model that contains a some patterns', - type: 'object', - required: ['key', 'name'], - properties: { - key: { - maxLength: 64, - pattern: '^[a-zA-Z0-9_]*$', - type: 'string' - }, - name: { - maxLength: 255, - type: 'string' - }, - enabled: { - type: 'boolean', - readOnly: true - }, - modified: { - type: 'string', - format: 'date-time', - readOnly: true - }, - id: { - type: 'string', - pattern: '^\\d{2}-\\d{3}-\\d{4}$' - }, - text: { - type: 'string', - pattern: '^\\w+$' - }, - patternWithSingleQuotes: { - type: 'string', - pattern: "^[a-zA-Z0-9']*$" - }, - patternWithNewline: { - type: 'string', - pattern: 'aaa\\nbbb' - }, - patternWithBacktick: { - type: 'string', - pattern: 'aaa`bbb' - } - } -} as const; - -export const $File = { - required: ['mime'], - type: 'object', - properties: { - id: { - title: 'Id', - type: 'string', - readOnly: true, - minLength: 1 - }, - updated_at: { - title: 'Updated at', - type: 'string', - format: 'date-time', - readOnly: true - }, - created_at: { - title: 'Created at', - type: 'string', - format: 'date-time', - readOnly: true - }, - mime: { - title: 'Mime', - type: 'string', - maxLength: 24, - minLength: 1 - }, - file: { - title: 'File', - type: 'string', - readOnly: true, - format: 'uri' - } - } -} as const; - -export const $default = { - type: 'object', - properties: { - name: { - type: 'string' - } - } -} as const; - -export const $Pageable = { - type: 'object', - properties: { - page: { - minimum: 0, - type: 'integer', - format: 'int32', - default: 0 - }, - size: { - minimum: 1, - type: 'integer', - format: 'int32' - }, - sort: { - type: 'array', - items: { - type: 'string' - } - } - } -} as const; - -export const $FreeFormObjectWithoutAdditionalProperties = { - description: 'This is a free-form object without additionalProperties.', - type: 'object' -} as const; - -export const $FreeFormObjectWithAdditionalPropertiesEqTrue = { - description: 'This is a free-form object with additionalProperties: true.', - type: 'object', - additionalProperties: true -} as const; - -export const $FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - description: 'This is a free-form object with additionalProperties: {}.', - type: 'object', - additionalProperties: {} -} as const; - -export const $ModelWithConst = { - type: 'object', - properties: { - String: { - const: 'String' - }, - number: { - const: 0 - }, - null: { - const: null - }, - withType: { - type: 'string', - const: 'Some string' - } - } -} as const; - -export const $ModelWithAdditionalPropertiesEqTrue = { - description: 'This is a model with one property and additionalProperties: true', - type: 'object', - properties: { - prop: { - description: 'This is a simple string property', - type: 'string' - } - }, - additionalProperties: true -} as const; - -export const $NestedAnyOfArraysNullable = { - properties: { - nullableArray: { - anyOf: [ - { - items: { - anyOf: [ - { - type: 'string' - }, - { - type: 'boolean' - } - ] - }, - type: 'array' - }, - { - type: 'null' - } - ] - } - }, - type: 'object' -} as const; - -export const $CompositionWithOneOfAndProperties = { - type: 'object', - oneOf: [ - { - type: 'object', - required: ['foo'], - properties: { - foo: { - '$ref': '#/components/parameters/SimpleParameter' - } - }, - additionalProperties: false - }, - { - type: 'object', - required: ['bar'], - properties: { - bar: { - '$ref': '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' - } - }, - additionalProperties: false - } - ], - required: ['baz', 'qux'], - properties: { - baz: { - type: 'integer', - format: 'uint16', - minimum: 0, - nullable: true - }, - qux: { - type: 'integer', - format: 'uint8', - minimum: 0 - } - } -} as const; - -export const $NullableObject = { - type: ['object', 'null'], - description: 'An object that can be null', - properties: { - foo: { - type: 'string' - } - }, - default: null -} as const; - -export const $CharactersInDescription = { - type: 'string', - description: 'Some % character' -} as const; - -export const $ModelWithNullableObject = { - type: 'object', - properties: { - data: { - '$ref': '#/components/schemas/NullableObject' - } - } -} as const; - -export const $ModelWithOneOfEnum = { - oneOf: [ - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Bar'] - } - } - }, - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Baz'] - } - } - }, - { - type: 'object', - required: ['foo'], - properties: { - foo: { - type: 'string', - enum: ['Qux'] - } - } - }, - { - type: 'object', - required: ['content', 'foo'], - properties: { - content: { - type: 'string', - format: 'date-time' - }, - foo: { - type: 'string', - enum: ['Quux'] - } - } - }, - { - type: 'object', - required: ['content', 'foo'], - properties: { - content: { - type: 'array', - items: [ - { - type: 'string', - format: 'date-time' - }, - { - type: 'string' - } - ], - maxItems: 2, - minItems: 2 - }, - foo: { - type: 'string', - enum: ['Corge'] - } - } - } - ] -} as const; - -export const $ModelWithNestedArrayEnumsDataFoo = { - enum: ['foo', 'bar'], - type: 'string' -} as const; - -export const $ModelWithNestedArrayEnumsDataBar = { - enum: ['baz', 'qux'], - type: 'string' -} as const; - -export const $ModelWithNestedArrayEnumsData = { - type: 'object', - properties: { - foo: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' - } - }, - bar: { - type: 'array', - items: { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataBar' - } - } - } -} as const; - -export const $ModelWithNestedArrayEnums = { - type: 'object', - properties: { - array_strings: { - type: 'array', - items: { - type: 'string' - } - }, - data: { - allOf: [ - { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsData' - } - ] - } - } -} as const; - -export const $ModelWithNestedCompositionEnums = { - type: 'object', - properties: { - foo: { - allOf: [ - { - '$ref': '#/components/schemas/ModelWithNestedArrayEnumsDataFoo' - } - ] - } - } -} as const; - -export const $ModelWithReadOnlyAndWriteOnly = { - type: 'object', - required: ['foo', 'bar', 'baz'], - properties: { - foo: { - type: 'string' - }, - bar: { - readOnly: true, - type: 'string' - }, - baz: { - type: 'string', - writeOnly: true - } - } -} as const; - -export const $ModelWithConstantSizeArray = { - type: 'array', - items: { - type: 'number' - }, - minItems: 2, - maxItems: 2 -} as const; - -export const $ModelWithAnyOfConstantSizeArray = { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - minItems: 3, - maxItems: 3 -} as const; - -export const $ModelWithPrefixItemsConstantSizeArray = { - type: 'array', - prefixItems: [ - { - '$ref': '#/components/schemas/ModelWithInteger' - }, - { - oneOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - { - type: 'string' - } - ] -} as const; - -export const $ModelWithAnyOfConstantSizeArrayNullable = { - type: ['array'], - items: { - oneOf: [ - { - type: 'number', - nullable: true - }, - { - type: 'string' - } - ] - }, - minItems: 3, - maxItems: 3 -} as const; - -export const $ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = { - type: 'array', - items: { - oneOf: [ - { - type: 'number' - }, - { - '$ref': '#/components/schemas/import' - } - ] - }, - minItems: 2, - maxItems: 2 -} as const; - -export const $ModelWithAnyOfConstantSizeArrayAndIntersect = { - type: 'array', - items: { - allOf: [ - { - type: 'number' - }, - { - type: 'string' - } - ] - }, - minItems: 2, - maxItems: 2 -} as const; - -export const $ModelWithNumericEnumUnion = { - type: 'object', - properties: { - value: { - type: 'number', - description: 'Период', - enum: [-10, -1, 0, 1, 3, 6, 12] - } - } -} as const; - -export const $ModelWithBackticksInDescription = { - description: 'Some description with `back ticks`', - type: 'object', - properties: { - template: { - type: 'string', - description: `The template \`that\` should be used for parsing and importing the contents of the CSV file. - -

There is one placeholder currently supported:

  • \${x} - refers to the n-th column in the CSV file, e.g. \${1}, \${2}, ...)

Example of a correct JSON template:

-
-[
-  {
-    "resourceType": "Asset",
-    "identifier": {
-      "name": "\${1}",
-      "domain": {
-        "name": "\${2}",
-        "community": {
-          "name": "Some Community"
-        }
-      }
-    },
-    "attributes" : {
-      "00000000-0000-0000-0000-000000003115" : [ {
-        "value" : "\${3}" 
-      } ],
-      "00000000-0000-0000-0000-000000000222" : [ {
-        "value" : "\${4}"
-      } ]
-    }
-  }
-]
-
` - } - } -} as const; - -export const $ModelWithOneOfAndProperties = { - type: 'object', - oneOf: [ - { - '$ref': '#/components/parameters/SimpleParameter' - }, - { - '$ref': '#/components/schemas/NonAsciiStringæøåÆØÅöôêÊ字符串' - } - ], - required: ['baz', 'qux'], - properties: { - baz: { - type: 'integer', - format: 'uint16', - minimum: 0, - nullable: true - }, - qux: { - type: 'integer', - format: 'uint8', - minimum: 0 - } - } -} as const; - -export const $ParameterSimpleParameterUnused = { - description: 'Model used to test deduplication strategy (unused)', - type: 'string' -} as const; - -export const $PostServiceWithEmptyTagResponse = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const $PostServiceWithEmptyTagResponse2 = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const $DeleteFooData = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const $DeleteFooData2 = { - description: 'Model used to test deduplication strategy', - type: 'string' -} as const; - -export const $import = { - description: 'Model with restricted keyword name', - type: 'string' -} as const; - -export const $SchemaWithFormRestrictedKeys = { - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - }, - object: { - type: 'object', - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - } - } - }, - array: { - type: 'array', - items: [ - { - type: 'object', - properties: { - description: { - type: 'string' - }, - 'x-enum-descriptions': { - type: 'string' - }, - 'x-enum-varnames': { - type: 'string' - }, - 'x-enumNames': { - type: 'string' - }, - title: { - type: 'string' - } - } - } - ] - } - } -} as const; - -export const $io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - description: 'This schema was giving PascalCase transformations a hard time', - properties: { - preconditions: { - allOf: [ - { - '$ref': '#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions' - } - ], - description: 'Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.' - } - }, - type: 'object' -} as const; - -export const $io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - description: 'This schema was giving PascalCase transformations a hard time', - properties: { - resourceVersion: { - description: 'Specifies the target ResourceVersion', - type: 'string' - }, - uid: { - description: 'Specifies the target UID.', - type: 'string' - } - }, - type: 'object' -} as const; - -export const $AdditionalPropertiesUnknownIssue = { - type: 'object', - properties: {}, - additionalProperties: { - anyOf: [ - { - type: 'string' - }, - { - type: 'number' - } - ] - } -} as const; - -export const $AdditionalPropertiesUnknownIssue2 = { - type: 'object', - additionalProperties: { - anyOf: [ - { - type: 'string' - }, - { - type: 'number' - } - ] - } -} as const; - -export const $AdditionalPropertiesUnknownIssue3 = { - type: 'object', - allOf: [ - { - type: 'string' - }, - { - type: 'object', - required: ['entries'], - properties: { - entries: { - additionalProperties: { - '$ref': '#/components/schemas/AdditionalPropertiesUnknownIssue' - } - } - } - } - ] -} as const; - -export const $AdditionalPropertiesIntegerIssue = { - type: 'object', - required: ['value'], - properties: { - value: { - type: 'integer' - } - }, - additionalProperties: { - type: 'integer' - } -} as const; - -export const $OneOfAllOfIssue = { - oneOf: [ - { - allOf: [ - { - oneOf: [ - { - '$ref': '#/components/schemas/ConstValue' - }, - { - '$ref': '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.Boolean]' - } - ] - }, - { - '$ref': '#/components/schemas/3e-num_1Период' - } - ] - }, - { - '$ref': '#/components/schemas/Generic.Schema.Duplicate.Issue`1[System.String]' - } - ] -} as const; - -export const $Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - type: 'object', - properties: { - item: { - type: 'boolean' - }, - error: { - type: 'string', - nullable: true - }, - hasError: { - type: 'boolean', - readOnly: true - }, - data: { - type: 'object', - properties: {}, - additionalProperties: false - } - }, - additionalProperties: false -} as const; - -export const $Generic_Schema_Duplicate_Issue_1_System_String_ = { - type: 'object', - properties: { - item: { - type: 'string', - nullable: true - }, - error: { - type: 'string', - nullable: true - }, - hasError: { - type: 'boolean', - readOnly: true - } - }, - additionalProperties: false -} as const; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/index.ts.snap deleted file mode 100644 index b43a5238d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/index.ts.snap +++ /dev/null @@ -1,3 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type * from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/types.gen.ts.snap deleted file mode 100644 index f350f691f..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3-types-PascalCase/types.gen.ts.snap +++ /dev/null @@ -1,1996 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type ClientOptions = { - baseUrl: 'http://localhost:3000/base' | (string & {}); -}; - -/** - * Model with number-only name - */ -export type _400 = string; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CamelCaseCommentWithBreaks = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; - -/** - * This is a simple file - */ -export type SimpleFile = unknown; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = string; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: CamelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<{ - foo?: string; -} | { - bar?: string; -}>; - -export type AnyOfAnyAndNull = { - data?: unknown | null; -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<{ - foo?: string; - } | { - bar?: string; - }>; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type ModelFromZendesk = string; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: string; - /** - * This is a simple string property - */ - nullableRequiredProp1: string; - /** - * This is a simple string property - */ - nullableProp2?: string | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: string | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: true; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - /** - * Foo-Bar-Baz-Qux - */ - 'foo-bar-baz-qux'?: '3.0'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a deprecated model with a deprecated property - * - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * - * @deprecated - */ - prop?: string; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * Circle - */ -export type ModelCircle = { - kind: string; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: string; - sideLength?: number; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ({ - kind: 'circle'; -} & ModelCircle) | ({ - kind: 'square'; -} & ModelSquare); - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: Array | Array; -}; - -export type _3eNum1Период = 'Bird' | 'Dog'; - -export type ConstValue = 'ConstValue'; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - /** - * Scopes - */ - propA?: Array<_3eNum1Период | ConstValue> | null; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: boolean | { - [key: string]: number; - }; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: { - boolean?: boolean; - } & ModelWithEnum & ModelWithArray & ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - age: number; - firstName: string; - lastname: string; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: string; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: string; - }; - }; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type File = { - /** - * Id - */ - readonly id?: string; - /** - * Updated at - */ - readonly updated_at?: string; - /** - * Created at - */ - readonly created_at?: string; - /** - * Mime - */ - mime: string; - /** - * File - */ - readonly file?: string; -}; - -export type Default = { - name?: string; -}; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -export type ModelWithConst = { - String?: 'String'; - number?: 0; - null?: null; - withType?: 'Some string'; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string | undefined; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: Array | null; -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: SimpleParameter; -} | { - bar: NonAsciiStringæøåÆøÅöôêÊ字符串; -}) & { - baz: number; - qux: number; -}; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - unknown, - unknown - ]; - foo: 'Corge'; -}; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: ModelWithNestedArrayEnumsData; -}; - -export type ModelWithNestedCompositionEnums = { - foo?: ModelWithNestedArrayEnumsDataFoo; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -export type ModelWithAnyOfConstantSizeArray = [ - number | string, - number | string, - number | string -]; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - number | string, - string -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - number | string, - number | string, - number | string -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - number | Import, - number | Import -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - number & string, - number & string -]; - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { - baz: number; - qux: number; -}; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * Model with restricted keyword name - */ -export type Import = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: unknown; -}; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number; -}; - -export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; - -export type GenericSchemaDuplicateIssue1SystemBoolean = { - item?: boolean; - error?: string; - readonly hasError?: boolean; - data?: { - [key: string]: never; - }; -}; - -export type GenericSchemaDuplicateIssue1SystemString = { - item?: string; - error?: string; - readonly hasError?: boolean; -}; - -/** - * This is a reusable parameter - */ -export type SimpleParameter = string; - -/** - * Parameter with illegal characters - */ -export type XFooBar = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleRequestBody = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleFormData = ModelWithString; - -export type ExportData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ImportData = { - body: ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type ImportResponses = { - /** - * Success - */ - 200: ModelFromZendesk; - /** - * Default success response - */ - default: ModelWithReadOnlyAndWriteOnly; -}; - -export type ImportResponse = ImportResponses[keyof ImportResponses]; - -export type FooWowData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type FooWowResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ApiVVersionODataControllerCountData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple/$count'; -}; - -export type ApiVVersionODataControllerCountResponses = { - /** - * Success - */ - 200: ModelFromZendesk; -}; - -export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; - -export type GetApiVbyApiVersionSimpleOperationData = { - body?: never; - path: { - /** - * foo in method - */ - foo_param: string; - }; - query?: never; - url: '/api/v{api-version}/simple:operation'; -}; - -export type GetApiVbyApiVersionSimpleOperationErrors = { - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; - -export type GetApiVbyApiVersionSimpleOperationResponses = { - /** - * Response is a simple number - */ - 200: number; -}; - -export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; - -export type DeleteCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type GetCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type HeadCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type OptionsCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PatchCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PostCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PutCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type DeleteFooData3 = { - body?: never; - headers: { - /** - * Parameter with illegal characters - */ - 'x-Foo-Bar': ModelWithString; - }; - path: { - /** - * foo in method - */ - foo_param: string; - /** - * bar in method - */ - BarParam: string; - }; - query?: never; - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; -}; - -export type CallWithDescriptionsData = { - body?: never; - path?: never; - query?: { - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - }; - url: '/api/v{api-version}/descriptions/'; -}; - -export type DeprecatedCallData = { - body?: never; - headers: { - /** - * This parameter is deprecated - * - * @deprecated - */ - parameter: DeprecatedModel; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/parameters/deprecated'; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the body - */ - body: { - [key: string]: unknown; - }; - headers: { - /** - * This is the parameter that goes into the header - */ - parameterHeader: string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - parameterPath: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; - foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the query params - */ - cursor: string; - }; - url: '/api/v{api-version}/parameters/{parameterPath}'; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter that goes into the body - */ - body: ModelWithString; - headers: { - /** - * This is the parameter that goes into the request header - */ - 'parameter.header': string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - 'parameter.path.1'?: string; - /** - * This is the parameter that goes into the path - */ - 'parameter-path-2'?: string; - /** - * This is the parameter that goes into the path - */ - 'PARAMETER-PATH-3'?: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - /** - * This is the parameter with a reserved keyword - */ - default?: string; - /** - * This is the parameter that goes into the request query params - */ - 'parameter-query': string; - }; - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is a required parameter - */ - body: ModelWithOneOfEnum; - path?: never; - query?: { - /** - * This is an optional parameter - */ - page?: number; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - body?: { - offset?: number; - }; - path?: never; - query: { - /** - * This is a required parameter - */ - parameter: Pageable; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; - -export type PostApiVbyApiVersionRequestBodyData = { - /** - * A reusable request body - */ - body?: SimpleRequestBody; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/requestBody/'; -}; - -export type PostApiVbyApiVersionFormDataData = { - /** - * A reusable request body - */ - body?: SimpleFormData; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/formData/'; -}; - -export type CallWithDefaultParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string with default value - */ - parameterString?: string; - /** - * This is a simple number with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallWithDefaultOptionalParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallToTestOrderOfParamsData = { - body?: never; - path?: never; - query: { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: string; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type DuplicateNameData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName2Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName3Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName4Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type CallWithNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no-content'; -}; - -export type CallWithNoContentResponseResponses = { - /** - * Success - */ - 204: void; -}; - -export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; - -export type CallWithResponseAndNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/response-and-no-content'; -}; - -export type CallWithResponseAndNoContentResponseResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; - -export type DummyAData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/a'; -}; - -export type DummyAResponses = { - 200: _400; -}; - -export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; - -export type DummyBData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/b'; -}; - -export type DummyBResponses = { - /** - * Success - */ - 204: void; -}; - -export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; - -export type CallWithResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponseResponses = { - default: Import; -}; - -export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; - -export type CallWithDuplicateResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithDuplicateResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for 4XX errors - */ - '4XX': DictionaryWithArray; - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; - -export type CallWithDuplicateResponsesResponses = { - /** - * Message for 200 response - */ - 200: ModelWithBoolean & ModelWithInteger; - /** - * Message for 201 response - */ - 201: ModelWithString; - /** - * Message for 202 response - */ - 202: ModelWithString; -}; - -export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; - -export type CallWithResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for default response - */ - default: ModelWithStringError; -}; - -export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; - -export type CallWithResponsesResponses = { - /** - * Message for 200 response - */ - 200: { - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; - }; - /** - * Message for 201 response - */ - 201: ModelThatExtends; - /** - * Message for 202 response - */ - 202: ModelThatExtendsExtends; -}; - -export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; - -export type CollectionFormatData = { - body?: never; - path?: never; - query: { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCSV: Array; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySSV: Array; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTSV: Array; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array; - }; - url: '/api/v{api-version}/collectionFormat'; -}; - -export type TypesData = { - body?: never; - path?: { - /** - * This is a number parameter - */ - id?: number; - }; - query: { - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is a string parameter - */ - parameterString: string; - /** - * This is a boolean parameter - */ - parameterBoolean: boolean; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - }; - /** - * This is an array parameter - */ - parameterArray: Array; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - }; - /** - * This is an enum parameter - */ - parameterEnum: 'Success' | 'Warning' | 'Error'; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; - }; - url: '/api/v{api-version}/types'; -}; - -export type TypesResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Response is a simple string - */ - 201: string; - /** - * Response is a simple boolean - */ - 202: boolean; - /** - * Response is a simple object - */ - 203: { - [key: string]: unknown; - }; -}; - -export type TypesResponse = TypesResponses[keyof TypesResponses]; - -export type UploadFileData = { - body: unknown; - path: { - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/upload'; -}; - -export type UploadFileResponses = { - 200: boolean; -}; - -export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; - -export type FileResponseData = { - body?: never; - path: { - id: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/file/{id}'; -}; - -export type FileResponseResponses = { - /** - * Success - */ - 200: unknown; -}; - -export type ComplexTypesData = { - body?: never; - path?: never; - query: { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; - }; - url: '/api/v{api-version}/complex'; -}; - -export type ComplexTypesErrors = { - /** - * 400 `server` error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type ComplexTypesResponses = { - /** - * Successful response - */ - 200: Array; -}; - -export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; - -export type MultipartResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type MultipartResponseResponses = { - /** - * OK - */ - 200: { - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; - }; -}; - -export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; - -export type MultipartRequestData = { - body?: { - content?: Blob | File; - data?: ModelWithString; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type ComplexParamsData = { - body?: { - readonly key: string; - name: string; - enabled?: boolean; - type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array; - listOfStrings?: Array; - parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; - readonly user?: { - readonly id?: number; - readonly name?: string; - }; - }; - path: { - id: number; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/complex/{id}'; -}; - -export type ComplexParamsResponses = { - /** - * Success - */ - 200: ModelWithString; -}; - -export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; - -export type CallWithResultFromHeaderData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/header'; -}; - -export type CallWithResultFromHeaderErrors = { - /** - * 400 server error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type CallWithResultFromHeaderResponses = { - /** - * Successful response - */ - 200: unknown; -}; - -export type TestErrorCodeData = { - body?: never; - path?: never; - query: { - /** - * Status code to return - */ - status: number; - }; - url: '/api/v{api-version}/error'; -}; - -export type TestErrorCodeErrors = { - /** - * Custom message: Internal Server Error - */ - 500: unknown; - /** - * Custom message: Not Implemented - */ - 501: unknown; - /** - * Custom message: Bad Gateway - */ - 502: unknown; - /** - * Custom message: Service Unavailable - */ - 503: unknown; -}; - -export type TestErrorCodeResponses = { - /** - * Custom message: Successful response - */ - 200: unknown; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - body?: never; - path?: never; - query: { - /** - * Dummy input param - */ - nonAsciiParamæøåÆØÅöôêÊ: number; - }; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { - /** - * Successful response - */ - 200: Array; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; - -export type PutWithFormUrlEncodedData = { - body: ArrayWithStrings; - path?: never; - query?: never; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/sdk.gen.ts.snap deleted file mode 100644 index 4ef5fc431..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/sdk.gen.ts.snap +++ /dev/null @@ -1,890 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, ComplexParamsData, ComplexParamsResponse, PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, DeprecatedCallData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, FileResponseData, FileResponseResponse, PostApiFormDataData, CallWithResultFromHeaderResponse, MultipartRequestData, MultipartResponseResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData, DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, ApiVVersionODataControllerCountResponse, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; - -export class CollectionFormat { - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public static collectionFormat(data: CollectionFormatData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -export class Complex { - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public static complexTypes(data: ComplexTypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); - } - - /** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ - public static complexParams(data: ComplexParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); - } -} - -export class Default { - /** - * @throws ApiError - */ - public static export(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static patchApiNoTag(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ - public static import(data: ImportData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static fooWow(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ - public static getApiSimpleOperation(data: GetApiSimpleOperationData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); - } -} - -export class Defaults { - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(data: CallWithDefaultParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -export class Deprecated { - /** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ - public static deprecatedCall(data: DeprecatedCallData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); - } -} - -export class Descriptions { - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public static callWithDescriptions(data: CallWithDescriptionsData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -export class Duplicate { - /** - * @throws ApiError - */ - public static duplicateName(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName1(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName2(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName3(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -export class Error { - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public static testErrorCode(data: TestErrorCodeData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -export class FileResponse { - /** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ - public static fileResponse(data: FileResponseData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); - } -} - -export class FormData { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ - public static postApiFormData(data: PostApiFormDataData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } -} - -export class Header { - /** - * @returns string Successful response - * @throws ApiError - */ - public static callWithResultFromHeader(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class Multipart { - /** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static multipartRequest(data: MultipartRequestData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static multipartResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); - } -} - -export class MultipleTags1 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags2 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags3 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class NoContent { - /** - * @returns void Success - * @throws ApiError - */ - public static callWithNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -export class NonAsciiÆøåÆøÅöôêÊ { - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public static nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } - - /** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static putWithFormUrlEncoded(data: PutWithFormUrlEncodedData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} - -export class Parameters { - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public static deleteFoo(data: DeleteFooData3): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public static callWithParameters(data: CallWithParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public static callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public static getCallWithOptionalParam(data: GetCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static postCallWithOptionalParam(data: PostCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -export class RequestBody { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ - public static postApiRequestBody(data: PostApiRequestBodyData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); - } -} - -export class Response { - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns import - * @throws ApiError - */ - public static callWithResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public static callWithDuplicateResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public static callWithResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -export class Simple { - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public static apiVVersionODataControllerCount(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public static getCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static putCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static postCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static deleteCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static optionsCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static headCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static patchCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -export class Types { - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public static types(data: TypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); - } -} - -export class Upload { - /** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ - public static uploadFile(data: UploadFileData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/types.gen.ts.snap deleted file mode 100644 index 27c4b1682..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3/types.gen.ts.snap +++ /dev/null @@ -1,1549 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -export const _3e_num_1Период = { - BIRD: 'Bird', - DOG: 'Dog' -} as const; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -export const EnumWithReplacedCharacters = { - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'ØÆÅÔÖ_ØÆÅÔÖ字符串': 'øæåôöØÆÅÔÖ字符串', - '_3.1': 3.1, - EMPTY_STRING: '' -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export const EnumWithXEnumNames = { - zero: 0, - one: 1, - two: 2 -} as const; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export const ModelWithNestedArrayEnumsDataBar = { - BAZ: 'baz', - QUX: 'qux' -} as const; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export const ModelWithNestedArrayEnumsDataFoo = { - FOO: 'foo', - BAR: 'bar' -} as const; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResultFromHeaderResponse = (string); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/OpenAPI.ts.snap deleted file mode 100644 index 9fafe8d52..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/OpenAPI.ts.snap +++ /dev/null @@ -1,55 +0,0 @@ -import type { HttpResponse } from '@angular/common/http'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - response: Interceptors>; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/request.ts.snap deleted file mode 100644 index 4eab34ab6..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/core/request.ts.snap +++ /dev/null @@ -1,337 +0,0 @@ -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import type { HttpResponse, HttpErrorResponse } from '@angular/common/http'; -import { forkJoin, of, throwError } from 'rxjs'; -import { catchError, map, switchMap } from 'rxjs/operators'; -import type { Observable } from 'rxjs'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = (config: OpenAPIConfig, options: ApiRequestOptions): Observable => { - return forkJoin({ - // @ts-ignore - token: resolve(options, config.TOKEN), - // @ts-ignore - username: resolve(options, config.USERNAME), - // @ts-ignore - password: resolve(options, config.PASSWORD), - // @ts-ignore - additionalHeaders: resolve(options, config.HEADERS), - }).pipe( - map(({ token, username, password, additionalHeaders }) => { - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new HttpHeaders(headers); - }), - ); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = ( - config: OpenAPIConfig, - options: ApiRequestOptions, - http: HttpClient, - url: string, - body: unknown, - formData: FormData | undefined, - headers: HttpHeaders -): Observable> => { - return http.request(options.method, url, { - headers, - body: body ?? formData, - withCredentials: config.WITH_CREDENTIALS, - observe: 'response', - }); -}; - -export const getResponseHeader = (response: HttpResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const value = response.headers.get(responseHeader); - if (isString(value)) { - return value; - } - } - return undefined; -}; - -export const getResponseBody = (response: HttpResponse): T | undefined => { - if (response.status !== 204 && response.body !== null) { - return response.body; - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param http The Angular HTTP client - * @param options The request options from the service - * @returns Observable - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, http: HttpClient, options: ApiRequestOptions): Observable => { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - - return getHeaders(config, options).pipe( - switchMap(headers => { - return sendRequest(config, options, http, url, body, formData, headers); - }), - switchMap(async response => { - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - return { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - } as ApiResult; - }), - catchError((error: HttpErrorResponse) => { - if (!error.status) { - return throwError(() => error); - } - return of({ - url, - ok: error.ok, - status: error.status, - statusText: error.statusText, - body: error.error ?? error.statusText, - } as ApiResult); - }), - map(result => { - catchErrorCodes(options, result); - return result.body as T; - }), - catchError((error: ApiError) => { - return throwError(() => error); - }), - ); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/index.ts.snap deleted file mode 100644 index 3f555f4f1..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/index.ts.snap +++ /dev/null @@ -1,5 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/sdk.gen.ts.snap deleted file mode 100644 index 047b29453..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/sdk.gen.ts.snap +++ /dev/null @@ -1,1007 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import type { Observable } from 'rxjs'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, ComplexParamsData, ComplexParamsResponse, PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, DeprecatedCallData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, FileResponseData, FileResponseResponse, PostApiFormDataData, CallWithResultFromHeaderResponse, MultipartRequestData, MultipartResponseResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData, DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, ApiVVersionODataControllerCountResponse, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; - -@Injectable({ - providedIn: 'root' -}) -export class CollectionFormat { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public collectionFormat(data: CollectionFormatData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Complex { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public complexTypes(data: ComplexTypesData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); - } - - /** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ - public complexParams(data: ComplexParamsData): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Default { - constructor(public readonly http: HttpClient) { } - - /** - * @throws ApiError - */ - public export(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public patchApiNoTag(): Observable { - return __request(OpenAPI, this.http, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ - public import(data: ImportData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public fooWow(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ - public getApiSimpleOperation(data: GetApiSimpleOperationData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Defaults { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public callWithDefaultParameters(data: CallWithDefaultParametersData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public callToTestOrderOfParams(data: CallToTestOrderOfParamsData): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Deprecated { - constructor(public readonly http: HttpClient) { } - - /** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ - public deprecatedCall(data: DeprecatedCallData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Descriptions { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public callWithDescriptions(data: CallWithDescriptionsData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Duplicate { - constructor(public readonly http: HttpClient) { } - - /** - * @throws ApiError - */ - public duplicateName(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public duplicateName1(): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public duplicateName2(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public duplicateName3(): Observable { - return __request(OpenAPI, this.http, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Error { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public testErrorCode(data: TestErrorCodeData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class FileResponse { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ - public fileResponse(data: FileResponseData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class FormData { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ - public postApiFormData(data: PostApiFormDataData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Header { - constructor(public readonly http: HttpClient) { } - - /** - * @returns string Successful response - * @throws ApiError - */ - public callWithResultFromHeader(): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Multipart { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public multipartRequest(data: MultipartRequestData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public multipartResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class MultipleTags1 { - constructor(public readonly http: HttpClient) { } - - /** - * @returns _400 - * @throws ApiError - */ - public dummyA(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public dummyB(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class MultipleTags2 { - constructor(public readonly http: HttpClient) { } - - /** - * @returns _400 - * @throws ApiError - */ - public dummyA(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public dummyB(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class MultipleTags3 { - constructor(public readonly http: HttpClient) { } - - /** - * @returns void Success - * @throws ApiError - */ - public dummyB(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class NoContent { - constructor(public readonly http: HttpClient) { } - - /** - * @returns void Success - * @throws ApiError - */ - public callWithNoContentResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public callWithResponseAndNoContentResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class NonAsciiÆøåÆøÅöôêÊ { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } - - /** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public putWithFormUrlEncoded(data: PutWithFormUrlEncodedData): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Parameters { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public deleteFoo(data: DeleteFooData3): Observable { - return __request(OpenAPI, this.http, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public callWithParameters(data: CallWithParametersData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public getCallWithOptionalParam(data: GetCallWithOptionalParamData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public postCallWithOptionalParam(data: PostCallWithOptionalParamData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class RequestBody { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ - public postApiRequestBody(data: PostApiRequestBodyData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Response { - constructor(public readonly http: HttpClient) { } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public callWithResponseAndNoContentResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns import - * @throws ApiError - */ - public callWithResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public callWithDuplicateResponses(): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public callWithResponses(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Simple { - constructor(public readonly http: HttpClient) { } - - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public apiVVersionODataControllerCount(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public getCallWithoutParametersAndResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public putCallWithoutParametersAndResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public postCallWithoutParametersAndResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public deleteCallWithoutParametersAndResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public optionsCallWithoutParametersAndResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public headCallWithoutParametersAndResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public patchCallWithoutParametersAndResponse(): Observable { - return __request(OpenAPI, this.http, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Types { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public types(data: TypesData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class Upload { - constructor(public readonly http: HttpClient) { } - - /** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ - public uploadFile(data: UploadFileData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/types.gen.ts.snap deleted file mode 100644 index 03c4f2e7b..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular/types.gen.ts.snap +++ /dev/null @@ -1,1469 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResultFromHeaderResponse = (string); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/OpenAPI.ts.snap deleted file mode 100644 index 9fafe8d52..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/OpenAPI.ts.snap +++ /dev/null @@ -1,55 +0,0 @@ -import type { HttpResponse } from '@angular/common/http'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - response: Interceptors>; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/request.ts.snap deleted file mode 100644 index 4eab34ab6..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/core/request.ts.snap +++ /dev/null @@ -1,337 +0,0 @@ -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import type { HttpResponse, HttpErrorResponse } from '@angular/common/http'; -import { forkJoin, of, throwError } from 'rxjs'; -import { catchError, map, switchMap } from 'rxjs/operators'; -import type { Observable } from 'rxjs'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = (config: OpenAPIConfig, options: ApiRequestOptions): Observable => { - return forkJoin({ - // @ts-ignore - token: resolve(options, config.TOKEN), - // @ts-ignore - username: resolve(options, config.USERNAME), - // @ts-ignore - password: resolve(options, config.PASSWORD), - // @ts-ignore - additionalHeaders: resolve(options, config.HEADERS), - }).pipe( - map(({ token, username, password, additionalHeaders }) => { - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new HttpHeaders(headers); - }), - ); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = ( - config: OpenAPIConfig, - options: ApiRequestOptions, - http: HttpClient, - url: string, - body: unknown, - formData: FormData | undefined, - headers: HttpHeaders -): Observable> => { - return http.request(options.method, url, { - headers, - body: body ?? formData, - withCredentials: config.WITH_CREDENTIALS, - observe: 'response', - }); -}; - -export const getResponseHeader = (response: HttpResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const value = response.headers.get(responseHeader); - if (isString(value)) { - return value; - } - } - return undefined; -}; - -export const getResponseBody = (response: HttpResponse): T | undefined => { - if (response.status !== 204 && response.body !== null) { - return response.body; - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param http The Angular HTTP client - * @param options The request options from the service - * @returns Observable - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, http: HttpClient, options: ApiRequestOptions): Observable => { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - - return getHeaders(config, options).pipe( - switchMap(headers => { - return sendRequest(config, options, http, url, body, formData, headers); - }), - switchMap(async response => { - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - return { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - } as ApiResult; - }), - catchError((error: HttpErrorResponse) => { - if (!error.status) { - return throwError(() => error); - } - return of({ - url, - ok: error.ok, - status: error.status, - statusText: error.statusText, - body: error.error ?? error.statusText, - } as ApiResult); - }), - map(result => { - catchErrorCodes(options, result); - return result.body as T; - }), - catchError((error: ApiError) => { - return throwError(() => error); - }), - ); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/index.ts.snap deleted file mode 100644 index 3f555f4f1..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/index.ts.snap +++ /dev/null @@ -1,5 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/sdk.gen.ts.snap deleted file mode 100644 index 37db98558..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/sdk.gen.ts.snap +++ /dev/null @@ -1,86 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import type { Observable } from 'rxjs'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import { type ParentModelWithDatesResponse, type ModelWithDatesResponse, type ModelWithDatesArrayResponse, type ArrayOfDatesResponse, type DateResponse, type MultipleResponsesResponse, ParentModelWithDatesResponseTransformer, ModelWithDatesResponseTransformer, ModelWithDatesArrayResponseTransformer } from './types.gen'; - -@Injectable({ - providedIn: 'root' -}) -export class Default { - constructor(public readonly http: HttpClient) { } - - /** - * @returns ParentModelWithDates Success - * @returns unknown Success - * @throws ApiError - */ - public parentModelWithDates(): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/model-with-dates', - responseTransformer: ParentModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public modelWithDates(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/model-with-dates', - responseTransformer: ModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public modelWithDatesArray(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/model-with-dates-array', - responseTransformer: ModelWithDatesArrayResponseTransformer - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public arrayOfDates(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/array-of-dates' - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public date(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/date' - }); - } - - /** - * @returns ModelWithDates Updated - * @returns SimpleModel Created - * @throws ApiError - */ - public multipleResponses(): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/multiple-responses' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/types.gen.ts.snap deleted file mode 100644 index 5de1d89cc..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_transform/types.gen.ts.snap +++ /dev/null @@ -1,106 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model that contains a some dates - */ -export type ModelWithDates = { - id: number; - name: string; - readonly enabled: boolean; - readonly modified: Date; - readonly expires?: Date; -}; - -/** - * This is a model that contains a some dates and arrays - */ -export type ParentModelWithDates = { - id: number; - readonly modified?: Date; - items?: Array; - item?: ModelWithDates; - 'nullable-date'?: Array<(Date | null)>; - simpleItems?: Array; - simpleItem?: SimpleModel; - dates?: Array; - strings?: Array; -}; - -/** - * This is a model that contains a some dates - */ -export type SimpleModel = { - id: number; - name: string; - readonly enabled: boolean; -}; - -export type ParentModelWithDatesResponse = (ParentModelWithDates | unknown); - -export type ModelWithDatesResponse = (ModelWithDates); - -export type ModelWithDatesArrayResponse = (Array); - -export type ArrayOfDatesResponse = (Array); - -export type DateResponse = (Date); - -export type MultipleResponsesResponse = (Array | Array); - -export type ParentModelWithDatesResponseTransformer = (data: any) => Promise; - -export type ParentModelWithDatesModelResponseTransformer = (data: any) => ParentModelWithDates; - -export type ModelWithDatesModelResponseTransformer = (data: any) => ModelWithDates; - -export const ModelWithDatesModelResponseTransformer: ModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (data?.expires) { - data.expires = new Date(data.expires); - } - return data; -}; - -export const ParentModelWithDatesModelResponseTransformer: ParentModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (Array.isArray(data?.items)) { - data.items.forEach(ModelWithDatesModelResponseTransformer); - } - if (data?.item) { - ModelWithDatesModelResponseTransformer(data.item); - } - if (Array.isArray(data?.['nullable-date'])) { - data['nullable-date'] = data['nullable-date'].map(item => item ? new Date(item) : item); - } - if (Array.isArray(data?.dates)) { - data.dates = data.dates.map(item => item ? new Date(item) : item); - } - return data; -}; - -export const ParentModelWithDatesResponseTransformer: ParentModelWithDatesResponseTransformer = async (data) => { - if (data) { - ParentModelWithDatesModelResponseTransformer(data); - } - return data; -}; - -export type ModelWithDatesResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesResponseTransformer: ModelWithDatesResponseTransformer = async (data) => { - ModelWithDatesModelResponseTransformer(data); - return data; -}; - -export type ModelWithDatesArrayResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesArrayResponseTransformer: ModelWithDatesArrayResponseTransformer = async (data) => { - if (Array.isArray(data)) { - data.forEach(ModelWithDatesModelResponseTransformer); - } - return data; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/OpenAPI.ts.snap deleted file mode 100644 index 9fafe8d52..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/OpenAPI.ts.snap +++ /dev/null @@ -1,55 +0,0 @@ -import type { HttpResponse } from '@angular/common/http'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - response: Interceptors>; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/request.ts.snap deleted file mode 100644 index 4eab34ab6..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/core/request.ts.snap +++ /dev/null @@ -1,337 +0,0 @@ -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import type { HttpResponse, HttpErrorResponse } from '@angular/common/http'; -import { forkJoin, of, throwError } from 'rxjs'; -import { catchError, map, switchMap } from 'rxjs/operators'; -import type { Observable } from 'rxjs'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = (config: OpenAPIConfig, options: ApiRequestOptions): Observable => { - return forkJoin({ - // @ts-ignore - token: resolve(options, config.TOKEN), - // @ts-ignore - username: resolve(options, config.USERNAME), - // @ts-ignore - password: resolve(options, config.PASSWORD), - // @ts-ignore - additionalHeaders: resolve(options, config.HEADERS), - }).pipe( - map(({ token, username, password, additionalHeaders }) => { - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new HttpHeaders(headers); - }), - ); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = ( - config: OpenAPIConfig, - options: ApiRequestOptions, - http: HttpClient, - url: string, - body: unknown, - formData: FormData | undefined, - headers: HttpHeaders -): Observable> => { - return http.request(options.method, url, { - headers, - body: body ?? formData, - withCredentials: config.WITH_CREDENTIALS, - observe: 'response', - }); -}; - -export const getResponseHeader = (response: HttpResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const value = response.headers.get(responseHeader); - if (isString(value)) { - return value; - } - } - return undefined; -}; - -export const getResponseBody = (response: HttpResponse): T | undefined => { - if (response.status !== 204 && response.body !== null) { - return response.body; - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param http The Angular HTTP client - * @param options The request options from the service - * @returns Observable - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, http: HttpClient, options: ApiRequestOptions): Observable => { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - - return getHeaders(config, options).pipe( - switchMap(headers => { - return sendRequest(config, options, http, url, body, formData, headers); - }), - switchMap(async response => { - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - return { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - } as ApiResult; - }), - catchError((error: HttpErrorResponse) => { - if (!error.status) { - return throwError(() => error); - } - return of({ - url, - ok: error.ok, - status: error.status, - statusText: error.statusText, - body: error.error ?? error.statusText, - } as ApiResult); - }), - map(result => { - catchErrorCodes(options, result); - return result.body as T; - }), - catchError((error: ApiError) => { - return throwError(() => error); - }), - ); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/index.ts.snap deleted file mode 100644 index 3f555f4f1..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/index.ts.snap +++ /dev/null @@ -1,5 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/sdk.gen.ts.snap deleted file mode 100644 index dc89c810c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/sdk.gen.ts.snap +++ /dev/null @@ -1,801 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import type { Observable } from 'rxjs'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, ApiVVersionODataControllerCountResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, DeleteFooData3, CallWithDescriptionsData, DeprecatedCallData, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, PostApiFormDataData, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, DummyAResponse, DummyBResponse, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, CollectionFormatData, TypesData, TypesResponse, UploadFileData, UploadFileResponse, FileResponseData, FileResponseResponse, ComplexTypesData, ComplexTypesResponse, MultipartRequestData, MultipartResponseResponse, ComplexParamsData, ComplexParamsResponse, CallWithResultFromHeaderResponse, TestErrorCodeData, TestErrorCodeResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData } from './types.gen'; - -/** - * @throws ApiError - */ -export const export_ = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); -}; - -/** - * @returns unknown OK - * @throws ApiError - */ -export const patchApiNoTag = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); -}; - -/** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ -export const import_ = function (data: ImportData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @returns unknown OK - * @throws ApiError - */ -export const fooWow = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); -}; - -/** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ -export const apiVVersionODataControllerCount = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); -}; - -/** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ -export const getApiSimpleOperation = function (data: GetApiSimpleOperationData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); -}; - -/** - * @throws ApiError - */ -export const getCallWithoutParametersAndResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const putCallWithoutParametersAndResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const postCallWithoutParametersAndResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const deleteCallWithoutParametersAndResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const optionsCallWithoutParametersAndResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const headCallWithoutParametersAndResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const patchCallWithoutParametersAndResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ -export const deleteFoo = function (data: DeleteFooData3): Observable { - return __request(OpenAPI, this.http, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ -export const callWithDescriptions = function (data: CallWithDescriptionsData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); -}; - -/** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ -export const deprecatedCall = function (data: DeprecatedCallData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ -export const callWithParameters = function (data: CallWithParametersData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ -export const callWithWeirdParameterNames = function (data: CallWithWeirdParameterNamesData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ -export const getCallWithOptionalParam = function (data: GetCallWithOptionalParamData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ -export const postCallWithOptionalParam = function (data: PostCallWithOptionalParamData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ -export const postApiRequestBody = function (data: PostApiRequestBodyData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ -export const postApiFormData = function (data: PostApiFormDataData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ -export const callWithDefaultParameters = function (data: CallWithDefaultParametersData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ -export const callWithDefaultOptionalParameters = function (data: CallWithDefaultOptionalParametersData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ -export const callToTestOrderOfParams = function (data: CallToTestOrderOfParamsData): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName1 = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName2 = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName3 = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @returns void Success - * @throws ApiError - */ -export const callWithNoContentResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); -}; - -/** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ -export const callWithResponseAndNoContentResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); -}; - -/** - * @returns _400 - * @throws ApiError - */ -export const dummyA = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); -}; - -/** - * @returns void Success - * @throws ApiError - */ -export const dummyB = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); -}; - -/** - * @returns import - * @throws ApiError - */ -export const callWithResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/response' - }); -}; - -/** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ -export const callWithDuplicateResponses = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); -}; - -/** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ -export const callWithResponses = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ -export const collectionFormat = function (data: CollectionFormatData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ -export const types = function (data: TypesData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); -}; - -/** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ -export const uploadFile = function (data: UploadFileData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); -}; - -/** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ -export const fileResponse = function (data: FileResponseData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ -export const complexTypes = function (data: ComplexTypesData): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ -export const multipartRequest = function (data: MultipartRequestData = {}): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); -}; - -/** - * @returns unknown OK - * @throws ApiError - */ -export const multipartResponse = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); -}; - -/** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ -export const complexParams = function (data: ComplexParamsData): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); -}; - -/** - * @returns string Successful response - * @throws ApiError - */ -export const callWithResultFromHeader = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ -export const testErrorCode = function (data: TestErrorCodeData): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ -export const nonAsciiæøåÆøÅöôêÊ字符串 = function (data: NonAsciiæøåÆøÅöôêÊ字符串Data): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); -}; - -/** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ -export const putWithFormUrlEncoded = function (data: PutWithFormUrlEncodedData): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/types.gen.ts.snap deleted file mode 100644 index eb2a891d6..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable/types.gen.ts.snap +++ /dev/null @@ -1,1469 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type CallWithResultFromHeaderResponse = (string); - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/OpenAPI.ts.snap deleted file mode 100644 index 9fafe8d52..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/OpenAPI.ts.snap +++ /dev/null @@ -1,55 +0,0 @@ -import type { HttpResponse } from '@angular/common/http'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - response: Interceptors>; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/request.ts.snap deleted file mode 100644 index 4eab34ab6..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/core/request.ts.snap +++ /dev/null @@ -1,337 +0,0 @@ -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import type { HttpResponse, HttpErrorResponse } from '@angular/common/http'; -import { forkJoin, of, throwError } from 'rxjs'; -import { catchError, map, switchMap } from 'rxjs/operators'; -import type { Observable } from 'rxjs'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = (config: OpenAPIConfig, options: ApiRequestOptions): Observable => { - return forkJoin({ - // @ts-ignore - token: resolve(options, config.TOKEN), - // @ts-ignore - username: resolve(options, config.USERNAME), - // @ts-ignore - password: resolve(options, config.PASSWORD), - // @ts-ignore - additionalHeaders: resolve(options, config.HEADERS), - }).pipe( - map(({ token, username, password, additionalHeaders }) => { - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new HttpHeaders(headers); - }), - ); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = ( - config: OpenAPIConfig, - options: ApiRequestOptions, - http: HttpClient, - url: string, - body: unknown, - formData: FormData | undefined, - headers: HttpHeaders -): Observable> => { - return http.request(options.method, url, { - headers, - body: body ?? formData, - withCredentials: config.WITH_CREDENTIALS, - observe: 'response', - }); -}; - -export const getResponseHeader = (response: HttpResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const value = response.headers.get(responseHeader); - if (isString(value)) { - return value; - } - } - return undefined; -}; - -export const getResponseBody = (response: HttpResponse): T | undefined => { - if (response.status !== 204 && response.body !== null) { - return response.body; - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param http The Angular HTTP client - * @param options The request options from the service - * @returns Observable - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, http: HttpClient, options: ApiRequestOptions): Observable => { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - - return getHeaders(config, options).pipe( - switchMap(headers => { - return sendRequest(config, options, http, url, body, formData, headers); - }), - switchMap(async response => { - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - return { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - } as ApiResult; - }), - catchError((error: HttpErrorResponse) => { - if (!error.status) { - return throwError(() => error); - } - return of({ - url, - ok: error.ok, - status: error.status, - statusText: error.statusText, - body: error.error ?? error.statusText, - } as ApiResult); - }), - map(result => { - catchErrorCodes(options, result); - return result.body as T; - }), - catchError((error: ApiError) => { - return throwError(() => error); - }), - ); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/index.ts.snap deleted file mode 100644 index 3f555f4f1..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/index.ts.snap +++ /dev/null @@ -1,5 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/sdk.gen.ts.snap deleted file mode 100644 index 109822a09..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/sdk.gen.ts.snap +++ /dev/null @@ -1,79 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import type { Observable } from 'rxjs'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import { type ParentModelWithDatesResponse, type ModelWithDatesResponse, type ModelWithDatesArrayResponse, type ArrayOfDatesResponse, type DateResponse, type MultipleResponsesResponse, ParentModelWithDatesResponseTransformer, ModelWithDatesResponseTransformer, ModelWithDatesArrayResponseTransformer } from './types.gen'; - -/** - * @returns ParentModelWithDates Success - * @returns unknown Success - * @throws ApiError - */ -export const parentModelWithDates = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'POST', - url: '/api/model-with-dates', - responseTransformer: ParentModelWithDatesResponseTransformer - }); -}; - -/** - * @returns ModelWithDates Success - * @throws ApiError - */ -export const modelWithDates = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/model-with-dates', - responseTransformer: ModelWithDatesResponseTransformer - }); -}; - -/** - * @returns ModelWithDates Success - * @throws ApiError - */ -export const modelWithDatesArray = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/model-with-dates-array', - responseTransformer: ModelWithDatesArrayResponseTransformer - }); -}; - -/** - * @returns string Success - * @throws ApiError - */ -export const arrayOfDates = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/array-of-dates' - }); -}; - -/** - * @returns string Success - * @throws ApiError - */ -export const date = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/date' - }); -}; - -/** - * @returns ModelWithDates Updated - * @returns SimpleModel Created - * @throws ApiError - */ -export const multipleResponses = function (): Observable { - return __request(OpenAPI, this.http, { - method: 'PUT', - url: '/api/multiple-responses' - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/types.gen.ts.snap deleted file mode 100644 index 5de1d89cc..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_angular_tree_shakeable_transform/types.gen.ts.snap +++ /dev/null @@ -1,106 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model that contains a some dates - */ -export type ModelWithDates = { - id: number; - name: string; - readonly enabled: boolean; - readonly modified: Date; - readonly expires?: Date; -}; - -/** - * This is a model that contains a some dates and arrays - */ -export type ParentModelWithDates = { - id: number; - readonly modified?: Date; - items?: Array; - item?: ModelWithDates; - 'nullable-date'?: Array<(Date | null)>; - simpleItems?: Array; - simpleItem?: SimpleModel; - dates?: Array; - strings?: Array; -}; - -/** - * This is a model that contains a some dates - */ -export type SimpleModel = { - id: number; - name: string; - readonly enabled: boolean; -}; - -export type ParentModelWithDatesResponse = (ParentModelWithDates | unknown); - -export type ModelWithDatesResponse = (ModelWithDates); - -export type ModelWithDatesArrayResponse = (Array); - -export type ArrayOfDatesResponse = (Array); - -export type DateResponse = (Date); - -export type MultipleResponsesResponse = (Array | Array); - -export type ParentModelWithDatesResponseTransformer = (data: any) => Promise; - -export type ParentModelWithDatesModelResponseTransformer = (data: any) => ParentModelWithDates; - -export type ModelWithDatesModelResponseTransformer = (data: any) => ModelWithDates; - -export const ModelWithDatesModelResponseTransformer: ModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (data?.expires) { - data.expires = new Date(data.expires); - } - return data; -}; - -export const ParentModelWithDatesModelResponseTransformer: ParentModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (Array.isArray(data?.items)) { - data.items.forEach(ModelWithDatesModelResponseTransformer); - } - if (data?.item) { - ModelWithDatesModelResponseTransformer(data.item); - } - if (Array.isArray(data?.['nullable-date'])) { - data['nullable-date'] = data['nullable-date'].map(item => item ? new Date(item) : item); - } - if (Array.isArray(data?.dates)) { - data.dates = data.dates.map(item => item ? new Date(item) : item); - } - return data; -}; - -export const ParentModelWithDatesResponseTransformer: ParentModelWithDatesResponseTransformer = async (data) => { - if (data) { - ParentModelWithDatesModelResponseTransformer(data); - } - return data; -}; - -export type ModelWithDatesResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesResponseTransformer: ModelWithDatesResponseTransformer = async (data) => { - ModelWithDatesModelResponseTransformer(data); - return data; -}; - -export type ModelWithDatesArrayResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesArrayResponseTransformer: ModelWithDatesArrayResponseTransformer = async (data) => { - if (Array.isArray(data)) { - data.forEach(ModelWithDatesModelResponseTransformer); - } - return data; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/OpenAPI.ts.snap deleted file mode 100644 index cb7b23cb7..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/OpenAPI.ts.snap +++ /dev/null @@ -1,57 +0,0 @@ -import type { AxiosRequestConfig, AxiosResponse } from 'axios'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/request.ts.snap deleted file mode 100644 index ecc2e393c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/core/request.ts.snap +++ /dev/null @@ -1,347 +0,0 @@ -import axios from 'axios'; -import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const isSuccess = (status: number): boolean => { - return status >= 200 && status < 300; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise> => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } else if (options.formData !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } - } - - return headers; -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - return options.body; - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: unknown, - formData: FormData | undefined, - headers: Record, - onCancel: OnCancel, - axiosClient: AxiosInstance -): Promise> => { - const controller = new AbortController(); - - let requestConfig: AxiosRequestConfig = { - data: body ?? formData, - headers, - method: options.method, - signal: controller.signal, - url, - withCredentials: config.WITH_CREDENTIALS, - }; - - onCancel(() => controller.abort()); - - for (const fn of config.interceptors.request._fns) { - requestConfig = await fn(requestConfig); - } - - try { - return await axiosClient.request(requestConfig); - } catch (error) { - const axiosError = error as AxiosError; - if (axiosError.response) { - return axiosError.response; - } - throw error; - } -}; - -export const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers[responseHeader]; - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = (response: AxiosResponse): unknown => { - if (response.status !== 204) { - return response.data; - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @param axiosClient The axios client instance to use - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && isSuccess(response.status)) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/sdk.gen.ts.snap deleted file mode 100644 index 4ef5fc431..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/sdk.gen.ts.snap +++ /dev/null @@ -1,890 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, ComplexParamsData, ComplexParamsResponse, PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, DeprecatedCallData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, FileResponseData, FileResponseResponse, PostApiFormDataData, CallWithResultFromHeaderResponse, MultipartRequestData, MultipartResponseResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData, DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, ApiVVersionODataControllerCountResponse, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; - -export class CollectionFormat { - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public static collectionFormat(data: CollectionFormatData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -export class Complex { - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public static complexTypes(data: ComplexTypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); - } - - /** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ - public static complexParams(data: ComplexParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); - } -} - -export class Default { - /** - * @throws ApiError - */ - public static export(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static patchApiNoTag(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ - public static import(data: ImportData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static fooWow(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ - public static getApiSimpleOperation(data: GetApiSimpleOperationData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); - } -} - -export class Defaults { - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(data: CallWithDefaultParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -export class Deprecated { - /** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ - public static deprecatedCall(data: DeprecatedCallData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); - } -} - -export class Descriptions { - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public static callWithDescriptions(data: CallWithDescriptionsData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -export class Duplicate { - /** - * @throws ApiError - */ - public static duplicateName(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName1(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName2(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName3(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -export class Error { - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public static testErrorCode(data: TestErrorCodeData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -export class FileResponse { - /** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ - public static fileResponse(data: FileResponseData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); - } -} - -export class FormData { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ - public static postApiFormData(data: PostApiFormDataData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } -} - -export class Header { - /** - * @returns string Successful response - * @throws ApiError - */ - public static callWithResultFromHeader(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class Multipart { - /** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static multipartRequest(data: MultipartRequestData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static multipartResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); - } -} - -export class MultipleTags1 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags2 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags3 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class NoContent { - /** - * @returns void Success - * @throws ApiError - */ - public static callWithNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -export class NonAsciiÆøåÆøÅöôêÊ { - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public static nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } - - /** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static putWithFormUrlEncoded(data: PutWithFormUrlEncodedData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} - -export class Parameters { - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public static deleteFoo(data: DeleteFooData3): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public static callWithParameters(data: CallWithParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public static callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public static getCallWithOptionalParam(data: GetCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static postCallWithOptionalParam(data: PostCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -export class RequestBody { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ - public static postApiRequestBody(data: PostApiRequestBodyData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); - } -} - -export class Response { - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns import - * @throws ApiError - */ - public static callWithResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public static callWithDuplicateResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public static callWithResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -export class Simple { - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public static apiVVersionODataControllerCount(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public static getCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static putCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static postCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static deleteCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static optionsCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static headCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static patchCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -export class Types { - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public static types(data: TypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); - } -} - -export class Upload { - /** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ - public static uploadFile(data: UploadFileData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/types.gen.ts.snap deleted file mode 100644 index 27c4b1682..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios/types.gen.ts.snap +++ /dev/null @@ -1,1549 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -export const _3e_num_1Период = { - BIRD: 'Bird', - DOG: 'Dog' -} as const; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -export const EnumWithReplacedCharacters = { - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'ØÆÅÔÖ_ØÆÅÔÖ字符串': 'øæåôöØÆÅÔÖ字符串', - '_3.1': 3.1, - EMPTY_STRING: '' -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export const EnumWithXEnumNames = { - zero: 0, - one: 1, - two: 2 -} as const; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export const ModelWithNestedArrayEnumsDataBar = { - BAZ: 'baz', - QUX: 'qux' -} as const; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export const ModelWithNestedArrayEnumsDataFoo = { - FOO: 'foo', - BAR: 'bar' -} as const; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResultFromHeaderResponse = (string); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/OpenAPI.ts.snap deleted file mode 100644 index cb7b23cb7..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/OpenAPI.ts.snap +++ /dev/null @@ -1,57 +0,0 @@ -import type { AxiosRequestConfig, AxiosResponse } from 'axios'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/request.ts.snap deleted file mode 100644 index ecc2e393c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/core/request.ts.snap +++ /dev/null @@ -1,347 +0,0 @@ -import axios from 'axios'; -import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const isSuccess = (status: number): boolean => { - return status >= 200 && status < 300; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise> => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } else if (options.formData !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } - } - - return headers; -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - return options.body; - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: unknown, - formData: FormData | undefined, - headers: Record, - onCancel: OnCancel, - axiosClient: AxiosInstance -): Promise> => { - const controller = new AbortController(); - - let requestConfig: AxiosRequestConfig = { - data: body ?? formData, - headers, - method: options.method, - signal: controller.signal, - url, - withCredentials: config.WITH_CREDENTIALS, - }; - - onCancel(() => controller.abort()); - - for (const fn of config.interceptors.request._fns) { - requestConfig = await fn(requestConfig); - } - - try { - return await axiosClient.request(requestConfig); - } catch (error) { - const axiosError = error as AxiosError; - if (axiosError.response) { - return axiosError.response; - } - throw error; - } -}; - -export const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers[responseHeader]; - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = (response: AxiosResponse): unknown => { - if (response.status !== 204) { - return response.data; - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @param axiosClient The axios client instance to use - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && isSuccess(response.status)) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/sdk.gen.ts.snap deleted file mode 100644 index 6789f1a5d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/sdk.gen.ts.snap +++ /dev/null @@ -1,79 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import { type ParentModelWithDatesResponse, type ModelWithDatesResponse, type ModelWithDatesArrayResponse, type ArrayOfDatesResponse, type DateResponse, type MultipleResponsesResponse, ParentModelWithDatesResponseTransformer, ModelWithDatesResponseTransformer, ModelWithDatesArrayResponseTransformer } from './types.gen'; - -export class Default { - /** - * @returns ParentModelWithDates Success - * @returns unknown Success - * @throws ApiError - */ - public static parentModelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/model-with-dates', - responseTransformer: ParentModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates', - responseTransformer: ModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDatesArray(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates-array', - responseTransformer: ModelWithDatesArrayResponseTransformer - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static arrayOfDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/array-of-dates' - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static date(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/date' - }); - } - - /** - * @returns ModelWithDates Updated - * @returns SimpleModel Created - * @throws ApiError - */ - public static multipleResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/multiple-responses' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/types.gen.ts.snap deleted file mode 100644 index 5de1d89cc..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_axios_transform/types.gen.ts.snap +++ /dev/null @@ -1,106 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model that contains a some dates - */ -export type ModelWithDates = { - id: number; - name: string; - readonly enabled: boolean; - readonly modified: Date; - readonly expires?: Date; -}; - -/** - * This is a model that contains a some dates and arrays - */ -export type ParentModelWithDates = { - id: number; - readonly modified?: Date; - items?: Array; - item?: ModelWithDates; - 'nullable-date'?: Array<(Date | null)>; - simpleItems?: Array; - simpleItem?: SimpleModel; - dates?: Array; - strings?: Array; -}; - -/** - * This is a model that contains a some dates - */ -export type SimpleModel = { - id: number; - name: string; - readonly enabled: boolean; -}; - -export type ParentModelWithDatesResponse = (ParentModelWithDates | unknown); - -export type ModelWithDatesResponse = (ModelWithDates); - -export type ModelWithDatesArrayResponse = (Array); - -export type ArrayOfDatesResponse = (Array); - -export type DateResponse = (Date); - -export type MultipleResponsesResponse = (Array | Array); - -export type ParentModelWithDatesResponseTransformer = (data: any) => Promise; - -export type ParentModelWithDatesModelResponseTransformer = (data: any) => ParentModelWithDates; - -export type ModelWithDatesModelResponseTransformer = (data: any) => ModelWithDates; - -export const ModelWithDatesModelResponseTransformer: ModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (data?.expires) { - data.expires = new Date(data.expires); - } - return data; -}; - -export const ParentModelWithDatesModelResponseTransformer: ParentModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (Array.isArray(data?.items)) { - data.items.forEach(ModelWithDatesModelResponseTransformer); - } - if (data?.item) { - ModelWithDatesModelResponseTransformer(data.item); - } - if (Array.isArray(data?.['nullable-date'])) { - data['nullable-date'] = data['nullable-date'].map(item => item ? new Date(item) : item); - } - if (Array.isArray(data?.dates)) { - data.dates = data.dates.map(item => item ? new Date(item) : item); - } - return data; -}; - -export const ParentModelWithDatesResponseTransformer: ParentModelWithDatesResponseTransformer = async (data) => { - if (data) { - ParentModelWithDatesModelResponseTransformer(data); - } - return data; -}; - -export type ModelWithDatesResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesResponseTransformer: ModelWithDatesResponseTransformer = async (data) => { - ModelWithDatesModelResponseTransformer(data); - return data; -}; - -export type ModelWithDatesArrayResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesArrayResponseTransformer: ModelWithDatesArrayResponseTransformer = async (data) => { - if (Array.isArray(data)) { - data.forEach(ModelWithDatesModelResponseTransformer); - } - return data; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/ApiClient.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/ApiClient.ts.snap deleted file mode 100644 index bb253b19a..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/ApiClient.ts.snap +++ /dev/null @@ -1,101 +0,0 @@ -import type { BaseHttpRequest } from './core/BaseHttpRequest'; -import type { OpenAPIConfig } from './core/OpenAPI'; -import { Interceptors } from './core/OpenAPI'; -import { FetchHttpRequest } from './core/FetchHttpRequest'; - -import { CollectionFormat } from './sdk.gen'; -import { Complex } from './sdk.gen'; -import { Default } from './sdk.gen'; -import { Defaults } from './sdk.gen'; -import { Deprecated } from './sdk.gen'; -import { Descriptions } from './sdk.gen'; -import { Duplicate } from './sdk.gen'; -import { Error } from './sdk.gen'; -import { FileResponse } from './sdk.gen'; -import { FormData } from './sdk.gen'; -import { Header } from './sdk.gen'; -import { Multipart } from './sdk.gen'; -import { MultipleTags1 } from './sdk.gen'; -import { MultipleTags2 } from './sdk.gen'; -import { MultipleTags3 } from './sdk.gen'; -import { NoContent } from './sdk.gen'; -import { NonAsciiÆøåÆøÅöôêÊ } from './sdk.gen'; -import { Parameters } from './sdk.gen'; -import { RequestBody } from './sdk.gen'; -import { Response } from './sdk.gen'; -import { Simple } from './sdk.gen'; -import { Types } from './sdk.gen'; -import { Upload } from './sdk.gen'; - -type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest; - -export class ApiClient { - - public readonly collectionFormat: CollectionFormat; - public readonly complex: Complex; - public readonly default: Default; - public readonly defaults: Defaults; - public readonly deprecated: Deprecated; - public readonly descriptions: Descriptions; - public readonly duplicate: Duplicate; - public readonly error: Error; - public readonly fileResponse: FileResponse; - public readonly formData: FormData; - public readonly header: Header; - public readonly multipart: Multipart; - public readonly multipleTags1: MultipleTags1; - public readonly multipleTags2: MultipleTags2; - public readonly multipleTags3: MultipleTags3; - public readonly noContent: NoContent; - public readonly nonAsciiÆøåÆøÅöôêÊ: NonAsciiÆøåÆøÅöôêÊ; - public readonly parameters: Parameters; - public readonly requestBody: RequestBody; - public readonly response: Response; - public readonly simple: Simple; - public readonly types: Types; - public readonly upload: Upload; - - public readonly request: BaseHttpRequest; - - constructor(config?: Partial, HttpRequest: HttpRequestConstructor = FetchHttpRequest) { - this.request = new HttpRequest({ - BASE: config?.BASE ?? 'http://localhost:3000/base', - VERSION: config?.VERSION ?? '1.0', - WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false, - CREDENTIALS: config?.CREDENTIALS ?? 'include', - TOKEN: config?.TOKEN, - USERNAME: config?.USERNAME, - PASSWORD: config?.PASSWORD, - HEADERS: config?.HEADERS, - ENCODE_PATH: config?.ENCODE_PATH, - interceptors: { - request: config?.interceptors?.request ?? new Interceptors(), - response: config?.interceptors?.response ?? new Interceptors(), - }, - }); - - this.collectionFormat = new CollectionFormat(this.request); - this.complex = new Complex(this.request); - this.default = new Default(this.request); - this.defaults = new Defaults(this.request); - this.deprecated = new Deprecated(this.request); - this.descriptions = new Descriptions(this.request); - this.duplicate = new Duplicate(this.request); - this.error = new Error(this.request); - this.fileResponse = new FileResponse(this.request); - this.formData = new FormData(this.request); - this.header = new Header(this.request); - this.multipart = new Multipart(this.request); - this.multipleTags1 = new MultipleTags1(this.request); - this.multipleTags2 = new MultipleTags2(this.request); - this.multipleTags3 = new MultipleTags3(this.request); - this.noContent = new NoContent(this.request); - this.nonAsciiÆøåÆøÅöôêÊ = new NonAsciiÆøåÆøÅöôêÊ(this.request); - this.parameters = new Parameters(this.request); - this.requestBody = new RequestBody(this.request); - this.response = new Response(this.request); - this.simple = new Simple(this.request); - this.types = new Types(this.request); - this.upload = new Upload(this.request); - } -} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/BaseHttpRequest.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/BaseHttpRequest.ts.snap deleted file mode 100644 index ee28b8164..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/BaseHttpRequest.ts.snap +++ /dev/null @@ -1,10 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export abstract class BaseHttpRequest { - - constructor(public readonly config: OpenAPIConfig) {} - - public abstract request(options: ApiRequestOptions): CancelablePromise; -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/FetchHttpRequest.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/FetchHttpRequest.ts.snap deleted file mode 100644 index e7c4bd5a9..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/FetchHttpRequest.ts.snap +++ /dev/null @@ -1,22 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import { BaseHttpRequest } from './BaseHttpRequest'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; -import { request as __request } from './request'; - -export class FetchHttpRequest extends BaseHttpRequest { - - constructor(config: OpenAPIConfig) { - super(config); - } - - /** - * Request method - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ - public override request(options: ApiRequestOptions): CancelablePromise { - return __request(this.config, options); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/index.ts.snap deleted file mode 100644 index 7e12dd663..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/index.ts.snap +++ /dev/null @@ -1,8 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiClient } from './ApiClient'; -export { ApiError } from './core/ApiError'; -export { BaseHttpRequest } from './core/BaseHttpRequest'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/sdk.gen.ts.snap deleted file mode 100644 index cae28f858..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/sdk.gen.ts.snap +++ /dev/null @@ -1,935 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import type { BaseHttpRequest } from './core/BaseHttpRequest'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, ComplexParamsData, ComplexParamsResponse, PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, DeprecatedCallData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, FileResponseData, FileResponseResponse, PostApiFormDataData, CallWithResultFromHeaderResponse, MultipartRequestData, MultipartResponseResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData, DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, ApiVVersionODataControllerCountResponse, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; - -export class CollectionFormat { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public collectionFormat(data: CollectionFormatData): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -export class Complex { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public complexTypes(data: ComplexTypesData): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); - } - - /** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ - public complexParams(data: ComplexParamsData): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); - } -} - -export class Default { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @throws ApiError - */ - public export(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public patchApiNoTag(): CancelablePromise { - return this.httpRequest.request({ - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ - public import(data: ImportData): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public fooWow(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ - public getApiSimpleOperation(data: GetApiSimpleOperationData): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); - } -} - -export class Defaults { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public callWithDefaultParameters(data: CallWithDefaultParametersData = {}): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -export class Deprecated { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ - public deprecatedCall(data: DeprecatedCallData): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); - } -} - -export class Descriptions { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public callWithDescriptions(data: CallWithDescriptionsData = {}): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -export class Duplicate { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @throws ApiError - */ - public duplicateName(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public duplicateName1(): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public duplicateName2(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public duplicateName3(): CancelablePromise { - return this.httpRequest.request({ - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -export class Error { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public testErrorCode(data: TestErrorCodeData): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -export class FileResponse { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ - public fileResponse(data: FileResponseData): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); - } -} - -export class FormData { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ - public postApiFormData(data: PostApiFormDataData = {}): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } -} - -export class Header { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns string Successful response - * @throws ApiError - */ - public callWithResultFromHeader(): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class Multipart { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public multipartRequest(data: MultipartRequestData = {}): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public multipartResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multipart' - }); - } -} - -export class MultipleTags1 { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns _400 - * @throws ApiError - */ - public dummyA(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public dummyB(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags2 { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns _400 - * @throws ApiError - */ - public dummyA(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public dummyB(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags3 { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns void Success - * @throws ApiError - */ - public dummyB(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class NoContent { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns void Success - * @throws ApiError - */ - public callWithNoContentResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public callWithResponseAndNoContentResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -export class NonAsciiÆøåÆøÅöôêÊ { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } - - /** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public putWithFormUrlEncoded(data: PutWithFormUrlEncodedData): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} - -export class Parameters { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public deleteFoo(data: DeleteFooData3): CancelablePromise { - return this.httpRequest.request({ - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public callWithParameters(data: CallWithParametersData): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public getCallWithOptionalParam(data: GetCallWithOptionalParamData): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public postCallWithOptionalParam(data: PostCallWithOptionalParamData): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -export class RequestBody { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ - public postApiRequestBody(data: PostApiRequestBodyData = {}): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); - } -} - -export class Response { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public callWithResponseAndNoContentResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns import - * @throws ApiError - */ - public callWithResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public callWithDuplicateResponses(): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public callWithResponses(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -export class Simple { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public apiVVersionODataControllerCount(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public getCallWithoutParametersAndResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public putCallWithoutParametersAndResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public postCallWithoutParametersAndResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public deleteCallWithoutParametersAndResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public optionsCallWithoutParametersAndResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public headCallWithoutParametersAndResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public patchCallWithoutParametersAndResponse(): CancelablePromise { - return this.httpRequest.request({ - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -export class Types { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public types(data: TypesData): CancelablePromise { - return this.httpRequest.request({ - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); - } -} - -export class Upload { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ - public uploadFile(data: UploadFileData): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/types.gen.ts.snap deleted file mode 100644 index 21ee5921d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client/types.gen.ts.snap +++ /dev/null @@ -1,1469 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export type File = { - readonly id?: string; - readonly updated_at?: Date; - readonly created_at?: Date; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: Date; - foo: 'Quux'; -} | { - content: [ - (Date | string), - (Date | string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: Date; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResultFromHeaderResponse = (string); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/ApiClient.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/ApiClient.ts.snap deleted file mode 100644 index 542f65bab..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/ApiClient.ts.snap +++ /dev/null @@ -1,35 +0,0 @@ -import type { BaseHttpRequest } from './core/BaseHttpRequest'; -import type { OpenAPIConfig } from './core/OpenAPI'; -import { Interceptors } from './core/OpenAPI'; -import { FetchHttpRequest } from './core/FetchHttpRequest'; - -import { Default } from './sdk.gen'; - -type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest; - -export class ApiClient { - - public readonly default: Default; - - public readonly request: BaseHttpRequest; - - constructor(config?: Partial, HttpRequest: HttpRequestConstructor = FetchHttpRequest) { - this.request = new HttpRequest({ - BASE: config?.BASE ?? 'http://localhost:3000/base', - VERSION: config?.VERSION ?? '1.0', - WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false, - CREDENTIALS: config?.CREDENTIALS ?? 'include', - TOKEN: config?.TOKEN, - USERNAME: config?.USERNAME, - PASSWORD: config?.PASSWORD, - HEADERS: config?.HEADERS, - ENCODE_PATH: config?.ENCODE_PATH, - interceptors: { - request: config?.interceptors?.request ?? new Interceptors(), - response: config?.interceptors?.response ?? new Interceptors(), - }, - }); - - this.default = new Default(this.request); - } -} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/BaseHttpRequest.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/BaseHttpRequest.ts.snap deleted file mode 100644 index ee28b8164..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/BaseHttpRequest.ts.snap +++ /dev/null @@ -1,10 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export abstract class BaseHttpRequest { - - constructor(public readonly config: OpenAPIConfig) {} - - public abstract request(options: ApiRequestOptions): CancelablePromise; -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/FetchHttpRequest.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/FetchHttpRequest.ts.snap deleted file mode 100644 index e7c4bd5a9..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/FetchHttpRequest.ts.snap +++ /dev/null @@ -1,22 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import { BaseHttpRequest } from './BaseHttpRequest'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; -import { request as __request } from './request'; - -export class FetchHttpRequest extends BaseHttpRequest { - - constructor(config: OpenAPIConfig) { - super(config); - } - - /** - * Request method - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ - public override request(options: ApiRequestOptions): CancelablePromise { - return __request(this.config, options); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/index.ts.snap deleted file mode 100644 index 7e12dd663..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/index.ts.snap +++ /dev/null @@ -1,8 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiClient } from './ApiClient'; -export { ApiError } from './core/ApiError'; -export { BaseHttpRequest } from './core/BaseHttpRequest'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/sdk.gen.ts.snap deleted file mode 100644 index 1666bf7da..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/sdk.gen.ts.snap +++ /dev/null @@ -1,80 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import type { BaseHttpRequest } from './core/BaseHttpRequest'; -import { type ParentModelWithDatesResponse, type ModelWithDatesResponse, type ModelWithDatesArrayResponse, type ArrayOfDatesResponse, type DateResponse, type MultipleResponsesResponse, ParentModelWithDatesResponseTransformer, ModelWithDatesResponseTransformer, ModelWithDatesArrayResponseTransformer } from './types.gen'; - -export class Default { - constructor(public readonly httpRequest: BaseHttpRequest) { } - - /** - * @returns ParentModelWithDates Success - * @returns unknown Success - * @throws ApiError - */ - public parentModelWithDates(): CancelablePromise { - return this.httpRequest.request({ - method: 'POST', - url: '/api/model-with-dates', - responseTransformer: ParentModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public modelWithDates(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/model-with-dates', - responseTransformer: ModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public modelWithDatesArray(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/model-with-dates-array', - responseTransformer: ModelWithDatesArrayResponseTransformer - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public arrayOfDates(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/array-of-dates' - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public date(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/date' - }); - } - - /** - * @returns ModelWithDates Updated - * @returns SimpleModel Created - * @throws ApiError - */ - public multipleResponses(): CancelablePromise { - return this.httpRequest.request({ - method: 'PUT', - url: '/api/multiple-responses' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/types.gen.ts.snap deleted file mode 100644 index 5de1d89cc..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_client_transform/types.gen.ts.snap +++ /dev/null @@ -1,106 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model that contains a some dates - */ -export type ModelWithDates = { - id: number; - name: string; - readonly enabled: boolean; - readonly modified: Date; - readonly expires?: Date; -}; - -/** - * This is a model that contains a some dates and arrays - */ -export type ParentModelWithDates = { - id: number; - readonly modified?: Date; - items?: Array; - item?: ModelWithDates; - 'nullable-date'?: Array<(Date | null)>; - simpleItems?: Array; - simpleItem?: SimpleModel; - dates?: Array; - strings?: Array; -}; - -/** - * This is a model that contains a some dates - */ -export type SimpleModel = { - id: number; - name: string; - readonly enabled: boolean; -}; - -export type ParentModelWithDatesResponse = (ParentModelWithDates | unknown); - -export type ModelWithDatesResponse = (ModelWithDates); - -export type ModelWithDatesArrayResponse = (Array); - -export type ArrayOfDatesResponse = (Array); - -export type DateResponse = (Date); - -export type MultipleResponsesResponse = (Array | Array); - -export type ParentModelWithDatesResponseTransformer = (data: any) => Promise; - -export type ParentModelWithDatesModelResponseTransformer = (data: any) => ParentModelWithDates; - -export type ModelWithDatesModelResponseTransformer = (data: any) => ModelWithDates; - -export const ModelWithDatesModelResponseTransformer: ModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (data?.expires) { - data.expires = new Date(data.expires); - } - return data; -}; - -export const ParentModelWithDatesModelResponseTransformer: ParentModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (Array.isArray(data?.items)) { - data.items.forEach(ModelWithDatesModelResponseTransformer); - } - if (data?.item) { - ModelWithDatesModelResponseTransformer(data.item); - } - if (Array.isArray(data?.['nullable-date'])) { - data['nullable-date'] = data['nullable-date'].map(item => item ? new Date(item) : item); - } - if (Array.isArray(data?.dates)) { - data.dates = data.dates.map(item => item ? new Date(item) : item); - } - return data; -}; - -export const ParentModelWithDatesResponseTransformer: ParentModelWithDatesResponseTransformer = async (data) => { - if (data) { - ParentModelWithDatesModelResponseTransformer(data); - } - return data; -}; - -export type ModelWithDatesResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesResponseTransformer: ModelWithDatesResponseTransformer = async (data) => { - ModelWithDatesModelResponseTransformer(data); - return data; -}; - -export type ModelWithDatesArrayResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesArrayResponseTransformer: ModelWithDatesArrayResponseTransformer = async (data) => { - if (Array.isArray(data)) { - data.forEach(ModelWithDatesModelResponseTransformer); - } - return data; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/index.ts.snap deleted file mode 100644 index 56bade120..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/index.ts.snap +++ /dev/null @@ -1,2 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/types.gen.ts.snap deleted file mode 100644 index 0913515f8..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_date/types.gen.ts.snap +++ /dev/null @@ -1,1022 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export type File = { - readonly id?: string; - readonly updated_at?: Date; - readonly created_at?: Date; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: Date; - foo: 'Quux'; -} | { - content: [ - (Date | string), - (Date | string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: Date; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/sdk.gen.ts.snap deleted file mode 100644 index 4ef5fc431..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/sdk.gen.ts.snap +++ /dev/null @@ -1,890 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, ComplexParamsData, ComplexParamsResponse, PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, DeprecatedCallData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, FileResponseData, FileResponseResponse, PostApiFormDataData, CallWithResultFromHeaderResponse, MultipartRequestData, MultipartResponseResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData, DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, ApiVVersionODataControllerCountResponse, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; - -export class CollectionFormat { - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public static collectionFormat(data: CollectionFormatData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -export class Complex { - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public static complexTypes(data: ComplexTypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); - } - - /** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ - public static complexParams(data: ComplexParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); - } -} - -export class Default { - /** - * @throws ApiError - */ - public static export(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static patchApiNoTag(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ - public static import(data: ImportData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static fooWow(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ - public static getApiSimpleOperation(data: GetApiSimpleOperationData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); - } -} - -export class Defaults { - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(data: CallWithDefaultParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -export class Deprecated { - /** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ - public static deprecatedCall(data: DeprecatedCallData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); - } -} - -export class Descriptions { - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public static callWithDescriptions(data: CallWithDescriptionsData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -export class Duplicate { - /** - * @throws ApiError - */ - public static duplicateName(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName1(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName2(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName3(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -export class Error { - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public static testErrorCode(data: TestErrorCodeData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -export class FileResponse { - /** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ - public static fileResponse(data: FileResponseData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); - } -} - -export class FormData { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ - public static postApiFormData(data: PostApiFormDataData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } -} - -export class Header { - /** - * @returns string Successful response - * @throws ApiError - */ - public static callWithResultFromHeader(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class Multipart { - /** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static multipartRequest(data: MultipartRequestData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static multipartResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); - } -} - -export class MultipleTags1 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags2 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags3 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class NoContent { - /** - * @returns void Success - * @throws ApiError - */ - public static callWithNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -export class NonAsciiÆøåÆøÅöôêÊ { - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public static nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } - - /** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static putWithFormUrlEncoded(data: PutWithFormUrlEncodedData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} - -export class Parameters { - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public static deleteFoo(data: DeleteFooData3): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public static callWithParameters(data: CallWithParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public static callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public static getCallWithOptionalParam(data: GetCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static postCallWithOptionalParam(data: PostCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -export class RequestBody { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ - public static postApiRequestBody(data: PostApiRequestBodyData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); - } -} - -export class Response { - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns import - * @throws ApiError - */ - public static callWithResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public static callWithDuplicateResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public static callWithResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -export class Simple { - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public static apiVVersionODataControllerCount(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public static getCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static putCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static postCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static deleteCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static optionsCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static headCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static patchCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -export class Types { - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public static types(data: TypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); - } -} - -export class Upload { - /** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ - public static uploadFile(data: UploadFileData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/types.gen.ts.snap deleted file mode 100644 index ef85bc585..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_enums_typescript/types.gen.ts.snap +++ /dev/null @@ -1,1524 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export enum _3e_num_1Период { - BIRD = 'Bird', - DOG = 'Dog' -} - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export enum EnumWithExtensions { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS = 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING = 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR = 500 -} - -/** - * This is a simple enum with numbers - */ -export enum EnumWithNumbers { - '_1' = 1, - '_2' = 2, - '_3' = 3, - '_1.1' = 1.1, - '_1.2' = 1.2, - '_1.3' = 1.3, - '_100' = 100, - '_200' = 200, - '_300' = 300, - '_-100' = -100, - '_-200' = -200, - '_-300' = -300, - '_-1.1' = -1.1, - '_-1.2' = -1.2, - '_-1.3' = -1.3 -} - -export enum EnumWithReplacedCharacters { - _SINGLE_QUOTE_ = "'Single Quote'", - _DOUBLE_QUOTES_ = '"Double Quotes"', - ØÆÅÔÖ_ØÆÅÔÖ字符串 = 'øæåôöØÆÅÔÖ字符串', - '_3.1' = 3.1, - EMPTY_STRING = '' -} - -/** - * This is a simple enum with strings - */ -export enum EnumWithStrings { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - _SINGLE_QUOTE_ = "'Single Quote'", - _DOUBLE_QUOTES_ = '"Double Quotes"', - NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串 = 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} - -export enum EnumWithXEnumNames { - zero = 0, - one = 1, - two = 2 -} - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export enum ModelWithNestedArrayEnumsDataBar { - BAZ = 'baz', - QUX = 'qux' -} - -export enum ModelWithNestedArrayEnumsDataFoo { - FOO = 'foo', - BAR = 'bar' -} - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResultFromHeaderResponse = (string); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/sdk.gen.ts.snap deleted file mode 100644 index 65d769266..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/sdk.gen.ts.snap +++ /dev/null @@ -1,84 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData } from './types.gen'; - -export class Defaults { - /** - * @param parameterString This is a simple string with default value - * @param parameterNumber This is a simple number with default value - * @param parameterBoolean This is a simple boolean with default value - * @param parameterEnum This is a simple enum with default value - * @param parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(parameterString: CallWithDefaultParametersData['parameterString'] = 'Hello World!', parameterNumber: CallWithDefaultParametersData['parameterNumber'] = 123, parameterBoolean: CallWithDefaultParametersData['parameterBoolean'] = true, parameterEnum: CallWithDefaultParametersData['parameterEnum'] = 'Success', parameterModel: CallWithDefaultParametersData['parameterModel'] = { - prop: 'Hello World!' - }): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString, - parameterNumber, - parameterBoolean, - parameterEnum, - parameterModel - } - }); - } - - /** - * @param parameterString This is a simple string that is optional with default value - * @param parameterNumber This is a simple number that is optional with default value - * @param parameterBoolean This is a simple boolean that is optional with default value - * @param parameterEnum This is a simple enum that is optional with default value - * @param parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(parameterString: CallWithDefaultOptionalParametersData['parameterString'] = 'Hello World!', parameterNumber: CallWithDefaultOptionalParametersData['parameterNumber'] = 123, parameterBoolean: CallWithDefaultOptionalParametersData['parameterBoolean'] = true, parameterEnum: CallWithDefaultOptionalParametersData['parameterEnum'] = 'Success', parameterModel: CallWithDefaultOptionalParametersData['parameterModel'] = { - prop: 'Hello World!' - }): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString, - parameterNumber, - parameterBoolean, - parameterEnum, - parameterModel - } - }); - } - - /** - * @param parameterStringWithNoDefault This is a string with no default - * @param parameterOptionalStringWithDefault This is a optional string with default - * @param parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param parameterOptionalStringWithNoDefault This is a optional string with no default - * @param parameterStringWithDefault This is a string with default - * @param parameterStringWithEmptyDefault This is a string with empty default - * @param parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(parameterStringWithNoDefault: CallToTestOrderOfParamsData['parameterStringWithNoDefault'], parameterOptionalStringWithDefault: CallToTestOrderOfParamsData['parameterOptionalStringWithDefault'] = 'Hello World!', parameterOptionalStringWithEmptyDefault: CallToTestOrderOfParamsData['parameterOptionalStringWithEmptyDefault'] = '', parameterOptionalStringWithNoDefault?: CallToTestOrderOfParamsData['parameterOptionalStringWithNoDefault'], parameterStringWithDefault: CallToTestOrderOfParamsData['parameterStringWithDefault'] = 'Hello World!', parameterStringWithEmptyDefault: CallToTestOrderOfParamsData['parameterStringWithEmptyDefault'] = '', parameterStringNullableWithNoDefault?: CallToTestOrderOfParamsData['parameterStringNullableWithNoDefault'], parameterStringNullableWithDefault: CallToTestOrderOfParamsData['parameterStringNullableWithDefault'] = null): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault, - parameterStringWithDefault, - parameterStringWithEmptyDefault, - parameterStringWithNoDefault, - parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault - } - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/types.gen.ts.snap deleted file mode 100644 index 3ee5e285c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_legacy_positional_args/types.gen.ts.snap +++ /dev/null @@ -1,102 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client.gen.ts.snap deleted file mode 100644 index 6b55ac80f..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client.gen.ts.snap +++ /dev/null @@ -1,18 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import { type ClientOptions, type Config, createClient, createConfig } from './client'; -import type { ClientOptions as ClientOptions2 } from './types.gen'; - -/** - * The `createClientConfig()` function will be called on client initialization - * and the returned object will become the client's initial configuration. - * - * You may want to initialize your client this way instead of calling - * `setConfig()`. This is useful for example if you're using Next.js - * to ensure your client always has the correct values. - */ -export type CreateClientConfig = (override?: Config) => Config & T>; - -export const client = createClient(createConfig({ - baseUrl: 'http://localhost:3000/base' -})); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/client.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/client.gen.ts.snap deleted file mode 100644 index a439d2748..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/client.gen.ts.snap +++ /dev/null @@ -1,268 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import { createSseClient } from '../core/serverSentEvents.gen'; -import type { HttpMethod } from '../core/types.gen'; -import { getValidRequestBody } from '../core/utils.gen'; -import type { - Client, - Config, - RequestOptions, - ResolvedRequestOptions, -} from './types.gen'; -import { - buildUrl, - createConfig, - createInterceptors, - getParseAs, - mergeConfigs, - mergeHeaders, - setAuthParams, -} from './utils.gen'; - -type ReqInit = Omit & { - body?: any; - headers: ReturnType; -}; - -export const createClient = (config: Config = {}): Client => { - let _config = mergeConfigs(createConfig(), config); - - const getConfig = (): Config => ({ ..._config }); - - const setConfig = (config: Config): Config => { - _config = mergeConfigs(_config, config); - return getConfig(); - }; - - const interceptors = createInterceptors< - Request, - Response, - unknown, - ResolvedRequestOptions - >(); - - const beforeRequest = async (options: RequestOptions) => { - const opts = { - ..._config, - ...options, - fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, - headers: mergeHeaders(_config.headers, options.headers), - serializedBody: undefined, - }; - - if (opts.security) { - await setAuthParams({ - ...opts, - security: opts.security, - }); - } - - if (opts.requestValidator) { - await opts.requestValidator(opts); - } - - if (opts.body !== undefined && opts.bodySerializer) { - opts.serializedBody = opts.bodySerializer(opts.body); - } - - // remove Content-Type header if body is empty to avoid sending invalid requests - if (opts.body === undefined || opts.serializedBody === '') { - opts.headers.delete('Content-Type'); - } - - const url = buildUrl(opts); - - return { opts, url }; - }; - - const request: Client['request'] = async (options) => { - // @ts-expect-error - const { opts, url } = await beforeRequest(options); - const requestInit: ReqInit = { - redirect: 'follow', - ...opts, - body: getValidRequestBody(opts), - }; - - let request = new Request(url, requestInit); - - for (const fn of interceptors.request.fns) { - if (fn) { - request = await fn(request, opts); - } - } - - // fetch must be assigned here, otherwise it would throw the error: - // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation - const _fetch = opts.fetch!; - let response = await _fetch(request); - - for (const fn of interceptors.response.fns) { - if (fn) { - response = await fn(response, request, opts); - } - } - - const result = { - request, - response, - }; - - if (response.ok) { - const parseAs = - (opts.parseAs === 'auto' - ? getParseAs(response.headers.get('Content-Type')) - : opts.parseAs) ?? 'json'; - - if ( - response.status === 204 || - response.headers.get('Content-Length') === '0' - ) { - let emptyData: any; - switch (parseAs) { - case 'arrayBuffer': - case 'blob': - case 'text': - emptyData = await response[parseAs](); - break; - case 'formData': - emptyData = new FormData(); - break; - case 'stream': - emptyData = response.body; - break; - case 'json': - default: - emptyData = {}; - break; - } - return opts.responseStyle === 'data' - ? emptyData - : { - data: emptyData, - ...result, - }; - } - - let data: any; - switch (parseAs) { - case 'arrayBuffer': - case 'blob': - case 'formData': - case 'json': - case 'text': - data = await response[parseAs](); - break; - case 'stream': - return opts.responseStyle === 'data' - ? response.body - : { - data: response.body, - ...result, - }; - } - - if (parseAs === 'json') { - if (opts.responseValidator) { - await opts.responseValidator(data); - } - - if (opts.responseTransformer) { - data = await opts.responseTransformer(data); - } - } - - return opts.responseStyle === 'data' - ? data - : { - data, - ...result, - }; - } - - const textError = await response.text(); - let jsonError: unknown; - - try { - jsonError = JSON.parse(textError); - } catch { - // noop - } - - const error = jsonError ?? textError; - let finalError = error; - - for (const fn of interceptors.error.fns) { - if (fn) { - finalError = (await fn(error, response, request, opts)) as string; - } - } - - finalError = finalError || ({} as string); - - if (opts.throwOnError) { - throw finalError; - } - - // TODO: we probably want to return error and improve types - return opts.responseStyle === 'data' - ? undefined - : { - error: finalError, - ...result, - }; - }; - - const makeMethodFn = - (method: Uppercase) => (options: RequestOptions) => - request({ ...options, method }); - - const makeSseFn = - (method: Uppercase) => async (options: RequestOptions) => { - const { opts, url } = await beforeRequest(options); - return createSseClient({ - ...opts, - body: opts.body as BodyInit | null | undefined, - headers: opts.headers as unknown as Record, - method, - onRequest: async (url, init) => { - let request = new Request(url, init); - for (const fn of interceptors.request.fns) { - if (fn) { - request = await fn(request, opts); - } - } - return request; - }, - url, - }); - }; - - return { - buildUrl, - connect: makeMethodFn('CONNECT'), - delete: makeMethodFn('DELETE'), - get: makeMethodFn('GET'), - getConfig, - head: makeMethodFn('HEAD'), - interceptors, - options: makeMethodFn('OPTIONS'), - patch: makeMethodFn('PATCH'), - post: makeMethodFn('POST'), - put: makeMethodFn('PUT'), - request, - setConfig, - sse: { - connect: makeSseFn('CONNECT'), - delete: makeSseFn('DELETE'), - get: makeSseFn('GET'), - head: makeSseFn('HEAD'), - options: makeSseFn('OPTIONS'), - patch: makeSseFn('PATCH'), - post: makeSseFn('POST'), - put: makeSseFn('PUT'), - trace: makeSseFn('TRACE'), - }, - trace: makeMethodFn('TRACE'), - } as Client; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/index.ts.snap deleted file mode 100644 index cbf8dfeed..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/index.ts.snap +++ /dev/null @@ -1,26 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type { Auth } from '../core/auth.gen'; -export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; -export { - formDataBodySerializer, - jsonBodySerializer, - urlSearchParamsBodySerializer, -} from '../core/bodySerializer.gen'; -export { buildClientParams } from '../core/params.gen'; -export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; -export { createClient } from './client.gen'; -export type { - Client, - ClientOptions, - Config, - CreateClientConfig, - Options, - OptionsLegacyParser, - RequestOptions, - RequestResult, - ResolvedRequestOptions, - ResponseStyle, - TDataShape, -} from './types.gen'; -export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/types.gen.ts.snap deleted file mode 100644 index 5c70971f2..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/types.gen.ts.snap +++ /dev/null @@ -1,268 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { Auth } from '../core/auth.gen'; -import type { - ServerSentEventsOptions, - ServerSentEventsResult, -} from '../core/serverSentEvents.gen'; -import type { - Client as CoreClient, - Config as CoreConfig, -} from '../core/types.gen'; -import type { Middleware } from './utils.gen'; - -export type ResponseStyle = 'data' | 'fields'; - -export interface Config - extends Omit, - CoreConfig { - /** - * Base URL for all requests made by this client. - */ - baseUrl?: T['baseUrl']; - /** - * Fetch API implementation. You can use this option to provide a custom - * fetch instance. - * - * @default globalThis.fetch - */ - fetch?: typeof fetch; - /** - * Please don't use the Fetch client for Next.js applications. The `next` - * options won't have any effect. - * - * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. - */ - next?: never; - /** - * Return the response data parsed in a specified format. By default, `auto` - * will infer the appropriate method from the `Content-Type` response header. - * You can override this behavior with any of the {@link Body} methods. - * Select `stream` if you don't want to parse response data at all. - * - * @default 'auto' - */ - parseAs?: - | 'arrayBuffer' - | 'auto' - | 'blob' - | 'formData' - | 'json' - | 'stream' - | 'text'; - /** - * Should we return only data or multiple fields (data, error, response, etc.)? - * - * @default 'fields' - */ - responseStyle?: ResponseStyle; - /** - * Throw an error instead of returning it in the response? - * - * @default false - */ - throwOnError?: T['throwOnError']; -} - -export interface RequestOptions< - TData = unknown, - TResponseStyle extends ResponseStyle = 'fields', - ThrowOnError extends boolean = boolean, - Url extends string = string, -> extends Config<{ - responseStyle: TResponseStyle; - throwOnError: ThrowOnError; - }>, - Pick< - ServerSentEventsOptions, - | 'onSseError' - | 'onSseEvent' - | 'sseDefaultRetryDelay' - | 'sseMaxRetryAttempts' - | 'sseMaxRetryDelay' - > { - /** - * Any body that you want to add to your request. - * - * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} - */ - body?: unknown; - path?: Record; - query?: Record; - /** - * Security mechanism(s) to use for the request. - */ - security?: ReadonlyArray; - url: Url; -} - -export interface ResolvedRequestOptions< - TResponseStyle extends ResponseStyle = 'fields', - ThrowOnError extends boolean = boolean, - Url extends string = string, -> extends RequestOptions { - serializedBody?: string; -} - -export type RequestResult< - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = boolean, - TResponseStyle extends ResponseStyle = 'fields', -> = ThrowOnError extends true - ? Promise< - TResponseStyle extends 'data' - ? TData extends Record - ? TData[keyof TData] - : TData - : { - data: TData extends Record - ? TData[keyof TData] - : TData; - request: Request; - response: Response; - } - > - : Promise< - TResponseStyle extends 'data' - ? - | (TData extends Record - ? TData[keyof TData] - : TData) - | undefined - : ( - | { - data: TData extends Record - ? TData[keyof TData] - : TData; - error: undefined; - } - | { - data: undefined; - error: TError extends Record - ? TError[keyof TError] - : TError; - } - ) & { - request: Request; - response: Response; - } - >; - -export interface ClientOptions { - baseUrl?: string; - responseStyle?: ResponseStyle; - throwOnError?: boolean; -} - -type MethodFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, - TResponseStyle extends ResponseStyle = 'fields', ->( - options: Omit, 'method'>, -) => RequestResult; - -type SseFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, - TResponseStyle extends ResponseStyle = 'fields', ->( - options: Omit, 'method'>, -) => Promise>; - -type RequestFn = < - TData = unknown, - TError = unknown, - ThrowOnError extends boolean = false, - TResponseStyle extends ResponseStyle = 'fields', ->( - options: Omit, 'method'> & - Pick< - Required>, - 'method' - >, -) => RequestResult; - -type BuildUrlFn = < - TData extends { - body?: unknown; - path?: Record; - query?: Record; - url: string; - }, ->( - options: TData & Options, -) => string; - -export type Client = CoreClient< - RequestFn, - Config, - MethodFn, - BuildUrlFn, - SseFn -> & { - interceptors: Middleware; -}; - -/** - * The `createClientConfig()` function will be called on client initialization - * and the returned object will become the client's initial configuration. - * - * You may want to initialize your client this way instead of calling - * `setConfig()`. This is useful for example if you're using Next.js - * to ensure your client always has the correct values. - */ -export type CreateClientConfig = ( - override?: Config, -) => Config & T>; - -export interface TDataShape { - body?: unknown; - headers?: unknown; - path?: unknown; - query?: unknown; - url: string; -} - -type OmitKeys = Pick>; - -export type Options< - TData extends TDataShape = TDataShape, - ThrowOnError extends boolean = boolean, - TResponse = unknown, - TResponseStyle extends ResponseStyle = 'fields', -> = OmitKeys< - RequestOptions, - 'body' | 'path' | 'query' | 'url' -> & - ([TData] extends [never] ? unknown : Omit); - -export type OptionsLegacyParser< - TData = unknown, - ThrowOnError extends boolean = boolean, - TResponseStyle extends ResponseStyle = 'fields', -> = TData extends { body?: any } - ? TData extends { headers?: any } - ? OmitKeys< - RequestOptions, - 'body' | 'headers' | 'url' - > & - TData - : OmitKeys< - RequestOptions, - 'body' | 'url' - > & - TData & - Pick, 'headers'> - : TData extends { headers?: any } - ? OmitKeys< - RequestOptions, - 'headers' | 'url' - > & - TData & - Pick, 'body'> - : OmitKeys, 'url'> & - TData; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/utils.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/utils.gen.ts.snap deleted file mode 100644 index 4c48a9ee1..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/client/utils.gen.ts.snap +++ /dev/null @@ -1,332 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import { getAuthToken } from '../core/auth.gen'; -import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; -import { jsonBodySerializer } from '../core/bodySerializer.gen'; -import { - serializeArrayParam, - serializeObjectParam, - serializePrimitiveParam, -} from '../core/pathSerializer.gen'; -import { getUrl } from '../core/utils.gen'; -import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; - -export const createQuerySerializer = ({ - parameters = {}, - ...args -}: QuerySerializerOptions = {}) => { - const querySerializer = (queryParams: T) => { - const search: string[] = []; - if (queryParams && typeof queryParams === 'object') { - for (const name in queryParams) { - const value = queryParams[name]; - - if (value === undefined || value === null) { - continue; - } - - const options = parameters[name] || args; - - if (Array.isArray(value)) { - const serializedArray = serializeArrayParam({ - allowReserved: options.allowReserved, - explode: true, - name, - style: 'form', - value, - ...options.array, - }); - if (serializedArray) search.push(serializedArray); - } else if (typeof value === 'object') { - const serializedObject = serializeObjectParam({ - allowReserved: options.allowReserved, - explode: true, - name, - style: 'deepObject', - value: value as Record, - ...options.object, - }); - if (serializedObject) search.push(serializedObject); - } else { - const serializedPrimitive = serializePrimitiveParam({ - allowReserved: options.allowReserved, - name, - value: value as string, - }); - if (serializedPrimitive) search.push(serializedPrimitive); - } - } - } - return search.join('&'); - }; - return querySerializer; -}; - -/** - * Infers parseAs value from provided Content-Type header. - */ -export const getParseAs = ( - contentType: string | null, -): Exclude => { - if (!contentType) { - // If no Content-Type header is provided, the best we can do is return the raw response body, - // which is effectively the same as the 'stream' option. - return 'stream'; - } - - const cleanContent = contentType.split(';')[0]?.trim(); - - if (!cleanContent) { - return; - } - - if ( - cleanContent.startsWith('application/json') || - cleanContent.endsWith('+json') - ) { - return 'json'; - } - - if (cleanContent === 'multipart/form-data') { - return 'formData'; - } - - if ( - ['application/', 'audio/', 'image/', 'video/'].some((type) => - cleanContent.startsWith(type), - ) - ) { - return 'blob'; - } - - if (cleanContent.startsWith('text/')) { - return 'text'; - } - - return; -}; - -const checkForExistence = ( - options: Pick & { - headers: Headers; - }, - name?: string, -): boolean => { - if (!name) { - return false; - } - if ( - options.headers.has(name) || - options.query?.[name] || - options.headers.get('Cookie')?.includes(`${name}=`) - ) { - return true; - } - return false; -}; - -export const setAuthParams = async ({ - security, - ...options -}: Pick, 'security'> & - Pick & { - headers: Headers; - }) => { - for (const auth of security) { - if (checkForExistence(options, auth.name)) { - continue; - } - - const token = await getAuthToken(auth, options.auth); - - if (!token) { - continue; - } - - const name = auth.name ?? 'Authorization'; - - switch (auth.in) { - case 'query': - if (!options.query) { - options.query = {}; - } - options.query[name] = token; - break; - case 'cookie': - options.headers.append('Cookie', `${name}=${token}`); - break; - case 'header': - default: - options.headers.set(name, token); - break; - } - } -}; - -export const buildUrl: Client['buildUrl'] = (options) => - getUrl({ - baseUrl: options.baseUrl as string, - path: options.path, - query: options.query, - querySerializer: - typeof options.querySerializer === 'function' - ? options.querySerializer - : createQuerySerializer(options.querySerializer), - url: options.url, - }); - -export const mergeConfigs = (a: Config, b: Config): Config => { - const config = { ...a, ...b }; - if (config.baseUrl?.endsWith('/')) { - config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); - } - config.headers = mergeHeaders(a.headers, b.headers); - return config; -}; - -const headersEntries = (headers: Headers): Array<[string, string]> => { - const entries: Array<[string, string]> = []; - headers.forEach((value, key) => { - entries.push([key, value]); - }); - return entries; -}; - -export const mergeHeaders = ( - ...headers: Array['headers'] | undefined> -): Headers => { - const mergedHeaders = new Headers(); - for (const header of headers) { - if (!header) { - continue; - } - - const iterator = - header instanceof Headers - ? headersEntries(header) - : Object.entries(header); - - for (const [key, value] of iterator) { - if (value === null) { - mergedHeaders.delete(key); - } else if (Array.isArray(value)) { - for (const v of value) { - mergedHeaders.append(key, v as string); - } - } else if (value !== undefined) { - // assume object headers are meant to be JSON stringified, i.e. their - // content value in OpenAPI specification is 'application/json' - mergedHeaders.set( - key, - typeof value === 'object' ? JSON.stringify(value) : (value as string), - ); - } - } - } - return mergedHeaders; -}; - -type ErrInterceptor = ( - error: Err, - response: Res, - request: Req, - options: Options, -) => Err | Promise; - -type ReqInterceptor = ( - request: Req, - options: Options, -) => Req | Promise; - -type ResInterceptor = ( - response: Res, - request: Req, - options: Options, -) => Res | Promise; - -class Interceptors { - fns: Array = []; - - clear(): void { - this.fns = []; - } - - eject(id: number | Interceptor): void { - const index = this.getInterceptorIndex(id); - if (this.fns[index]) { - this.fns[index] = null; - } - } - - exists(id: number | Interceptor): boolean { - const index = this.getInterceptorIndex(id); - return Boolean(this.fns[index]); - } - - getInterceptorIndex(id: number | Interceptor): number { - if (typeof id === 'number') { - return this.fns[id] ? id : -1; - } - return this.fns.indexOf(id); - } - - update( - id: number | Interceptor, - fn: Interceptor, - ): number | Interceptor | false { - const index = this.getInterceptorIndex(id); - if (this.fns[index]) { - this.fns[index] = fn; - return id; - } - return false; - } - - use(fn: Interceptor): number { - this.fns.push(fn); - return this.fns.length - 1; - } -} - -export interface Middleware { - error: Interceptors>; - request: Interceptors>; - response: Interceptors>; -} - -export const createInterceptors = (): Middleware< - Req, - Res, - Err, - Options -> => ({ - error: new Interceptors>(), - request: new Interceptors>(), - response: new Interceptors>(), -}); - -const defaultQuerySerializer = createQuerySerializer({ - allowReserved: false, - array: { - explode: true, - style: 'form', - }, - object: { - explode: true, - style: 'deepObject', - }, -}); - -const defaultHeaders = { - 'Content-Type': 'application/json', -}; - -export const createConfig = ( - override: Config & T> = {}, -): Config & T> => ({ - ...jsonBodySerializer, - headers: defaultHeaders, - parseAs: 'auto', - querySerializer: defaultQuerySerializer, - ...override, -}); diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/auth.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/auth.gen.ts.snap deleted file mode 100644 index f8a73266f..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/auth.gen.ts.snap +++ /dev/null @@ -1,42 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type AuthToken = string | undefined; - -export interface Auth { - /** - * Which part of the request do we use to send the auth? - * - * @default 'header' - */ - in?: 'header' | 'query' | 'cookie'; - /** - * Header or query parameter name. - * - * @default 'Authorization' - */ - name?: string; - scheme?: 'basic' | 'bearer'; - type: 'apiKey' | 'http'; -} - -export const getAuthToken = async ( - auth: Auth, - callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, -): Promise => { - const token = - typeof callback === 'function' ? await callback(auth) : callback; - - if (!token) { - return; - } - - if (auth.scheme === 'bearer') { - return `Bearer ${token}`; - } - - if (auth.scheme === 'basic') { - return `Basic ${btoa(token)}`; - } - - return token; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/bodySerializer.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/bodySerializer.gen.ts.snap deleted file mode 100644 index 552b50f7c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/bodySerializer.gen.ts.snap +++ /dev/null @@ -1,100 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { - ArrayStyle, - ObjectStyle, - SerializerOptions, -} from './pathSerializer.gen'; - -export type QuerySerializer = (query: Record) => string; - -export type BodySerializer = (body: any) => any; - -type QuerySerializerOptionsObject = { - allowReserved?: boolean; - array?: Partial>; - object?: Partial>; -}; - -export type QuerySerializerOptions = QuerySerializerOptionsObject & { - /** - * Per-parameter serialization overrides. When provided, these settings - * override the global array/object settings for specific parameter names. - */ - parameters?: Record; -}; - -const serializeFormDataPair = ( - data: FormData, - key: string, - value: unknown, -): void => { - if (typeof value === 'string' || value instanceof Blob) { - data.append(key, value); - } else if (value instanceof Date) { - data.append(key, value.toISOString()); - } else { - data.append(key, JSON.stringify(value)); - } -}; - -const serializeUrlSearchParamsPair = ( - data: URLSearchParams, - key: string, - value: unknown, -): void => { - if (typeof value === 'string') { - data.append(key, value); - } else { - data.append(key, JSON.stringify(value)); - } -}; - -export const formDataBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): FormData => { - const data = new FormData(); - - Object.entries(body).forEach(([key, value]) => { - if (value === undefined || value === null) { - return; - } - if (Array.isArray(value)) { - value.forEach((v) => serializeFormDataPair(data, key, v)); - } else { - serializeFormDataPair(data, key, value); - } - }); - - return data; - }, -}; - -export const jsonBodySerializer = { - bodySerializer: (body: T): string => - JSON.stringify(body, (_key, value) => - typeof value === 'bigint' ? value.toString() : value, - ), -}; - -export const urlSearchParamsBodySerializer = { - bodySerializer: | Array>>( - body: T, - ): string => { - const data = new URLSearchParams(); - - Object.entries(body).forEach(([key, value]) => { - if (value === undefined || value === null) { - return; - } - if (Array.isArray(value)) { - value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); - } else { - serializeUrlSearchParamsPair(data, key, value); - } - }); - - return data.toString(); - }, -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/params.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/params.gen.ts.snap deleted file mode 100644 index 602715c46..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/params.gen.ts.snap +++ /dev/null @@ -1,176 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -type Slot = 'body' | 'headers' | 'path' | 'query'; - -export type Field = - | { - in: Exclude; - /** - * Field name. This is the name we want the user to see and use. - */ - key: string; - /** - * Field mapped name. This is the name we want to use in the request. - * If omitted, we use the same value as `key`. - */ - map?: string; - } - | { - in: Extract; - /** - * Key isn't required for bodies. - */ - key?: string; - map?: string; - } - | { - /** - * Field name. This is the name we want the user to see and use. - */ - key: string; - /** - * Field mapped name. This is the name we want to use in the request. - * If `in` is omitted, `map` aliases `key` to the transport layer. - */ - map: Slot; - }; - -export interface Fields { - allowExtra?: Partial>; - args?: ReadonlyArray; -} - -export type FieldsConfig = ReadonlyArray; - -const extraPrefixesMap: Record = { - $body_: 'body', - $headers_: 'headers', - $path_: 'path', - $query_: 'query', -}; -const extraPrefixes = Object.entries(extraPrefixesMap); - -type KeyMap = Map< - string, - | { - in: Slot; - map?: string; - } - | { - in?: never; - map: Slot; - } ->; - -const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { - if (!map) { - map = new Map(); - } - - for (const config of fields) { - if ('in' in config) { - if (config.key) { - map.set(config.key, { - in: config.in, - map: config.map, - }); - } - } else if ('key' in config) { - map.set(config.key, { - map: config.map, - }); - } else if (config.args) { - buildKeyMap(config.args, map); - } - } - - return map; -}; - -interface Params { - body: unknown; - headers: Record; - path: Record; - query: Record; -} - -const stripEmptySlots = (params: Params) => { - for (const [slot, value] of Object.entries(params)) { - if (value && typeof value === 'object' && !Object.keys(value).length) { - delete params[slot as Slot]; - } - } -}; - -export const buildClientParams = ( - args: ReadonlyArray, - fields: FieldsConfig, -) => { - const params: Params = { - body: {}, - headers: {}, - path: {}, - query: {}, - }; - - const map = buildKeyMap(fields); - - let config: FieldsConfig[number] | undefined; - - for (const [index, arg] of args.entries()) { - if (fields[index]) { - config = fields[index]; - } - - if (!config) { - continue; - } - - if ('in' in config) { - if (config.key) { - const field = map.get(config.key)!; - const name = field.map || config.key; - if (field.in) { - (params[field.in] as Record)[name] = arg; - } - } else { - params.body = arg; - } - } else { - for (const [key, value] of Object.entries(arg ?? {})) { - const field = map.get(key); - - if (field) { - if (field.in) { - const name = field.map || key; - (params[field.in] as Record)[name] = value; - } else { - params[field.map] = value; - } - } else { - const extra = extraPrefixes.find(([prefix]) => - key.startsWith(prefix), - ); - - if (extra) { - const [prefix, slot] = extra; - (params[slot] as Record)[ - key.slice(prefix.length) - ] = value; - } else if ('allowExtra' in config && config.allowExtra) { - for (const [slot, allowed] of Object.entries(config.allowExtra)) { - if (allowed) { - (params[slot as Slot] as Record)[key] = value; - break; - } - } - } - } - } - } - } - - stripEmptySlots(params); - - return params; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/pathSerializer.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/pathSerializer.gen.ts.snap deleted file mode 100644 index 8d9993104..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/pathSerializer.gen.ts.snap +++ /dev/null @@ -1,181 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -interface SerializeOptions - extends SerializePrimitiveOptions, - SerializerOptions {} - -interface SerializePrimitiveOptions { - allowReserved?: boolean; - name: string; -} - -export interface SerializerOptions { - /** - * @default true - */ - explode: boolean; - style: T; -} - -export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; -export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; -type MatrixStyle = 'label' | 'matrix' | 'simple'; -export type ObjectStyle = 'form' | 'deepObject'; -type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; - -interface SerializePrimitiveParam extends SerializePrimitiveOptions { - value: string; -} - -export const separatorArrayExplode = (style: ArraySeparatorStyle) => { - switch (style) { - case 'label': - return '.'; - case 'matrix': - return ';'; - case 'simple': - return ','; - default: - return '&'; - } -}; - -export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { - switch (style) { - case 'form': - return ','; - case 'pipeDelimited': - return '|'; - case 'spaceDelimited': - return '%20'; - default: - return ','; - } -}; - -export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { - switch (style) { - case 'label': - return '.'; - case 'matrix': - return ';'; - case 'simple': - return ','; - default: - return '&'; - } -}; - -export const serializeArrayParam = ({ - allowReserved, - explode, - name, - style, - value, -}: SerializeOptions & { - value: unknown[]; -}) => { - if (!explode) { - const joinedValues = ( - allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) - ).join(separatorArrayNoExplode(style)); - switch (style) { - case 'label': - return `.${joinedValues}`; - case 'matrix': - return `;${name}=${joinedValues}`; - case 'simple': - return joinedValues; - default: - return `${name}=${joinedValues}`; - } - } - - const separator = separatorArrayExplode(style); - const joinedValues = value - .map((v) => { - if (style === 'label' || style === 'simple') { - return allowReserved ? v : encodeURIComponent(v as string); - } - - return serializePrimitiveParam({ - allowReserved, - name, - value: v as string, - }); - }) - .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; -}; - -export const serializePrimitiveParam = ({ - allowReserved, - name, - value, -}: SerializePrimitiveParam) => { - if (value === undefined || value === null) { - return ''; - } - - if (typeof value === 'object') { - throw new Error( - 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', - ); - } - - return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; -}; - -export const serializeObjectParam = ({ - allowReserved, - explode, - name, - style, - value, - valueOnly, -}: SerializeOptions & { - value: Record | Date; - valueOnly?: boolean; -}) => { - if (value instanceof Date) { - return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; - } - - if (style !== 'deepObject' && !explode) { - let values: string[] = []; - Object.entries(value).forEach(([key, v]) => { - values = [ - ...values, - key, - allowReserved ? (v as string) : encodeURIComponent(v as string), - ]; - }); - const joinedValues = values.join(','); - switch (style) { - case 'form': - return `${name}=${joinedValues}`; - case 'label': - return `.${joinedValues}`; - case 'matrix': - return `;${name}=${joinedValues}`; - default: - return joinedValues; - } - } - - const separator = separatorObjectExplode(style); - const joinedValues = Object.entries(value) - .map(([key, v]) => - serializePrimitiveParam({ - allowReserved, - name: style === 'deepObject' ? `${name}[${key}]` : key, - value: v as string, - }), - ) - .join(separator); - return style === 'label' || style === 'matrix' - ? separator + joinedValues - : joinedValues; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/queryKeySerializer.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/queryKeySerializer.gen.ts.snap deleted file mode 100644 index d3bb68396..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/queryKeySerializer.gen.ts.snap +++ /dev/null @@ -1,136 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * JSON-friendly union that mirrors what Pinia Colada can hash. - */ -export type JsonValue = - | null - | string - | number - | boolean - | JsonValue[] - | { [key: string]: JsonValue }; - -/** - * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. - */ -export const queryKeyJsonReplacer = (_key: string, value: unknown) => { - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { - return undefined; - } - if (typeof value === 'bigint') { - return value.toString(); - } - if (value instanceof Date) { - return value.toISOString(); - } - return value; -}; - -/** - * Safely stringifies a value and parses it back into a JsonValue. - */ -export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { - try { - const json = JSON.stringify(input, queryKeyJsonReplacer); - if (json === undefined) { - return undefined; - } - return JSON.parse(json) as JsonValue; - } catch { - return undefined; - } -}; - -/** - * Detects plain objects (including objects with a null prototype). - */ -const isPlainObject = (value: unknown): value is Record => { - if (value === null || typeof value !== 'object') { - return false; - } - const prototype = Object.getPrototypeOf(value as object); - return prototype === Object.prototype || prototype === null; -}; - -/** - * Turns URLSearchParams into a sorted JSON object for deterministic keys. - */ -const serializeSearchParams = (params: URLSearchParams): JsonValue => { - const entries = Array.from(params.entries()).sort(([a], [b]) => - a.localeCompare(b), - ); - const result: Record = {}; - - for (const [key, value] of entries) { - const existing = result[key]; - if (existing === undefined) { - result[key] = value; - continue; - } - - if (Array.isArray(existing)) { - (existing as string[]).push(value); - } else { - result[key] = [existing, value]; - } - } - - return result; -}; - -/** - * Normalizes any accepted value into a JSON-friendly shape for query keys. - */ -export const serializeQueryKeyValue = ( - value: unknown, -): JsonValue | undefined => { - if (value === null) { - return null; - } - - if ( - typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' - ) { - return value; - } - - if ( - value === undefined || - typeof value === 'function' || - typeof value === 'symbol' - ) { - return undefined; - } - - if (typeof value === 'bigint') { - return value.toString(); - } - - if (value instanceof Date) { - return value.toISOString(); - } - - if (Array.isArray(value)) { - return stringifyToJsonValue(value); - } - - if ( - typeof URLSearchParams !== 'undefined' && - value instanceof URLSearchParams - ) { - return serializeSearchParams(value); - } - - if (isPlainObject(value)) { - return stringifyToJsonValue(value); - } - - return undefined; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/serverSentEvents.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/serverSentEvents.gen.ts.snap deleted file mode 100644 index f8fd78e28..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/serverSentEvents.gen.ts.snap +++ /dev/null @@ -1,264 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { Config } from './types.gen'; - -export type ServerSentEventsOptions = Omit< - RequestInit, - 'method' -> & - Pick & { - /** - * Fetch API implementation. You can use this option to provide a custom - * fetch instance. - * - * @default globalThis.fetch - */ - fetch?: typeof fetch; - /** - * Implementing clients can call request interceptors inside this hook. - */ - onRequest?: (url: string, init: RequestInit) => Promise; - /** - * Callback invoked when a network or parsing error occurs during streaming. - * - * This option applies only if the endpoint returns a stream of events. - * - * @param error The error that occurred. - */ - onSseError?: (error: unknown) => void; - /** - * Callback invoked when an event is streamed from the server. - * - * This option applies only if the endpoint returns a stream of events. - * - * @param event Event streamed from the server. - * @returns Nothing (void). - */ - onSseEvent?: (event: StreamEvent) => void; - serializedBody?: RequestInit['body']; - /** - * Default retry delay in milliseconds. - * - * This option applies only if the endpoint returns a stream of events. - * - * @default 3000 - */ - sseDefaultRetryDelay?: number; - /** - * Maximum number of retry attempts before giving up. - */ - sseMaxRetryAttempts?: number; - /** - * Maximum retry delay in milliseconds. - * - * Applies only when exponential backoff is used. - * - * This option applies only if the endpoint returns a stream of events. - * - * @default 30000 - */ - sseMaxRetryDelay?: number; - /** - * Optional sleep function for retry backoff. - * - * Defaults to using `setTimeout`. - */ - sseSleepFn?: (ms: number) => Promise; - url: string; - }; - -export interface StreamEvent { - data: TData; - event?: string; - id?: string; - retry?: number; -} - -export type ServerSentEventsResult< - TData = unknown, - TReturn = void, - TNext = unknown, -> = { - stream: AsyncGenerator< - TData extends Record ? TData[keyof TData] : TData, - TReturn, - TNext - >; -}; - -export const createSseClient = ({ - onRequest, - onSseError, - onSseEvent, - responseTransformer, - responseValidator, - sseDefaultRetryDelay, - sseMaxRetryAttempts, - sseMaxRetryDelay, - sseSleepFn, - url, - ...options -}: ServerSentEventsOptions): ServerSentEventsResult => { - let lastEventId: string | undefined; - - const sleep = - sseSleepFn ?? - ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); - - const createStream = async function* () { - let retryDelay: number = sseDefaultRetryDelay ?? 3000; - let attempt = 0; - const signal = options.signal ?? new AbortController().signal; - - while (true) { - if (signal.aborted) break; - - attempt++; - - const headers = - options.headers instanceof Headers - ? options.headers - : new Headers(options.headers as Record | undefined); - - if (lastEventId !== undefined) { - headers.set('Last-Event-ID', lastEventId); - } - - try { - const requestInit: RequestInit = { - redirect: 'follow', - ...options, - body: options.serializedBody, - headers, - signal, - }; - let request = new Request(url, requestInit); - if (onRequest) { - request = await onRequest(url, requestInit); - } - // fetch must be assigned here, otherwise it would throw the error: - // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation - const _fetch = options.fetch ?? globalThis.fetch; - const response = await _fetch(request); - - if (!response.ok) - throw new Error( - `SSE failed: ${response.status} ${response.statusText}`, - ); - - if (!response.body) throw new Error('No body in SSE response'); - - const reader = response.body - .pipeThrough(new TextDecoderStream()) - .getReader(); - - let buffer = ''; - - const abortHandler = () => { - try { - reader.cancel(); - } catch { - // noop - } - }; - - signal.addEventListener('abort', abortHandler); - - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += value; - - const chunks = buffer.split('\n\n'); - buffer = chunks.pop() ?? ''; - - for (const chunk of chunks) { - const lines = chunk.split('\n'); - const dataLines: Array = []; - let eventName: string | undefined; - - for (const line of lines) { - if (line.startsWith('data:')) { - dataLines.push(line.replace(/^data:\s*/, '')); - } else if (line.startsWith('event:')) { - eventName = line.replace(/^event:\s*/, ''); - } else if (line.startsWith('id:')) { - lastEventId = line.replace(/^id:\s*/, ''); - } else if (line.startsWith('retry:')) { - const parsed = Number.parseInt( - line.replace(/^retry:\s*/, ''), - 10, - ); - if (!Number.isNaN(parsed)) { - retryDelay = parsed; - } - } - } - - let data: unknown; - let parsedJson = false; - - if (dataLines.length) { - const rawData = dataLines.join('\n'); - try { - data = JSON.parse(rawData); - parsedJson = true; - } catch { - data = rawData; - } - } - - if (parsedJson) { - if (responseValidator) { - await responseValidator(data); - } - - if (responseTransformer) { - data = await responseTransformer(data); - } - } - - onSseEvent?.({ - data, - event: eventName, - id: lastEventId, - retry: retryDelay, - }); - - if (dataLines.length) { - yield data as any; - } - } - } - } finally { - signal.removeEventListener('abort', abortHandler); - reader.releaseLock(); - } - - break; // exit loop on normal completion - } catch (error) { - // connection failed or aborted; retry after delay - onSseError?.(error); - - if ( - sseMaxRetryAttempts !== undefined && - attempt >= sseMaxRetryAttempts - ) { - break; // stop after firing error - } - - // exponential backoff: double retry each attempt, cap at 30s - const backoff = Math.min( - retryDelay * 2 ** (attempt - 1), - sseMaxRetryDelay ?? 30000, - ); - await sleep(backoff); - } - } - }; - - const stream = createStream(); - - return { stream }; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/types.gen.ts.snap deleted file mode 100644 index 643c070c9..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/types.gen.ts.snap +++ /dev/null @@ -1,118 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { Auth, AuthToken } from './auth.gen'; -import type { - BodySerializer, - QuerySerializer, - QuerySerializerOptions, -} from './bodySerializer.gen'; - -export type HttpMethod = - | 'connect' - | 'delete' - | 'get' - | 'head' - | 'options' - | 'patch' - | 'post' - | 'put' - | 'trace'; - -export type Client< - RequestFn = never, - Config = unknown, - MethodFn = never, - BuildUrlFn = never, - SseFn = never, -> = { - /** - * Returns the final request URL. - */ - buildUrl: BuildUrlFn; - getConfig: () => Config; - request: RequestFn; - setConfig: (config: Config) => Config; -} & { - [K in HttpMethod]: MethodFn; -} & ([SseFn] extends [never] - ? { sse?: never } - : { sse: { [K in HttpMethod]: SseFn } }); - -export interface Config { - /** - * Auth token or a function returning auth token. The resolved value will be - * added to the request payload as defined by its `security` array. - */ - auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; - /** - * A function for serializing request body parameter. By default, - * {@link JSON.stringify()} will be used. - */ - bodySerializer?: BodySerializer | null; - /** - * An object containing any HTTP headers that you want to pre-populate your - * `Headers` object with. - * - * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} - */ - headers?: - | RequestInit['headers'] - | Record< - string, - | string - | number - | boolean - | (string | number | boolean)[] - | null - | undefined - | unknown - >; - /** - * The request method. - * - * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} - */ - method?: Uppercase; - /** - * A function for serializing request query parameters. By default, arrays - * will be exploded in form style, objects will be exploded in deepObject - * style, and reserved characters are percent-encoded. - * - * This method will have no effect if the native `paramsSerializer()` Axios - * API function is used. - * - * {@link https://swagger.io/docs/specification/serialization/#query View examples} - */ - querySerializer?: QuerySerializer | QuerySerializerOptions; - /** - * A function validating request data. This is useful if you want to ensure - * the request conforms to the desired shape, so it can be safely sent to - * the server. - */ - requestValidator?: (data: unknown) => Promise; - /** - * A function transforming response data before it's returned. This is useful - * for post-processing data, e.g. converting ISO strings into Date objects. - */ - responseTransformer?: (data: unknown) => Promise; - /** - * A function validating response data. This is useful if you want to ensure - * the response conforms to the desired shape, so it can be safely passed to - * the transformers and returned to the user. - */ - responseValidator?: (data: unknown) => Promise; -} - -type IsExactlyNeverOrNeverUndefined = [T] extends [never] - ? true - : [T] extends [never | undefined] - ? [undefined] extends [T] - ? false - : true - : false; - -export type OmitNever> = { - [K in keyof T as IsExactlyNeverOrNeverUndefined extends true - ? never - : K]: T[K]; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/utils.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/utils.gen.ts.snap deleted file mode 100644 index 0b5389d08..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/core/utils.gen.ts.snap +++ /dev/null @@ -1,143 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; -import { - type ArraySeparatorStyle, - serializeArrayParam, - serializeObjectParam, - serializePrimitiveParam, -} from './pathSerializer.gen'; - -export interface PathSerializer { - path: Record; - url: string; -} - -export const PATH_PARAM_RE = /\{[^{}]+\}/g; - -export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => { - let url = _url; - const matches = _url.match(PATH_PARAM_RE); - if (matches) { - for (const match of matches) { - let explode = false; - let name = match.substring(1, match.length - 1); - let style: ArraySeparatorStyle = 'simple'; - - if (name.endsWith('*')) { - explode = true; - name = name.substring(0, name.length - 1); - } - - if (name.startsWith('.')) { - name = name.substring(1); - style = 'label'; - } else if (name.startsWith(';')) { - name = name.substring(1); - style = 'matrix'; - } - - const value = path[name]; - - if (value === undefined || value === null) { - continue; - } - - if (Array.isArray(value)) { - url = url.replace( - match, - serializeArrayParam({ explode, name, style, value }), - ); - continue; - } - - if (typeof value === 'object') { - url = url.replace( - match, - serializeObjectParam({ - explode, - name, - style, - value: value as Record, - valueOnly: true, - }), - ); - continue; - } - - if (style === 'matrix') { - url = url.replace( - match, - `;${serializePrimitiveParam({ - name, - value: value as string, - })}`, - ); - continue; - } - - const replaceValue = encodeURIComponent( - style === 'label' ? `.${value as string}` : (value as string), - ); - url = url.replace(match, replaceValue); - } - } - return url; -}; - -export const getUrl = ({ - baseUrl, - path, - query, - querySerializer, - url: _url, -}: { - baseUrl?: string; - path?: Record; - query?: Record; - querySerializer: QuerySerializer; - url: string; -}) => { - const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; - let url = (baseUrl ?? '') + pathUrl; - if (path) { - url = defaultPathSerializer({ path, url }); - } - let search = query ? querySerializer(query) : ''; - if (search.startsWith('?')) { - search = search.substring(1); - } - if (search) { - url += `?${search}`; - } - return url; -}; - -export function getValidRequestBody(options: { - body?: unknown; - bodySerializer?: BodySerializer | null; - serializedBody?: unknown; -}) { - const hasBody = options.body !== undefined; - const isSerializedBody = hasBody && options.bodySerializer; - - if (isSerializedBody) { - if ('serializedBody' in options) { - const hasSerializedBody = - options.serializedBody !== undefined && options.serializedBody !== ''; - - return hasSerializedBody ? options.serializedBody : null; - } - - // not all clients implement a serializedBody property (i.e. client-axios) - return options.body !== '' ? options.body : null; - } - - // plain/text body - if (hasBody) { - return options.body; - } - - // no body was provided - return undefined; -} diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/types.gen.ts.snap deleted file mode 100644 index f350f691f..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_no_index/types.gen.ts.snap +++ /dev/null @@ -1,1996 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type ClientOptions = { - baseUrl: 'http://localhost:3000/base' | (string & {}); -}; - -/** - * Model with number-only name - */ -export type _400 = string; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CamelCaseCommentWithBreaks = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; - -/** - * This is a simple file - */ -export type SimpleFile = unknown; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = string; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: CamelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<{ - foo?: string; -} | { - bar?: string; -}>; - -export type AnyOfAnyAndNull = { - data?: unknown | null; -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<{ - foo?: string; - } | { - bar?: string; - }>; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type ModelFromZendesk = string; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: string; - /** - * This is a simple string property - */ - nullableRequiredProp1: string; - /** - * This is a simple string property - */ - nullableProp2?: string | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: string | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: true; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - /** - * Foo-Bar-Baz-Qux - */ - 'foo-bar-baz-qux'?: '3.0'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a deprecated model with a deprecated property - * - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * - * @deprecated - */ - prop?: string; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * Circle - */ -export type ModelCircle = { - kind: string; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: string; - sideLength?: number; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ({ - kind: 'circle'; -} & ModelCircle) | ({ - kind: 'square'; -} & ModelSquare); - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: Array | Array; -}; - -export type _3eNum1Период = 'Bird' | 'Dog'; - -export type ConstValue = 'ConstValue'; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - /** - * Scopes - */ - propA?: Array<_3eNum1Период | ConstValue> | null; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: boolean | { - [key: string]: number; - }; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: { - boolean?: boolean; - } & ModelWithEnum & ModelWithArray & ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - age: number; - firstName: string; - lastname: string; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: string; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: string; - }; - }; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type File = { - /** - * Id - */ - readonly id?: string; - /** - * Updated at - */ - readonly updated_at?: string; - /** - * Created at - */ - readonly created_at?: string; - /** - * Mime - */ - mime: string; - /** - * File - */ - readonly file?: string; -}; - -export type Default = { - name?: string; -}; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -export type ModelWithConst = { - String?: 'String'; - number?: 0; - null?: null; - withType?: 'Some string'; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string | undefined; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: Array | null; -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: SimpleParameter; -} | { - bar: NonAsciiStringæøåÆøÅöôêÊ字符串; -}) & { - baz: number; - qux: number; -}; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - unknown, - unknown - ]; - foo: 'Corge'; -}; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: ModelWithNestedArrayEnumsData; -}; - -export type ModelWithNestedCompositionEnums = { - foo?: ModelWithNestedArrayEnumsDataFoo; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -export type ModelWithAnyOfConstantSizeArray = [ - number | string, - number | string, - number | string -]; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - number | string, - string -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - number | string, - number | string, - number | string -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - number | Import, - number | Import -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - number & string, - number & string -]; - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { - baz: number; - qux: number; -}; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * Model with restricted keyword name - */ -export type Import = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: unknown; -}; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number; -}; - -export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; - -export type GenericSchemaDuplicateIssue1SystemBoolean = { - item?: boolean; - error?: string; - readonly hasError?: boolean; - data?: { - [key: string]: never; - }; -}; - -export type GenericSchemaDuplicateIssue1SystemString = { - item?: string; - error?: string; - readonly hasError?: boolean; -}; - -/** - * This is a reusable parameter - */ -export type SimpleParameter = string; - -/** - * Parameter with illegal characters - */ -export type XFooBar = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleRequestBody = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleFormData = ModelWithString; - -export type ExportData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ImportData = { - body: ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type ImportResponses = { - /** - * Success - */ - 200: ModelFromZendesk; - /** - * Default success response - */ - default: ModelWithReadOnlyAndWriteOnly; -}; - -export type ImportResponse = ImportResponses[keyof ImportResponses]; - -export type FooWowData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type FooWowResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ApiVVersionODataControllerCountData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple/$count'; -}; - -export type ApiVVersionODataControllerCountResponses = { - /** - * Success - */ - 200: ModelFromZendesk; -}; - -export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; - -export type GetApiVbyApiVersionSimpleOperationData = { - body?: never; - path: { - /** - * foo in method - */ - foo_param: string; - }; - query?: never; - url: '/api/v{api-version}/simple:operation'; -}; - -export type GetApiVbyApiVersionSimpleOperationErrors = { - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; - -export type GetApiVbyApiVersionSimpleOperationResponses = { - /** - * Response is a simple number - */ - 200: number; -}; - -export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; - -export type DeleteCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type GetCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type HeadCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type OptionsCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PatchCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PostCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PutCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type DeleteFooData3 = { - body?: never; - headers: { - /** - * Parameter with illegal characters - */ - 'x-Foo-Bar': ModelWithString; - }; - path: { - /** - * foo in method - */ - foo_param: string; - /** - * bar in method - */ - BarParam: string; - }; - query?: never; - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; -}; - -export type CallWithDescriptionsData = { - body?: never; - path?: never; - query?: { - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - }; - url: '/api/v{api-version}/descriptions/'; -}; - -export type DeprecatedCallData = { - body?: never; - headers: { - /** - * This parameter is deprecated - * - * @deprecated - */ - parameter: DeprecatedModel; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/parameters/deprecated'; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the body - */ - body: { - [key: string]: unknown; - }; - headers: { - /** - * This is the parameter that goes into the header - */ - parameterHeader: string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - parameterPath: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; - foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the query params - */ - cursor: string; - }; - url: '/api/v{api-version}/parameters/{parameterPath}'; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter that goes into the body - */ - body: ModelWithString; - headers: { - /** - * This is the parameter that goes into the request header - */ - 'parameter.header': string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - 'parameter.path.1'?: string; - /** - * This is the parameter that goes into the path - */ - 'parameter-path-2'?: string; - /** - * This is the parameter that goes into the path - */ - 'PARAMETER-PATH-3'?: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - /** - * This is the parameter with a reserved keyword - */ - default?: string; - /** - * This is the parameter that goes into the request query params - */ - 'parameter-query': string; - }; - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is a required parameter - */ - body: ModelWithOneOfEnum; - path?: never; - query?: { - /** - * This is an optional parameter - */ - page?: number; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - body?: { - offset?: number; - }; - path?: never; - query: { - /** - * This is a required parameter - */ - parameter: Pageable; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; - -export type PostApiVbyApiVersionRequestBodyData = { - /** - * A reusable request body - */ - body?: SimpleRequestBody; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/requestBody/'; -}; - -export type PostApiVbyApiVersionFormDataData = { - /** - * A reusable request body - */ - body?: SimpleFormData; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/formData/'; -}; - -export type CallWithDefaultParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string with default value - */ - parameterString?: string; - /** - * This is a simple number with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallWithDefaultOptionalParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallToTestOrderOfParamsData = { - body?: never; - path?: never; - query: { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: string; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type DuplicateNameData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName2Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName3Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName4Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type CallWithNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no-content'; -}; - -export type CallWithNoContentResponseResponses = { - /** - * Success - */ - 204: void; -}; - -export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; - -export type CallWithResponseAndNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/response-and-no-content'; -}; - -export type CallWithResponseAndNoContentResponseResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; - -export type DummyAData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/a'; -}; - -export type DummyAResponses = { - 200: _400; -}; - -export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; - -export type DummyBData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/b'; -}; - -export type DummyBResponses = { - /** - * Success - */ - 204: void; -}; - -export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; - -export type CallWithResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponseResponses = { - default: Import; -}; - -export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; - -export type CallWithDuplicateResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithDuplicateResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for 4XX errors - */ - '4XX': DictionaryWithArray; - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; - -export type CallWithDuplicateResponsesResponses = { - /** - * Message for 200 response - */ - 200: ModelWithBoolean & ModelWithInteger; - /** - * Message for 201 response - */ - 201: ModelWithString; - /** - * Message for 202 response - */ - 202: ModelWithString; -}; - -export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; - -export type CallWithResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for default response - */ - default: ModelWithStringError; -}; - -export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; - -export type CallWithResponsesResponses = { - /** - * Message for 200 response - */ - 200: { - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; - }; - /** - * Message for 201 response - */ - 201: ModelThatExtends; - /** - * Message for 202 response - */ - 202: ModelThatExtendsExtends; -}; - -export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; - -export type CollectionFormatData = { - body?: never; - path?: never; - query: { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCSV: Array; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySSV: Array; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTSV: Array; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array; - }; - url: '/api/v{api-version}/collectionFormat'; -}; - -export type TypesData = { - body?: never; - path?: { - /** - * This is a number parameter - */ - id?: number; - }; - query: { - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is a string parameter - */ - parameterString: string; - /** - * This is a boolean parameter - */ - parameterBoolean: boolean; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - }; - /** - * This is an array parameter - */ - parameterArray: Array; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - }; - /** - * This is an enum parameter - */ - parameterEnum: 'Success' | 'Warning' | 'Error'; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; - }; - url: '/api/v{api-version}/types'; -}; - -export type TypesResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Response is a simple string - */ - 201: string; - /** - * Response is a simple boolean - */ - 202: boolean; - /** - * Response is a simple object - */ - 203: { - [key: string]: unknown; - }; -}; - -export type TypesResponse = TypesResponses[keyof TypesResponses]; - -export type UploadFileData = { - body: unknown; - path: { - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/upload'; -}; - -export type UploadFileResponses = { - 200: boolean; -}; - -export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; - -export type FileResponseData = { - body?: never; - path: { - id: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/file/{id}'; -}; - -export type FileResponseResponses = { - /** - * Success - */ - 200: unknown; -}; - -export type ComplexTypesData = { - body?: never; - path?: never; - query: { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; - }; - url: '/api/v{api-version}/complex'; -}; - -export type ComplexTypesErrors = { - /** - * 400 `server` error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type ComplexTypesResponses = { - /** - * Successful response - */ - 200: Array; -}; - -export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; - -export type MultipartResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type MultipartResponseResponses = { - /** - * OK - */ - 200: { - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; - }; -}; - -export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; - -export type MultipartRequestData = { - body?: { - content?: Blob | File; - data?: ModelWithString; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type ComplexParamsData = { - body?: { - readonly key: string; - name: string; - enabled?: boolean; - type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array; - listOfStrings?: Array; - parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; - readonly user?: { - readonly id?: number; - readonly name?: string; - }; - }; - path: { - id: number; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/complex/{id}'; -}; - -export type ComplexParamsResponses = { - /** - * Success - */ - 200: ModelWithString; -}; - -export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; - -export type CallWithResultFromHeaderData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/header'; -}; - -export type CallWithResultFromHeaderErrors = { - /** - * 400 server error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type CallWithResultFromHeaderResponses = { - /** - * Successful response - */ - 200: unknown; -}; - -export type TestErrorCodeData = { - body?: never; - path?: never; - query: { - /** - * Status code to return - */ - status: number; - }; - url: '/api/v{api-version}/error'; -}; - -export type TestErrorCodeErrors = { - /** - * Custom message: Internal Server Error - */ - 500: unknown; - /** - * Custom message: Not Implemented - */ - 501: unknown; - /** - * Custom message: Bad Gateway - */ - 502: unknown; - /** - * Custom message: Service Unavailable - */ - 503: unknown; -}; - -export type TestErrorCodeResponses = { - /** - * Custom message: Successful response - */ - 200: unknown; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - body?: never; - path?: never; - query: { - /** - * Dummy input param - */ - nonAsciiParamæøåÆØÅöôêÊ: number; - }; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { - /** - * Successful response - */ - 200: Array; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; - -export type PutWithFormUrlEncodedData = { - body: ArrayWithStrings; - path?: never; - query?: never; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/OpenAPI.ts.snap deleted file mode 100644 index 90c96f9a3..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/OpenAPI.ts.snap +++ /dev/null @@ -1,57 +0,0 @@ -import type { RequestInit, Response } from 'node-fetch'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/request.ts.snap deleted file mode 100644 index fa1ed3862..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import fetch, { FormData, Headers } from 'node-fetch'; -import type { RequestInit, Response } from 'node-fetch'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/sdk.gen.ts.snap deleted file mode 100644 index 4ef5fc431..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/sdk.gen.ts.snap +++ /dev/null @@ -1,890 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, ComplexParamsData, ComplexParamsResponse, PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, DeprecatedCallData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, FileResponseData, FileResponseResponse, PostApiFormDataData, CallWithResultFromHeaderResponse, MultipartRequestData, MultipartResponseResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData, DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, ApiVVersionODataControllerCountResponse, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; - -export class CollectionFormat { - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public static collectionFormat(data: CollectionFormatData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -export class Complex { - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public static complexTypes(data: ComplexTypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); - } - - /** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ - public static complexParams(data: ComplexParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); - } -} - -export class Default { - /** - * @throws ApiError - */ - public static export(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static patchApiNoTag(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ - public static import(data: ImportData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static fooWow(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ - public static getApiSimpleOperation(data: GetApiSimpleOperationData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); - } -} - -export class Defaults { - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(data: CallWithDefaultParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -export class Deprecated { - /** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ - public static deprecatedCall(data: DeprecatedCallData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); - } -} - -export class Descriptions { - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public static callWithDescriptions(data: CallWithDescriptionsData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -export class Duplicate { - /** - * @throws ApiError - */ - public static duplicateName(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName1(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName2(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName3(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -export class Error { - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public static testErrorCode(data: TestErrorCodeData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -export class FileResponse { - /** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ - public static fileResponse(data: FileResponseData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); - } -} - -export class FormData { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ - public static postApiFormData(data: PostApiFormDataData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } -} - -export class Header { - /** - * @returns string Successful response - * @throws ApiError - */ - public static callWithResultFromHeader(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class Multipart { - /** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static multipartRequest(data: MultipartRequestData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static multipartResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); - } -} - -export class MultipleTags1 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags2 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags3 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class NoContent { - /** - * @returns void Success - * @throws ApiError - */ - public static callWithNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -export class NonAsciiÆøåÆøÅöôêÊ { - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public static nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } - - /** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static putWithFormUrlEncoded(data: PutWithFormUrlEncodedData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} - -export class Parameters { - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public static deleteFoo(data: DeleteFooData3): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public static callWithParameters(data: CallWithParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public static callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public static getCallWithOptionalParam(data: GetCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static postCallWithOptionalParam(data: PostCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -export class RequestBody { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ - public static postApiRequestBody(data: PostApiRequestBodyData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); - } -} - -export class Response { - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns import - * @throws ApiError - */ - public static callWithResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public static callWithDuplicateResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public static callWithResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -export class Simple { - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public static apiVVersionODataControllerCount(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public static getCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static putCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static postCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static deleteCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static optionsCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static headCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static patchCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -export class Types { - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public static types(data: TypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); - } -} - -export class Upload { - /** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ - public static uploadFile(data: UploadFileData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/types.gen.ts.snap deleted file mode 100644 index 27c4b1682..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node/types.gen.ts.snap +++ /dev/null @@ -1,1549 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -export const _3e_num_1Период = { - BIRD: 'Bird', - DOG: 'Dog' -} as const; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -export const EnumWithReplacedCharacters = { - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'ØÆÅÔÖ_ØÆÅÔÖ字符串': 'øæåôöØÆÅÔÖ字符串', - '_3.1': 3.1, - EMPTY_STRING: '' -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export const EnumWithXEnumNames = { - zero: 0, - one: 1, - two: 2 -} as const; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export const ModelWithNestedArrayEnumsDataBar = { - BAZ: 'baz', - QUX: 'qux' -} as const; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export const ModelWithNestedArrayEnumsDataFoo = { - FOO: 'foo', - BAR: 'bar' -} as const; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResultFromHeaderResponse = (string); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/OpenAPI.ts.snap deleted file mode 100644 index 90c96f9a3..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/OpenAPI.ts.snap +++ /dev/null @@ -1,57 +0,0 @@ -import type { RequestInit, Response } from 'node-fetch'; -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/request.ts.snap deleted file mode 100644 index fa1ed3862..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import fetch, { FormData, Headers } from 'node-fetch'; -import type { RequestInit, Response } from 'node-fetch'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/sdk.gen.ts.snap deleted file mode 100644 index 6789f1a5d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/sdk.gen.ts.snap +++ /dev/null @@ -1,79 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import { type ParentModelWithDatesResponse, type ModelWithDatesResponse, type ModelWithDatesArrayResponse, type ArrayOfDatesResponse, type DateResponse, type MultipleResponsesResponse, ParentModelWithDatesResponseTransformer, ModelWithDatesResponseTransformer, ModelWithDatesArrayResponseTransformer } from './types.gen'; - -export class Default { - /** - * @returns ParentModelWithDates Success - * @returns unknown Success - * @throws ApiError - */ - public static parentModelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/model-with-dates', - responseTransformer: ParentModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates', - responseTransformer: ModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDatesArray(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates-array', - responseTransformer: ModelWithDatesArrayResponseTransformer - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static arrayOfDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/array-of-dates' - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static date(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/date' - }); - } - - /** - * @returns ModelWithDates Updated - * @returns SimpleModel Created - * @throws ApiError - */ - public static multipleResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/multiple-responses' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/types.gen.ts.snap deleted file mode 100644 index 5de1d89cc..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_node_transform/types.gen.ts.snap +++ /dev/null @@ -1,106 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model that contains a some dates - */ -export type ModelWithDates = { - id: number; - name: string; - readonly enabled: boolean; - readonly modified: Date; - readonly expires?: Date; -}; - -/** - * This is a model that contains a some dates and arrays - */ -export type ParentModelWithDates = { - id: number; - readonly modified?: Date; - items?: Array; - item?: ModelWithDates; - 'nullable-date'?: Array<(Date | null)>; - simpleItems?: Array; - simpleItem?: SimpleModel; - dates?: Array; - strings?: Array; -}; - -/** - * This is a model that contains a some dates - */ -export type SimpleModel = { - id: number; - name: string; - readonly enabled: boolean; -}; - -export type ParentModelWithDatesResponse = (ParentModelWithDates | unknown); - -export type ModelWithDatesResponse = (ModelWithDates); - -export type ModelWithDatesArrayResponse = (Array); - -export type ArrayOfDatesResponse = (Array); - -export type DateResponse = (Date); - -export type MultipleResponsesResponse = (Array | Array); - -export type ParentModelWithDatesResponseTransformer = (data: any) => Promise; - -export type ParentModelWithDatesModelResponseTransformer = (data: any) => ParentModelWithDates; - -export type ModelWithDatesModelResponseTransformer = (data: any) => ModelWithDates; - -export const ModelWithDatesModelResponseTransformer: ModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (data?.expires) { - data.expires = new Date(data.expires); - } - return data; -}; - -export const ParentModelWithDatesModelResponseTransformer: ParentModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (Array.isArray(data?.items)) { - data.items.forEach(ModelWithDatesModelResponseTransformer); - } - if (data?.item) { - ModelWithDatesModelResponseTransformer(data.item); - } - if (Array.isArray(data?.['nullable-date'])) { - data['nullable-date'] = data['nullable-date'].map(item => item ? new Date(item) : item); - } - if (Array.isArray(data?.dates)) { - data.dates = data.dates.map(item => item ? new Date(item) : item); - } - return data; -}; - -export const ParentModelWithDatesResponseTransformer: ParentModelWithDatesResponseTransformer = async (data) => { - if (data) { - ParentModelWithDatesModelResponseTransformer(data); - } - return data; -}; - -export type ModelWithDatesResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesResponseTransformer: ModelWithDatesResponseTransformer = async (data) => { - ModelWithDatesModelResponseTransformer(data); - return data; -}; - -export type ModelWithDatesArrayResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesArrayResponseTransformer: ModelWithDatesArrayResponseTransformer = async (data) => { - if (Array.isArray(data)) { - data.forEach(ModelWithDatesModelResponseTransformer); - } - return data; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/sdk.gen.ts.snap deleted file mode 100644 index 560ea23a9..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/sdk.gen.ts.snap +++ /dev/null @@ -1,83 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData } from './types.gen'; - -export class Defaults { - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(data: CallWithDefaultParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/types.gen.ts.snap deleted file mode 100644 index 3ee5e285c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_options/types.gen.ts.snap +++ /dev/null @@ -1,102 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/index.ts.snap deleted file mode 100644 index 81abc8221..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/index.ts.snap +++ /dev/null @@ -1,3 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/sdk.gen.ts.snap deleted file mode 100644 index ab8cd7396..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/sdk.gen.ts.snap +++ /dev/null @@ -1,75 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; - -/** - * @throws ApiError - */ -export const getCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const putCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const postCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const deleteCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const optionsCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const headCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const patchCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/types.gen.ts.snap deleted file mode 100644 index 54c9b51ce..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_filter/types.gen.ts.snap +++ /dev/null @@ -1,1102 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -export const _3e_num_1Период = { - BIRD: 'Bird', - DOG: 'Dog' -} as const; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -export const EnumWithReplacedCharacters = { - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'ØÆÅÔÖ_ØÆÅÔÖ字符串': 'øæåôöØÆÅÔÖ字符串', - '_3.1': 3.1, - EMPTY_STRING: '' -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export const EnumWithXEnumNames = { - zero: 0, - one: 1, - two: 2 -} as const; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export const ModelWithNestedArrayEnumsDataBar = { - BAZ: 'baz', - QUX: 'qux' -} as const; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export const ModelWithNestedArrayEnumsDataFoo = { - FOO: 'foo', - BAR: 'bar' -} as const; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/index.ts.snap deleted file mode 100644 index 81abc8221..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/index.ts.snap +++ /dev/null @@ -1,3 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/sdk.gen.ts.snap deleted file mode 100644 index f0eecd417..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/sdk.gen.ts.snap +++ /dev/null @@ -1,220 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, ApiVVersionODataControllerCountResponse } from './types.gen'; - -export class myAwesomeParametersApi { - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public static deleteFoo(data: DeleteFooData3): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public static callWithParameters(data: CallWithParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public static callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public static getCallWithOptionalParam(data: GetCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static postCallWithOptionalParam(data: PostCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -export class myAwesomeSimpleApi { - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public static apiVVersionODataControllerCount(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public static getCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static putCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static postCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static deleteCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static optionsCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static headCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static patchCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/types.gen.ts.snap deleted file mode 100644 index 9fb1e5b11..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_services_name/types.gen.ts.snap +++ /dev/null @@ -1,1207 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -export const _3e_num_1Период = { - BIRD: 'Bird', - DOG: 'Dog' -} as const; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -export const EnumWithReplacedCharacters = { - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'ØÆÅÔÖ_ØÆÅÔÖ字符串': 'øæåôöØÆÅÔÖ字符串', - '_3.1': 3.1, - EMPTY_STRING: '' -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export const EnumWithXEnumNames = { - zero: 0, - one: 1, - two: 2 -} as const; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export const ModelWithNestedArrayEnumsDataBar = { - BAZ: 'baz', - QUX: 'qux' -} as const; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export const ModelWithNestedArrayEnumsDataFoo = { - FOO: 'foo', - BAR: 'bar' -} as const; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/OpenAPI.ts.snap deleted file mode 100644 index 144e25744..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/request.ts.snap deleted file mode 100644 index 5458a2899..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; - -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/sdk.gen.ts.snap deleted file mode 100644 index 6789f1a5d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/sdk.gen.ts.snap +++ /dev/null @@ -1,79 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import { type ParentModelWithDatesResponse, type ModelWithDatesResponse, type ModelWithDatesArrayResponse, type ArrayOfDatesResponse, type DateResponse, type MultipleResponsesResponse, ParentModelWithDatesResponseTransformer, ModelWithDatesResponseTransformer, ModelWithDatesArrayResponseTransformer } from './types.gen'; - -export class Default { - /** - * @returns ParentModelWithDates Success - * @returns unknown Success - * @throws ApiError - */ - public static parentModelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/model-with-dates', - responseTransformer: ParentModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates', - responseTransformer: ModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDatesArray(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates-array', - responseTransformer: ModelWithDatesArrayResponseTransformer - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static arrayOfDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/array-of-dates' - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static date(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/date' - }); - } - - /** - * @returns ModelWithDates Updated - * @returns SimpleModel Created - * @throws ApiError - */ - public static multipleResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/multiple-responses' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/types.gen.ts.snap deleted file mode 100644 index 5de1d89cc..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_transform/types.gen.ts.snap +++ /dev/null @@ -1,106 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model that contains a some dates - */ -export type ModelWithDates = { - id: number; - name: string; - readonly enabled: boolean; - readonly modified: Date; - readonly expires?: Date; -}; - -/** - * This is a model that contains a some dates and arrays - */ -export type ParentModelWithDates = { - id: number; - readonly modified?: Date; - items?: Array; - item?: ModelWithDates; - 'nullable-date'?: Array<(Date | null)>; - simpleItems?: Array; - simpleItem?: SimpleModel; - dates?: Array; - strings?: Array; -}; - -/** - * This is a model that contains a some dates - */ -export type SimpleModel = { - id: number; - name: string; - readonly enabled: boolean; -}; - -export type ParentModelWithDatesResponse = (ParentModelWithDates | unknown); - -export type ModelWithDatesResponse = (ModelWithDates); - -export type ModelWithDatesArrayResponse = (Array); - -export type ArrayOfDatesResponse = (Array); - -export type DateResponse = (Date); - -export type MultipleResponsesResponse = (Array | Array); - -export type ParentModelWithDatesResponseTransformer = (data: any) => Promise; - -export type ParentModelWithDatesModelResponseTransformer = (data: any) => ParentModelWithDates; - -export type ModelWithDatesModelResponseTransformer = (data: any) => ModelWithDates; - -export const ModelWithDatesModelResponseTransformer: ModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (data?.expires) { - data.expires = new Date(data.expires); - } - return data; -}; - -export const ParentModelWithDatesModelResponseTransformer: ParentModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (Array.isArray(data?.items)) { - data.items.forEach(ModelWithDatesModelResponseTransformer); - } - if (data?.item) { - ModelWithDatesModelResponseTransformer(data.item); - } - if (Array.isArray(data?.['nullable-date'])) { - data['nullable-date'] = data['nullable-date'].map(item => item ? new Date(item) : item); - } - if (Array.isArray(data?.dates)) { - data.dates = data.dates.map(item => item ? new Date(item) : item); - } - return data; -}; - -export const ParentModelWithDatesResponseTransformer: ParentModelWithDatesResponseTransformer = async (data) => { - if (data) { - ParentModelWithDatesModelResponseTransformer(data); - } - return data; -}; - -export type ModelWithDatesResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesResponseTransformer: ModelWithDatesResponseTransformer = async (data) => { - ModelWithDatesModelResponseTransformer(data); - return data; -}; - -export type ModelWithDatesArrayResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesArrayResponseTransformer: ModelWithDatesArrayResponseTransformer = async (data) => { - if (Array.isArray(data)) { - data.forEach(ModelWithDatesModelResponseTransformer); - } - return data; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/index.ts.snap deleted file mode 100644 index 81abc8221..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/index.ts.snap +++ /dev/null @@ -1,3 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/sdk.gen.ts.snap deleted file mode 100644 index 01dbca473..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/sdk.gen.ts.snap +++ /dev/null @@ -1,799 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, ApiVVersionODataControllerCountResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, DeleteFooData3, CallWithDescriptionsData, DeprecatedCallData, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, PostApiFormDataData, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, DummyAResponse, DummyBResponse, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, CollectionFormatData, TypesData, TypesResponse, UploadFileData, UploadFileResponse, FileResponseData, FileResponseResponse, ComplexTypesData, ComplexTypesResponse, MultipartRequestData, MultipartResponseResponse, ComplexParamsData, ComplexParamsResponse, CallWithResultFromHeaderResponse, TestErrorCodeData, TestErrorCodeResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData } from './types.gen'; - -/** - * @throws ApiError - */ -export const export_ = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); -}; - -/** - * @returns unknown OK - * @throws ApiError - */ -export const patchApiNoTag = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); -}; - -/** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ -export const import_ = (data: ImportData): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @returns unknown OK - * @throws ApiError - */ -export const fooWow = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); -}; - -/** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ -export const apiVVersionODataControllerCount = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); -}; - -/** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ -export const getApiSimpleOperation = (data: GetApiSimpleOperationData): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); -}; - -/** - * @throws ApiError - */ -export const getCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const putCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const postCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const deleteCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const optionsCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const headCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @throws ApiError - */ -export const patchCallWithoutParametersAndResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); -}; - -/** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ -export const deleteFoo = (data: DeleteFooData3): CancelablePromise => { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ -export const callWithDescriptions = (data: CallWithDescriptionsData = {}): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); -}; - -/** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ -export const deprecatedCall = (data: DeprecatedCallData): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ -export const callWithParameters = (data: CallWithParametersData): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ -export const callWithWeirdParameterNames = (data: CallWithWeirdParameterNamesData): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ -export const getCallWithOptionalParam = (data: GetCallWithOptionalParamData): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ -export const postCallWithOptionalParam = (data: PostCallWithOptionalParamData): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ -export const postApiRequestBody = (data: PostApiRequestBodyData = {}): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ -export const postApiFormData = (data: PostApiFormDataData = {}): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ -export const callWithDefaultParameters = (data: CallWithDefaultParametersData = {}): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ -export const callWithDefaultOptionalParameters = (data: CallWithDefaultOptionalParametersData = {}): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ -export const callToTestOrderOfParams = (data: CallToTestOrderOfParamsData): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName1 = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName2 = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @throws ApiError - */ -export const duplicateName3 = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); -}; - -/** - * @returns void Success - * @throws ApiError - */ -export const callWithNoContentResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); -}; - -/** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ -export const callWithResponseAndNoContentResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); -}; - -/** - * @returns _400 - * @throws ApiError - */ -export const dummyA = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); -}; - -/** - * @returns void Success - * @throws ApiError - */ -export const dummyB = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); -}; - -/** - * @returns import - * @throws ApiError - */ -export const callWithResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/response' - }); -}; - -/** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ -export const callWithDuplicateResponses = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); -}; - -/** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ -export const callWithResponses = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ -export const collectionFormat = (data: CollectionFormatData): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ -export const types = (data: TypesData): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); -}; - -/** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ -export const uploadFile = (data: UploadFileData): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); -}; - -/** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ -export const fileResponse = (data: FileResponseData): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); -}; - -/** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ -export const complexTypes = (data: ComplexTypesData): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ -export const multipartRequest = (data: MultipartRequestData = {}): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); -}; - -/** - * @returns unknown OK - * @throws ApiError - */ -export const multipartResponse = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); -}; - -/** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ -export const complexParams = (data: ComplexParamsData): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); -}; - -/** - * @returns string Successful response - * @throws ApiError - */ -export const callWithResultFromHeader = (): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ -export const testErrorCode = (data: TestErrorCodeData): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); -}; - -/** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ -export const nonAsciiæøåÆøÅöôêÊ字符串 = (data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise => { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); -}; - -/** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ -export const putWithFormUrlEncoded = (data: PutWithFormUrlEncodedData): CancelablePromise => { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/types.gen.ts.snap deleted file mode 100644 index ecb4fde89..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_tree_shakeable/types.gen.ts.snap +++ /dev/null @@ -1,1549 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -export const _3e_num_1Период = { - BIRD: 'Bird', - DOG: 'Dog' -} as const; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -export const EnumWithReplacedCharacters = { - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'ØÆÅÔÖ_ØÆÅÔÖ字符串': 'øæåôöØÆÅÔÖ字符串', - '_3.1': 3.1, - EMPTY_STRING: '' -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export const EnumWithXEnumNames = { - zero: 0, - one: 1, - two: 2 -} as const; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export const ModelWithNestedArrayEnumsDataBar = { - BAZ: 'baz', - QUX: 'qux' -} as const; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export const ModelWithNestedArrayEnumsDataFoo = { - FOO: 'foo', - BAR: 'bar' -} as const; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type CallWithResultFromHeaderResponse = (string); - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/index.ts.snap deleted file mode 100644 index b43a5238d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/index.ts.snap +++ /dev/null @@ -1,3 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type * from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/types.gen.ts.snap deleted file mode 100644 index f350f691f..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types/types.gen.ts.snap +++ /dev/null @@ -1,1996 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type ClientOptions = { - baseUrl: 'http://localhost:3000/base' | (string & {}); -}; - -/** - * Model with number-only name - */ -export type _400 = string; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CamelCaseCommentWithBreaks = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; - -/** - * This is a simple file - */ -export type SimpleFile = unknown; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = string; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: CamelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<{ - foo?: string; -} | { - bar?: string; -}>; - -export type AnyOfAnyAndNull = { - data?: unknown | null; -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<{ - foo?: string; - } | { - bar?: string; - }>; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type ModelFromZendesk = string; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: string; - /** - * This is a simple string property - */ - nullableRequiredProp1: string; - /** - * This is a simple string property - */ - nullableProp2?: string | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: string | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: true; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - /** - * Foo-Bar-Baz-Qux - */ - 'foo-bar-baz-qux'?: '3.0'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a deprecated model with a deprecated property - * - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * - * @deprecated - */ - prop?: string; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * Circle - */ -export type ModelCircle = { - kind: string; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: string; - sideLength?: number; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ({ - kind: 'circle'; -} & ModelCircle) | ({ - kind: 'square'; -} & ModelSquare); - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: Array | Array; -}; - -export type _3eNum1Период = 'Bird' | 'Dog'; - -export type ConstValue = 'ConstValue'; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - /** - * Scopes - */ - propA?: Array<_3eNum1Период | ConstValue> | null; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: boolean | { - [key: string]: number; - }; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: { - boolean?: boolean; - } & ModelWithEnum & ModelWithArray & ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - age: number; - firstName: string; - lastname: string; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: string; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: string; - }; - }; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type File = { - /** - * Id - */ - readonly id?: string; - /** - * Updated at - */ - readonly updated_at?: string; - /** - * Created at - */ - readonly created_at?: string; - /** - * Mime - */ - mime: string; - /** - * File - */ - readonly file?: string; -}; - -export type Default = { - name?: string; -}; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -export type ModelWithConst = { - String?: 'String'; - number?: 0; - null?: null; - withType?: 'Some string'; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string | undefined; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: Array | null; -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: SimpleParameter; -} | { - bar: NonAsciiStringæøåÆøÅöôêÊ字符串; -}) & { - baz: number; - qux: number; -}; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - unknown, - unknown - ]; - foo: 'Corge'; -}; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: ModelWithNestedArrayEnumsData; -}; - -export type ModelWithNestedCompositionEnums = { - foo?: ModelWithNestedArrayEnumsDataFoo; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -export type ModelWithAnyOfConstantSizeArray = [ - number | string, - number | string, - number | string -]; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - number | string, - string -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - number | string, - number | string, - number | string -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - number | Import, - number | Import -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - number & string, - number & string -]; - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { - baz: number; - qux: number; -}; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * Model with restricted keyword name - */ -export type Import = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: unknown; -}; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number; -}; - -export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; - -export type GenericSchemaDuplicateIssue1SystemBoolean = { - item?: boolean; - error?: string; - readonly hasError?: boolean; - data?: { - [key: string]: never; - }; -}; - -export type GenericSchemaDuplicateIssue1SystemString = { - item?: string; - error?: string; - readonly hasError?: boolean; -}; - -/** - * This is a reusable parameter - */ -export type SimpleParameter = string; - -/** - * Parameter with illegal characters - */ -export type XFooBar = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleRequestBody = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleFormData = ModelWithString; - -export type ExportData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ImportData = { - body: ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type ImportResponses = { - /** - * Success - */ - 200: ModelFromZendesk; - /** - * Default success response - */ - default: ModelWithReadOnlyAndWriteOnly; -}; - -export type ImportResponse = ImportResponses[keyof ImportResponses]; - -export type FooWowData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type FooWowResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ApiVVersionODataControllerCountData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple/$count'; -}; - -export type ApiVVersionODataControllerCountResponses = { - /** - * Success - */ - 200: ModelFromZendesk; -}; - -export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; - -export type GetApiVbyApiVersionSimpleOperationData = { - body?: never; - path: { - /** - * foo in method - */ - foo_param: string; - }; - query?: never; - url: '/api/v{api-version}/simple:operation'; -}; - -export type GetApiVbyApiVersionSimpleOperationErrors = { - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; - -export type GetApiVbyApiVersionSimpleOperationResponses = { - /** - * Response is a simple number - */ - 200: number; -}; - -export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; - -export type DeleteCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type GetCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type HeadCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type OptionsCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PatchCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PostCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PutCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type DeleteFooData3 = { - body?: never; - headers: { - /** - * Parameter with illegal characters - */ - 'x-Foo-Bar': ModelWithString; - }; - path: { - /** - * foo in method - */ - foo_param: string; - /** - * bar in method - */ - BarParam: string; - }; - query?: never; - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; -}; - -export type CallWithDescriptionsData = { - body?: never; - path?: never; - query?: { - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - }; - url: '/api/v{api-version}/descriptions/'; -}; - -export type DeprecatedCallData = { - body?: never; - headers: { - /** - * This parameter is deprecated - * - * @deprecated - */ - parameter: DeprecatedModel; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/parameters/deprecated'; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the body - */ - body: { - [key: string]: unknown; - }; - headers: { - /** - * This is the parameter that goes into the header - */ - parameterHeader: string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - parameterPath: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; - foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the query params - */ - cursor: string; - }; - url: '/api/v{api-version}/parameters/{parameterPath}'; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter that goes into the body - */ - body: ModelWithString; - headers: { - /** - * This is the parameter that goes into the request header - */ - 'parameter.header': string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - 'parameter.path.1'?: string; - /** - * This is the parameter that goes into the path - */ - 'parameter-path-2'?: string; - /** - * This is the parameter that goes into the path - */ - 'PARAMETER-PATH-3'?: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - /** - * This is the parameter with a reserved keyword - */ - default?: string; - /** - * This is the parameter that goes into the request query params - */ - 'parameter-query': string; - }; - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is a required parameter - */ - body: ModelWithOneOfEnum; - path?: never; - query?: { - /** - * This is an optional parameter - */ - page?: number; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - body?: { - offset?: number; - }; - path?: never; - query: { - /** - * This is a required parameter - */ - parameter: Pageable; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; - -export type PostApiVbyApiVersionRequestBodyData = { - /** - * A reusable request body - */ - body?: SimpleRequestBody; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/requestBody/'; -}; - -export type PostApiVbyApiVersionFormDataData = { - /** - * A reusable request body - */ - body?: SimpleFormData; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/formData/'; -}; - -export type CallWithDefaultParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string with default value - */ - parameterString?: string; - /** - * This is a simple number with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallWithDefaultOptionalParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallToTestOrderOfParamsData = { - body?: never; - path?: never; - query: { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: string; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type DuplicateNameData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName2Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName3Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName4Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type CallWithNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no-content'; -}; - -export type CallWithNoContentResponseResponses = { - /** - * Success - */ - 204: void; -}; - -export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; - -export type CallWithResponseAndNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/response-and-no-content'; -}; - -export type CallWithResponseAndNoContentResponseResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; - -export type DummyAData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/a'; -}; - -export type DummyAResponses = { - 200: _400; -}; - -export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; - -export type DummyBData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/b'; -}; - -export type DummyBResponses = { - /** - * Success - */ - 204: void; -}; - -export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; - -export type CallWithResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponseResponses = { - default: Import; -}; - -export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; - -export type CallWithDuplicateResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithDuplicateResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for 4XX errors - */ - '4XX': DictionaryWithArray; - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; - -export type CallWithDuplicateResponsesResponses = { - /** - * Message for 200 response - */ - 200: ModelWithBoolean & ModelWithInteger; - /** - * Message for 201 response - */ - 201: ModelWithString; - /** - * Message for 202 response - */ - 202: ModelWithString; -}; - -export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; - -export type CallWithResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for default response - */ - default: ModelWithStringError; -}; - -export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; - -export type CallWithResponsesResponses = { - /** - * Message for 200 response - */ - 200: { - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; - }; - /** - * Message for 201 response - */ - 201: ModelThatExtends; - /** - * Message for 202 response - */ - 202: ModelThatExtendsExtends; -}; - -export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; - -export type CollectionFormatData = { - body?: never; - path?: never; - query: { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCSV: Array; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySSV: Array; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTSV: Array; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array; - }; - url: '/api/v{api-version}/collectionFormat'; -}; - -export type TypesData = { - body?: never; - path?: { - /** - * This is a number parameter - */ - id?: number; - }; - query: { - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is a string parameter - */ - parameterString: string; - /** - * This is a boolean parameter - */ - parameterBoolean: boolean; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - }; - /** - * This is an array parameter - */ - parameterArray: Array; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - }; - /** - * This is an enum parameter - */ - parameterEnum: 'Success' | 'Warning' | 'Error'; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; - }; - url: '/api/v{api-version}/types'; -}; - -export type TypesResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Response is a simple string - */ - 201: string; - /** - * Response is a simple boolean - */ - 202: boolean; - /** - * Response is a simple object - */ - 203: { - [key: string]: unknown; - }; -}; - -export type TypesResponse = TypesResponses[keyof TypesResponses]; - -export type UploadFileData = { - body: unknown; - path: { - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/upload'; -}; - -export type UploadFileResponses = { - 200: boolean; -}; - -export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; - -export type FileResponseData = { - body?: never; - path: { - id: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/file/{id}'; -}; - -export type FileResponseResponses = { - /** - * Success - */ - 200: unknown; -}; - -export type ComplexTypesData = { - body?: never; - path?: never; - query: { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; - }; - url: '/api/v{api-version}/complex'; -}; - -export type ComplexTypesErrors = { - /** - * 400 `server` error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type ComplexTypesResponses = { - /** - * Successful response - */ - 200: Array; -}; - -export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; - -export type MultipartResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type MultipartResponseResponses = { - /** - * OK - */ - 200: { - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; - }; -}; - -export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; - -export type MultipartRequestData = { - body?: { - content?: Blob | File; - data?: ModelWithString; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type ComplexParamsData = { - body?: { - readonly key: string; - name: string; - enabled?: boolean; - type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array; - listOfStrings?: Array; - parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; - readonly user?: { - readonly id?: number; - readonly name?: string; - }; - }; - path: { - id: number; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/complex/{id}'; -}; - -export type ComplexParamsResponses = { - /** - * Success - */ - 200: ModelWithString; -}; - -export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; - -export type CallWithResultFromHeaderData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/header'; -}; - -export type CallWithResultFromHeaderErrors = { - /** - * 400 server error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type CallWithResultFromHeaderResponses = { - /** - * Successful response - */ - 200: unknown; -}; - -export type TestErrorCodeData = { - body?: never; - path?: never; - query: { - /** - * Status code to return - */ - status: number; - }; - url: '/api/v{api-version}/error'; -}; - -export type TestErrorCodeErrors = { - /** - * Custom message: Internal Server Error - */ - 500: unknown; - /** - * Custom message: Not Implemented - */ - 501: unknown; - /** - * Custom message: Bad Gateway - */ - 502: unknown; - /** - * Custom message: Service Unavailable - */ - 503: unknown; -}; - -export type TestErrorCodeResponses = { - /** - * Custom message: Successful response - */ - 200: unknown; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - body?: never; - path?: never; - query: { - /** - * Dummy input param - */ - nonAsciiParamæøåÆØÅöôêÊ: number; - }; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { - /** - * Successful response - */ - 200: Array; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; - -export type PutWithFormUrlEncodedData = { - body: ArrayWithStrings; - path?: never; - query?: never; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/index.ts.snap deleted file mode 100644 index b43a5238d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/index.ts.snap +++ /dev/null @@ -1,3 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type * from './types.gen'; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/types.gen.ts.snap deleted file mode 100644 index f350f691f..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_types_no_tree/types.gen.ts.snap +++ /dev/null @@ -1,1996 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type ClientOptions = { - baseUrl: 'http://localhost:3000/base' | (string & {}); -}; - -/** - * Model with number-only name - */ -export type _400 = string; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CamelCaseCommentWithBreaks = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆøÅöôêÊ字符串 = string; - -/** - * This is a simple file - */ -export type SimpleFile = unknown; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = string; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: CamelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<{ - foo?: string; -} | { - bar?: string; -}>; - -export type AnyOfAnyAndNull = { - data?: unknown | null; -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<{ - foo?: string; - } | { - bar?: string; - }>; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type ModelFromZendesk = string; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: string; - /** - * This is a simple string property - */ - nullableRequiredProp1: string; - /** - * This is a simple string property - */ - nullableProp2?: string | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: string | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: true; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - /** - * Foo-Bar-Baz-Qux - */ - 'foo-bar-baz-qux'?: '3.0'; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a deprecated model with a deprecated property - * - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * - * @deprecated - */ - prop?: string; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * Circle - */ -export type ModelCircle = { - kind: string; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: string; - sideLength?: number; -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ({ - kind: 'circle'; -} & ModelCircle) | ({ - kind: 'square'; -} & ModelSquare); - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: { - propA?: string; - } | string | number; -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: Array | Array; -}; - -export type _3eNum1Период = 'Bird' | 'Dog'; - -export type ConstValue = 'ConstValue'; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - /** - * Scopes - */ - propA?: Array<_3eNum1Период | ConstValue> | null; -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: boolean | { - [key: string]: number; - }; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: boolean | { - [key: string]: Array; - }; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: { - boolean?: boolean; - } & ModelWithEnum & ModelWithArray & ModelWithDictionary; -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: { - boolean?: boolean; - } | ModelWithEnum | ModelWithArray | ModelWithDictionary; -}; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - age: number; - firstName: string; - lastname: string; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: string; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: string; - }; - }; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type File = { - /** - * Id - */ - readonly id?: string; - /** - * Updated at - */ - readonly updated_at?: string; - /** - * Created at - */ - readonly created_at?: string; - /** - * Mime - */ - mime: string; - /** - * File - */ - readonly file?: string; -}; - -export type Default = { - name?: string; -}; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -export type ModelWithConst = { - String?: 'String'; - number?: 0; - null?: null; - withType?: 'Some string'; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string | undefined; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: Array | null; -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: SimpleParameter; -} | { - bar: NonAsciiStringæøåÆøÅöôêÊ字符串; -}) & { - baz: number; - qux: number; -}; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - unknown, - unknown - ]; - foo: 'Corge'; -}; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: ModelWithNestedArrayEnumsData; -}; - -export type ModelWithNestedCompositionEnums = { - foo?: ModelWithNestedArrayEnumsDataFoo; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -export type ModelWithAnyOfConstantSizeArray = [ - number | string, - number | string, - number | string -]; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - number | string, - string -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - number | string, - number | string, - number | string -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - number | Import, - number | Import -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - number & string, - number & string -]; - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -export type ModelWithOneOfAndProperties = (SimpleParameter | NonAsciiStringæøåÆøÅöôêÊ字符串) & { - baz: number; - qux: number; -}; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * Model with restricted keyword name - */ -export type Import = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: IoK8sApimachineryPkgApisMetaV1Preconditions; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type IoK8sApimachineryPkgApisMetaV1Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: string | number; -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: unknown; -}; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number; -}; - -export type OneOfAllOfIssue = ((ConstValue | GenericSchemaDuplicateIssue1SystemBoolean) & _3eNum1Период) | GenericSchemaDuplicateIssue1SystemString; - -export type GenericSchemaDuplicateIssue1SystemBoolean = { - item?: boolean; - error?: string; - readonly hasError?: boolean; - data?: { - [key: string]: never; - }; -}; - -export type GenericSchemaDuplicateIssue1SystemString = { - item?: string; - error?: string; - readonly hasError?: boolean; -}; - -/** - * This is a reusable parameter - */ -export type SimpleParameter = string; - -/** - * Parameter with illegal characters - */ -export type XFooBar = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleRequestBody = ModelWithString; - -/** - * A reusable request body - */ -export type SimpleFormData = ModelWithString; - -export type ExportData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type PatchApiVbyApiVersionNoTagResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ImportData = { - body: ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type ImportResponses = { - /** - * Success - */ - 200: ModelFromZendesk; - /** - * Default success response - */ - default: ModelWithReadOnlyAndWriteOnly; -}; - -export type ImportResponse = ImportResponses[keyof ImportResponses]; - -export type FooWowData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no+tag'; -}; - -export type FooWowResponses = { - /** - * OK - */ - default: unknown; -}; - -export type ApiVVersionODataControllerCountData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple/$count'; -}; - -export type ApiVVersionODataControllerCountResponses = { - /** - * Success - */ - 200: ModelFromZendesk; -}; - -export type ApiVVersionODataControllerCountResponse = ApiVVersionODataControllerCountResponses[keyof ApiVVersionODataControllerCountResponses]; - -export type GetApiVbyApiVersionSimpleOperationData = { - body?: never; - path: { - /** - * foo in method - */ - foo_param: string; - }; - query?: never; - url: '/api/v{api-version}/simple:operation'; -}; - -export type GetApiVbyApiVersionSimpleOperationErrors = { - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type GetApiVbyApiVersionSimpleOperationError = GetApiVbyApiVersionSimpleOperationErrors[keyof GetApiVbyApiVersionSimpleOperationErrors]; - -export type GetApiVbyApiVersionSimpleOperationResponses = { - /** - * Response is a simple number - */ - 200: number; -}; - -export type GetApiVbyApiVersionSimpleOperationResponse = GetApiVbyApiVersionSimpleOperationResponses[keyof GetApiVbyApiVersionSimpleOperationResponses]; - -export type DeleteCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type GetCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type HeadCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type OptionsCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PatchCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PostCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type PutCallWithoutParametersAndResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/simple'; -}; - -export type DeleteFooData3 = { - body?: never; - headers: { - /** - * Parameter with illegal characters - */ - 'x-Foo-Bar': ModelWithString; - }; - path: { - /** - * foo in method - */ - foo_param: string; - /** - * bar in method - */ - BarParam: string; - }; - query?: never; - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}'; -}; - -export type CallWithDescriptionsData = { - body?: never; - path?: never; - query?: { - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - }; - url: '/api/v{api-version}/descriptions/'; -}; - -export type DeprecatedCallData = { - body?: never; - headers: { - /** - * This parameter is deprecated - * - * @deprecated - */ - parameter: DeprecatedModel; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/parameters/deprecated'; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the body - */ - body: { - [key: string]: unknown; - }; - headers: { - /** - * This is the parameter that goes into the header - */ - parameterHeader: string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - parameterPath: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - foo_ref_enum?: ModelWithNestedArrayEnumsDataFoo; - foo_all_of_enum: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the query params - */ - cursor: string; - }; - url: '/api/v{api-version}/parameters/{parameterPath}'; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter that goes into the body - */ - body: ModelWithString; - headers: { - /** - * This is the parameter that goes into the request header - */ - 'parameter.header': string; - }; - path: { - /** - * This is the parameter that goes into the path - */ - 'parameter.path.1'?: string; - /** - * This is the parameter that goes into the path - */ - 'parameter-path-2'?: string; - /** - * This is the parameter that goes into the path - */ - 'PARAMETER-PATH-3'?: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query: { - /** - * This is the parameter with a reserved keyword - */ - default?: string; - /** - * This is the parameter that goes into the request query params - */ - 'parameter-query': string; - }; - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}'; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is a required parameter - */ - body: ModelWithOneOfEnum; - path?: never; - query?: { - /** - * This is an optional parameter - */ - page?: number; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - body?: { - offset?: number; - }; - path?: never; - query: { - /** - * This is a required parameter - */ - parameter: Pageable; - }; - url: '/api/v{api-version}/parameters/'; -}; - -export type PostCallWithOptionalParamResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type PostCallWithOptionalParamResponse = PostCallWithOptionalParamResponses[keyof PostCallWithOptionalParamResponses]; - -export type PostApiVbyApiVersionRequestBodyData = { - /** - * A reusable request body - */ - body?: SimpleRequestBody; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/requestBody/'; -}; - -export type PostApiVbyApiVersionFormDataData = { - /** - * A reusable request body - */ - body?: SimpleFormData; - path?: never; - query?: { - /** - * This is a reusable parameter - */ - parameter?: string; - }; - url: '/api/v{api-version}/formData/'; -}; - -export type CallWithDefaultParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string with default value - */ - parameterString?: string; - /** - * This is a simple number with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallWithDefaultOptionalParametersData = { - body?: never; - path?: never; - query?: { - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type CallToTestOrderOfParamsData = { - body?: never; - path?: never; - query: { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: string; - }; - url: '/api/v{api-version}/defaults'; -}; - -export type DuplicateNameData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName2Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName3Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type DuplicateName4Data = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/duplicate'; -}; - -export type CallWithNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/no-content'; -}; - -export type CallWithNoContentResponseResponses = { - /** - * Success - */ - 204: void; -}; - -export type CallWithNoContentResponseResponse = CallWithNoContentResponseResponses[keyof CallWithNoContentResponseResponses]; - -export type CallWithResponseAndNoContentResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/response-and-no-content'; -}; - -export type CallWithResponseAndNoContentResponseResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Success - */ - 204: void; -}; - -export type CallWithResponseAndNoContentResponseResponse = CallWithResponseAndNoContentResponseResponses[keyof CallWithResponseAndNoContentResponseResponses]; - -export type DummyAData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/a'; -}; - -export type DummyAResponses = { - 200: _400; -}; - -export type DummyAResponse = DummyAResponses[keyof DummyAResponses]; - -export type DummyBData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multiple-tags/b'; -}; - -export type DummyBResponses = { - /** - * Success - */ - 204: void; -}; - -export type DummyBResponse = DummyBResponses[keyof DummyBResponses]; - -export type CallWithResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponseResponses = { - default: Import; -}; - -export type CallWithResponseResponse = CallWithResponseResponses[keyof CallWithResponseResponses]; - -export type CallWithDuplicateResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithDuplicateResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for 4XX errors - */ - '4XX': DictionaryWithArray; - /** - * Default error response - */ - default: ModelWithBoolean; -}; - -export type CallWithDuplicateResponsesError = CallWithDuplicateResponsesErrors[keyof CallWithDuplicateResponsesErrors]; - -export type CallWithDuplicateResponsesResponses = { - /** - * Message for 200 response - */ - 200: ModelWithBoolean & ModelWithInteger; - /** - * Message for 201 response - */ - 201: ModelWithString; - /** - * Message for 202 response - */ - 202: ModelWithString; -}; - -export type CallWithDuplicateResponsesResponse = CallWithDuplicateResponsesResponses[keyof CallWithDuplicateResponsesResponses]; - -export type CallWithResponsesData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/response'; -}; - -export type CallWithResponsesErrors = { - /** - * Message for 500 error - */ - 500: ModelWithStringError; - /** - * Message for 501 error - */ - 501: ModelWithStringError; - /** - * Message for 502 error - */ - 502: ModelWithStringError; - /** - * Message for default response - */ - default: ModelWithStringError; -}; - -export type CallWithResponsesError = CallWithResponsesErrors[keyof CallWithResponsesErrors]; - -export type CallWithResponsesResponses = { - /** - * Message for 200 response - */ - 200: { - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; - }; - /** - * Message for 201 response - */ - 201: ModelThatExtends; - /** - * Message for 202 response - */ - 202: ModelThatExtendsExtends; -}; - -export type CallWithResponsesResponse = CallWithResponsesResponses[keyof CallWithResponsesResponses]; - -export type CollectionFormatData = { - body?: never; - path?: never; - query: { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCSV: Array; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySSV: Array; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTSV: Array; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array; - }; - url: '/api/v{api-version}/collectionFormat'; -}; - -export type TypesData = { - body?: never; - path?: { - /** - * This is a number parameter - */ - id?: number; - }; - query: { - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is a string parameter - */ - parameterString: string; - /** - * This is a boolean parameter - */ - parameterBoolean: boolean; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - }; - /** - * This is an array parameter - */ - parameterArray: Array; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - }; - /** - * This is an enum parameter - */ - parameterEnum: 'Success' | 'Warning' | 'Error'; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; - }; - url: '/api/v{api-version}/types'; -}; - -export type TypesResponses = { - /** - * Response is a simple number - */ - 200: number; - /** - * Response is a simple string - */ - 201: string; - /** - * Response is a simple boolean - */ - 202: boolean; - /** - * Response is a simple object - */ - 203: { - [key: string]: unknown; - }; -}; - -export type TypesResponse = TypesResponses[keyof TypesResponses]; - -export type UploadFileData = { - body: unknown; - path: { - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/upload'; -}; - -export type UploadFileResponses = { - 200: boolean; -}; - -export type UploadFileResponse = UploadFileResponses[keyof UploadFileResponses]; - -export type FileResponseData = { - body?: never; - path: { - id: string; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/file/{id}'; -}; - -export type FileResponseResponses = { - /** - * Success - */ - 200: unknown; -}; - -export type ComplexTypesData = { - body?: never; - path?: never; - query: { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; - }; - url: '/api/v{api-version}/complex'; -}; - -export type ComplexTypesErrors = { - /** - * 400 `server` error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type ComplexTypesResponses = { - /** - * Successful response - */ - 200: Array; -}; - -export type ComplexTypesResponse = ComplexTypesResponses[keyof ComplexTypesResponses]; - -export type MultipartResponseData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type MultipartResponseResponses = { - /** - * OK - */ - 200: { - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; - }; -}; - -export type MultipartResponseResponse = MultipartResponseResponses[keyof MultipartResponseResponses]; - -export type MultipartRequestData = { - body?: { - content?: Blob | File; - data?: ModelWithString; - }; - path?: never; - query?: never; - url: '/api/v{api-version}/multipart'; -}; - -export type ComplexParamsData = { - body?: { - readonly key: string; - name: string; - enabled?: boolean; - type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array; - listOfStrings?: Array; - parameters: ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary; - readonly user?: { - readonly id?: number; - readonly name?: string; - }; - }; - path: { - id: number; - /** - * api-version should be required in standalone clients - */ - 'api-version': string; - }; - query?: never; - url: '/api/v{api-version}/complex/{id}'; -}; - -export type ComplexParamsResponses = { - /** - * Success - */ - 200: ModelWithString; -}; - -export type ComplexParamsResponse = ComplexParamsResponses[keyof ComplexParamsResponses]; - -export type CallWithResultFromHeaderData = { - body?: never; - path?: never; - query?: never; - url: '/api/v{api-version}/header'; -}; - -export type CallWithResultFromHeaderErrors = { - /** - * 400 server error - */ - 400: unknown; - /** - * 500 server error - */ - 500: unknown; -}; - -export type CallWithResultFromHeaderResponses = { - /** - * Successful response - */ - 200: unknown; -}; - -export type TestErrorCodeData = { - body?: never; - path?: never; - query: { - /** - * Status code to return - */ - status: number; - }; - url: '/api/v{api-version}/error'; -}; - -export type TestErrorCodeErrors = { - /** - * Custom message: Internal Server Error - */ - 500: unknown; - /** - * Custom message: Not Implemented - */ - 501: unknown; - /** - * Custom message: Bad Gateway - */ - 502: unknown; - /** - * Custom message: Service Unavailable - */ - 503: unknown; -}; - -export type TestErrorCodeResponses = { - /** - * Custom message: Successful response - */ - 200: unknown; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - body?: never; - path?: never; - query: { - /** - * Dummy input param - */ - nonAsciiParamæøåÆØÅöôêÊ: number; - }; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Responses = { - /** - * Successful response - */ - 200: Array; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = NonAsciiæøåÆøÅöôêÊ字符串Responses[keyof NonAsciiæøåÆøÅöôêÊ字符串Responses]; - -export type PutWithFormUrlEncodedData = { - body: ArrayWithStrings; - path?: never; - query?: never; - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串'; -}; diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/OpenAPI.ts.snap deleted file mode 100644 index 0317507fa..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/request.ts.snap deleted file mode 100644 index 9b08a59cd..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const isSuccess = (status: number): boolean => { - return status >= 200 && status < 300; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - let xhr = new XMLHttpRequest(); - xhr.open(options.method, url, true); - xhr.withCredentials = config.WITH_CREDENTIALS; - - headers.forEach((value, key) => { - xhr.setRequestHeader(key, value); - }); - - return new Promise(async (resolve, reject) => { - xhr.onload = () => resolve(xhr); - xhr.onabort = () => reject(new Error('Request aborted')); - xhr.onerror = () => reject(new Error('Network error')); - - for (const fn of config.interceptors.request._fns) { - xhr = await fn(xhr); - } - - xhr.send(body ?? formData); - - onCancel(() => xhr.abort()); - }); -}; - -export const getResponseHeader = (xhr: XMLHttpRequest, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = xhr.getResponseHeader(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = (xhr: XMLHttpRequest): unknown => { - if (xhr.status !== 204) { - try { - const contentType = xhr.getResponseHeader('Content-Type'); - if (contentType) { - if (contentType.includes('application/json') || contentType.includes('+json')) { - return JSON.parse(xhr.responseText); - } else { - return xhr.responseText; - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && isSuccess(response.status)) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/sdk.gen.ts.snap deleted file mode 100644 index 4ef5fc431..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/sdk.gen.ts.snap +++ /dev/null @@ -1,890 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import type { CollectionFormatData, ComplexTypesData, ComplexTypesResponse, ComplexParamsData, ComplexParamsResponse, PatchApiNoTagResponse, ImportData, ImportResponse, FooWowResponse, GetApiSimpleOperationData, GetApiSimpleOperationResponse, CallWithDefaultParametersData, CallWithDefaultOptionalParametersData, CallToTestOrderOfParamsData, DeprecatedCallData, CallWithDescriptionsData, TestErrorCodeData, TestErrorCodeResponse, FileResponseData, FileResponseResponse, PostApiFormDataData, CallWithResultFromHeaderResponse, MultipartRequestData, MultipartResponseResponse, DummyAResponse, DummyBResponse, CallWithNoContentResponseResponse, CallWithResponseAndNoContentResponseResponse, NonAsciiæøåÆøÅöôêÊ字符串Data, NonAsciiæøåÆøÅöôêÊ字符串Response, PutWithFormUrlEncodedData, DeleteFooData3, CallWithParametersData, CallWithWeirdParameterNamesData, GetCallWithOptionalParamData, PostCallWithOptionalParamData, PostCallWithOptionalParamResponse, PostApiRequestBodyData, CallWithResponseResponse, CallWithDuplicateResponsesResponse, CallWithResponsesResponse, ApiVVersionODataControllerCountResponse, TypesData, TypesResponse, UploadFileData, UploadFileResponse } from './types.gen'; - -export class CollectionFormat { - /** - * @param data The data for the request. - * @param data.parameterArrayCsv This is an array parameter that is sent as csv format (comma-separated values) - * @param data.parameterArraySsv This is an array parameter that is sent as ssv format (space-separated values) - * @param data.parameterArrayTsv This is an array parameter that is sent as tsv format (tab-separated values) - * @param data.parameterArrayPipes This is an array parameter that is sent as pipes format (pipe-separated values) - * @param data.parameterArrayMulti This is an array parameter that is sent as multi format (multiple parameter instances) - * @throws ApiError - */ - public static collectionFormat(data: CollectionFormatData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/collectionFormat', - query: { - parameterArrayCSV: data.parameterArrayCsv, - parameterArraySSV: data.parameterArraySsv, - parameterArrayTSV: data.parameterArrayTsv, - parameterArrayPipes: data.parameterArrayPipes, - parameterArrayMulti: data.parameterArrayMulti - } - }); - } -} - -export class Complex { - /** - * @param data The data for the request. - * @param data.parameterObject Parameter containing object - * @param data.parameterReference Parameter containing reference - * @returns ModelWithString Successful response - * @throws ApiError - */ - public static complexTypes(data: ComplexTypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/complex', - query: { - parameterObject: data.parameterObject, - parameterReference: data.parameterReference - }, - errors: { - 400: '400 `server` error', - 500: '500 server error' - } - }); - } - - /** - * @param data The data for the request. - * @param data.id - * @param data.requestBody - * @returns ModelWithString Success - * @throws ApiError - */ - public static complexParams(data: ComplexParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/complex/{id}', - path: { - id: data.id - }, - body: data.requestBody, - mediaType: 'application/json-patch+json' - }); - } -} - -export class Default { - /** - * @throws ApiError - */ - public static export(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static patchApiNoTag(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody - * @returns Model_From_Zendesk Success - * @returns ModelWithReadOnlyAndWriteOnly Default success response - * @throws ApiError - */ - public static import(data: ImportData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/no+tag', - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static fooWow(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/no+tag' - }); - } - - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @returns number Response is a simple number - * @throws ApiError - */ - public static getApiSimpleOperation(data: GetApiSimpleOperationData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple:operation', - path: { - foo_param: data.fooParam - }, - errors: { - default: 'Default error response' - } - }); - } -} - -export class Defaults { - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string with default value - * @param data.parameterNumber This is a simple number with default value - * @param data.parameterBoolean This is a simple boolean with default value - * @param data.parameterEnum This is a simple enum with default value - * @param data.parameterModel This is a simple model with default value - * @throws ApiError - */ - public static callWithDefaultParameters(data: CallWithDefaultParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterString This is a simple string that is optional with default value - * @param data.parameterNumber This is a simple number that is optional with default value - * @param data.parameterBoolean This is a simple boolean that is optional with default value - * @param data.parameterEnum This is a simple enum that is optional with default value - * @param data.parameterModel This is a simple model that is optional with default value - * @throws ApiError - */ - public static callWithDefaultOptionalParameters(data: CallWithDefaultOptionalParametersData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/defaults', - query: { - parameterString: data.parameterString, - parameterNumber: data.parameterNumber, - parameterBoolean: data.parameterBoolean, - parameterEnum: data.parameterEnum, - parameterModel: data.parameterModel - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterStringWithNoDefault This is a string with no default - * @param data.parameterOptionalStringWithDefault This is a optional string with default - * @param data.parameterOptionalStringWithEmptyDefault This is a optional string with empty default - * @param data.parameterOptionalStringWithNoDefault This is a optional string with no default - * @param data.parameterStringWithDefault This is a string with default - * @param data.parameterStringWithEmptyDefault This is a string with empty default - * @param data.parameterStringNullableWithNoDefault This is a string that can be null with no default - * @param data.parameterStringNullableWithDefault This is a string that can be null with default - * @throws ApiError - */ - public static callToTestOrderOfParams(data: CallToTestOrderOfParamsData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/defaults', - query: { - parameterOptionalStringWithDefault: data.parameterOptionalStringWithDefault, - parameterOptionalStringWithEmptyDefault: data.parameterOptionalStringWithEmptyDefault, - parameterOptionalStringWithNoDefault: data.parameterOptionalStringWithNoDefault, - parameterStringWithDefault: data.parameterStringWithDefault, - parameterStringWithEmptyDefault: data.parameterStringWithEmptyDefault, - parameterStringWithNoDefault: data.parameterStringWithNoDefault, - parameterStringNullableWithNoDefault: data.parameterStringNullableWithNoDefault, - parameterStringNullableWithDefault: data.parameterStringNullableWithDefault - } - }); - } -} - -export class Deprecated { - /** - * @deprecated - * @param data The data for the request. - * @param data.parameter This parameter is deprecated - * @throws ApiError - */ - public static deprecatedCall(data: DeprecatedCallData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/deprecated', - headers: { - parameter: data.parameter - } - }); - } -} - -export class Descriptions { - /** - * @param data The data for the request. - * @param data.parameterWithBreaks Testing multiline comments in string: First line - * Second line - * - * Fourth line - * @param data.parameterWithBackticks Testing backticks in string: `backticks` and ```multiple backticks``` should work - * @param data.parameterWithSlashes Testing slashes in string: \backwards\\\ and /forwards/// should work - * @param data.parameterWithExpressionPlaceholders Testing expression placeholders in string: ${expression} should work - * @param data.parameterWithQuotes Testing quotes in string: 'single quote''' and "double quotes""" should work - * @param data.parameterWithReservedCharacters Testing reserved characters in string: * inline * and ** inline ** should work - * @throws ApiError - */ - public static callWithDescriptions(data: CallWithDescriptionsData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/descriptions/', - query: { - parameterWithBreaks: data.parameterWithBreaks, - parameterWithBackticks: data.parameterWithBackticks, - parameterWithSlashes: data.parameterWithSlashes, - parameterWithExpressionPlaceholders: data.parameterWithExpressionPlaceholders, - parameterWithQuotes: data.parameterWithQuotes, - parameterWithReservedCharacters: data.parameterWithReservedCharacters - } - }); - } -} - -export class Duplicate { - /** - * @throws ApiError - */ - public static duplicateName(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName1(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName2(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/duplicate' - }); - } - - /** - * @throws ApiError - */ - public static duplicateName3(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/duplicate' - }); - } -} - -export class Error { - /** - * @param data The data for the request. - * @param data.status Status code to return - * @returns unknown Custom message: Successful response - * @throws ApiError - */ - public static testErrorCode(data: TestErrorCodeData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/error', - query: { - status: data.status - }, - errors: { - 500: 'Custom message: Internal Server Error', - 501: 'Custom message: Not Implemented', - 502: 'Custom message: Bad Gateway', - 503: 'Custom message: Service Unavailable' - } - }); - } -} - -export class FileResponse { - /** - * @param data The data for the request. - * @param data.id - * @returns binary Success - * @throws ApiError - */ - public static fileResponse(data: FileResponseData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/file/{id}', - path: { - id: data.id - } - }); - } -} - -export class FormData { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.formData A reusable request body - * @throws ApiError - */ - public static postApiFormData(data: PostApiFormDataData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/formData/', - query: { - parameter: data.parameter - }, - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } -} - -export class Header { - /** - * @returns string Successful response - * @throws ApiError - */ - public static callWithResultFromHeader(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/header', - responseHeader: 'operation-location', - errors: { - 400: '400 server error', - 500: '500 server error' - } - }); - } -} - -export class Multipart { - /** - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static multipartRequest(data: MultipartRequestData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/multipart', - formData: data.formData, - mediaType: 'multipart/form-data' - }); - } - - /** - * @returns unknown OK - * @throws ApiError - */ - public static multipartResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multipart' - }); - } -} - -export class MultipleTags1 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags2 { - /** - * @returns _400 - * @throws ApiError - */ - public static dummyA(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/a' - }); - } - - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class MultipleTags3 { - /** - * @returns void Success - * @throws ApiError - */ - public static dummyB(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/b' - }); - } -} - -export class NoContent { - /** - * @returns void Success - * @throws ApiError - */ - public static callWithNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/no-content' - }); - } - - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } -} - -export class NonAsciiÆøåÆøÅöôêÊ { - /** - * @param data The data for the request. - * @param data.nonAsciiParamæøåÆøÅöôêÊ Dummy input param - * @returns NonAsciiStringæøåÆØÅöôêÊ字符串 Successful response - * @throws ApiError - */ - public static nonAsciiæøåÆøÅöôêÊ字符串(data: NonAsciiæøåÆøÅöôêÊ字符串Data): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - query: { - 'nonAsciiParamæøåÆØÅöôêÊ': data.nonAsciiParamæøåÆøÅöôêÊ - } - }); - } - - /** - * Login User - * @param data The data for the request. - * @param data.formData - * @throws ApiError - */ - public static putWithFormUrlEncoded(data: PutWithFormUrlEncodedData): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/non-ascii-æøåÆØÅöôêÊ字符串', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} - -export class Parameters { - /** - * @param data The data for the request. - * @param data.fooParam foo in method - * @param data.barParam bar in method - * @param data.xFooBar Parameter with illegal characters - * @throws ApiError - */ - public static deleteFoo(data: DeleteFooData3): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/foo/{foo_param}/bar/{BarParam}', - path: { - foo_param: data.fooParam, - BarParam: data.barParam - }, - headers: { - 'x-Foo-Bar': data.xFooBar - } - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the header - * @param data.fooAllOfEnum - * @param data.cursor This is the parameter that goes into the query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.parameterPath This is the parameter that goes into the path - * @param data.requestBody This is the parameter that goes into the body - * @param data.fooRefEnum - * @throws ApiError - */ - public static callWithParameters(data: CallWithParametersData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameterPath}', - path: { - parameterPath: data.parameterPath - }, - cookies: { - parameterCookie: data.parameterCookie - }, - headers: { - parameterHeader: data.parameterHeader - }, - query: { - foo_ref_enum: data.fooRefEnum, - foo_all_of_enum: data.fooAllOfEnum, - cursor: data.cursor - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameterHeader This is the parameter that goes into the request header - * @param data.parameterQuery This is the parameter that goes into the request query params - * @param data.parameterCookie This is the parameter that goes into the cookie - * @param data.requestBody This is the parameter that goes into the body - * @param data.parameterPath1 This is the parameter that goes into the path - * @param data.parameterPath2 This is the parameter that goes into the path - * @param data.parameterPath3 This is the parameter that goes into the path - * @param data._default This is the parameter with a reserved keyword - * @throws ApiError - */ - public static callWithWeirdParameterNames(data: CallWithWeirdParameterNamesData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/{parameter.path.1}/{parameter-path-2}/{PARAMETER-PATH-3}', - path: { - 'parameter.path.1': data.parameterPath1, - 'parameter-path-2': data.parameterPath2, - 'PARAMETER-PATH-3': data.parameterPath3 - }, - cookies: { - 'PARAMETER-COOKIE': data.parameterCookie - }, - headers: { - 'parameter.header': data.parameterHeader - }, - query: { - default: data._default, - 'parameter-query': data.parameterQuery - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.requestBody This is a required parameter - * @param data.page This is an optional parameter - * @throws ApiError - */ - public static getCallWithOptionalParam(data: GetCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/parameters/', - query: { - page: data.page - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } - - /** - * @param data The data for the request. - * @param data.parameter This is a required parameter - * @param data.requestBody This is an optional parameter - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static postCallWithOptionalParam(data: PostCallWithOptionalParamData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/parameters/', - query: { - parameter: data.parameter - }, - body: data.requestBody, - mediaType: 'application/json' - }); - } -} - -export class RequestBody { - /** - * @param data The data for the request. - * @param data.parameter This is a reusable parameter - * @param data.foo A reusable request body - * @throws ApiError - */ - public static postApiRequestBody(data: PostApiRequestBodyData = {}): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/requestBody/', - query: { - parameter: data.parameter - }, - body: data.foo, - mediaType: 'application/json' - }); - } -} - -export class Response { - /** - * @returns number Response is a simple number - * @returns void Success - * @throws ApiError - */ - public static callWithResponseAndNoContentResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/multiple-tags/response-and-no-content' - }); - } - - /** - * @returns import - * @throws ApiError - */ - public static callWithResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/response' - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelWithString Message for 201 response - * @returns ModelWithString Message for 202 response - * @throws ApiError - */ - public static callWithDuplicateResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - '4XX': 'Message for 4XX errors', - default: 'Default error response' - } - }); - } - - /** - * @returns unknown Message for 200 response - * @returns ModelThatExtends Message for 201 response - * @returns ModelThatExtendsExtends Message for 202 response - * @throws ApiError - */ - public static callWithResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/response', - errors: { - 500: 'Message for 500 error', - 501: 'Message for 501 error', - 502: 'Message for 502 error', - default: 'Message for default response' - } - }); - } -} - -export class Simple { - /** - * @returns Model_From_Zendesk Success - * @throws ApiError - */ - public static apiVVersionODataControllerCount(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple/$count' - }); - } - - /** - * @throws ApiError - */ - public static getCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static putCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static postCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static deleteCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static optionsCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'OPTIONS', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static headCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'HEAD', - url: '/api/v{api-version}/simple' - }); - } - - /** - * @throws ApiError - */ - public static patchCallWithoutParametersAndResponse(): CancelablePromise { - return __request(OpenAPI, { - method: 'PATCH', - url: '/api/v{api-version}/simple' - }); - } -} - -export class Types { - /** - * @param data The data for the request. - * @param data.parameterArray This is an array parameter - * @param data.parameterDictionary This is a dictionary parameter - * @param data.parameterEnum This is an enum parameter - * @param data.parameterTuple This is tuple parameter - * @param data.parameterNumber This is a number parameter - * @param data.parameterString This is a string parameter - * @param data.parameterBoolean This is a boolean parameter - * @param data.parameterObject This is an object parameter - * @param data.id This is a number parameter - * @returns number Response is a simple number - * @returns string Response is a simple string - * @returns boolean Response is a simple boolean - * @returns unknown Response is a simple object - * @throws ApiError - */ - public static types(data: TypesData): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/v{api-version}/types', - path: { - id: data.id - }, - query: { - parameterNumber: data.parameterNumber, - parameterString: data.parameterString, - parameterBoolean: data.parameterBoolean, - parameterObject: data.parameterObject, - parameterArray: data.parameterArray, - parameterDictionary: data.parameterDictionary, - parameterEnum: data.parameterEnum, - parameterTuple: data.parameterTuple - } - }); - } -} - -export class Upload { - /** - * @param data The data for the request. - * @param data.formData - * @returns boolean - * @throws ApiError - */ - public static uploadFile(data: UploadFileData): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/v{api-version}/upload', - formData: data.formData, - mediaType: 'application/x-www-form-urlencoded' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/types.gen.ts.snap deleted file mode 100644 index 27c4b1682..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr/types.gen.ts.snap +++ /dev/null @@ -1,1549 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -export type _3e_num_1Период = 'Bird' | 'Dog'; - -export const _3e_num_1Период = { - BIRD: 'Bird', - DOG: 'Dog' -} as const; - -/** - * Model with number-only name - */ -export type _400 = string; - -export type _default = { - name?: string; -}; - -/** - * Model with restricted keyword name - */ -export type _import = string; - -export type AdditionalPropertiesIntegerIssue = { - value: number; - [key: string]: number | undefined; -}; - -export type AdditionalPropertiesUnknownIssue = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue2 = { - [key: string]: (string | number); -}; - -export type AdditionalPropertiesUnknownIssue3 = string & { - entries: { - [key: string]: AdditionalPropertiesUnknownIssue; - }; -}; - -export type AnyOfAnyAndNull = { - data?: (unknown | null); -}; - -/** - * This is a simple array with any of properties - */ -export type AnyOfArrays = { - results?: Array<({ - foo?: string; -} | { - bar?: string; -})>; -}; - -/** - * This is a simple array with any of properties - */ -export type ArrayWithAnyOfProperties = Array<({ - foo?: string; -} | { - bar?: string; -})>; - -/** - * This is a simple array containing an array - */ -export type ArrayWithArray = Array>; - -/** - * This is a simple array with booleans - */ -export type ArrayWithBooleans = Array; - -/** - * This is a simple array with numbers - */ -export type ArrayWithNumbers = Array; - -/** - * This is a simple array with properties - */ -export type ArrayWithProperties = Array<{ - '16x16'?: camelCaseCommentWithBreaks; - bar?: string; -}>; - -/** - * This is a simple array with references - */ -export type ArrayWithReferences = Array; - -/** - * This is a simple array with strings - */ -export type ArrayWithStrings = Array; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type camelCaseCommentWithBreaks = number; - -/** - * Some % character - */ -export type CharactersInDescription = string; - -/** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ -export type CommentWithBackticks = number; - -/** - * Testing backticks and quotes in string: `backticks`, 'quotes', "double quotes" and ```multiple backticks``` should work - */ -export type CommentWithBackticksAndQuotes = number; - -/** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ -export type CommentWithBreaks = number; - -/** - * Testing expression placeholders in string: ${expression} should work - */ -export type CommentWithExpressionPlaceholders = number; - -/** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ -export type CommentWithQuotes = number; - -/** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ -export type CommentWithReservedCharacters = number; - -/** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ -export type CommentWithSlashes = number; - -/** - * This is a base model with two simple optional properties - */ -export type CompositionBaseModel = { - firstName?: string; - lastname?: string; -}; - -/** - * This is a model that extends the base model - */ -export type CompositionExtendedModel = CompositionBaseModel & { - firstName: string; - lastname: string; - age: number; -}; - -/** - * This is a model with one property with a 'all of' relationship - */ -export type CompositionWithAllOfAndNullable = { - propA?: (({ - boolean?: boolean; -} & ModelWithEnum & ModelWithArray & ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model with one property with a 'any of' relationship - */ -export type CompositionWithAnyOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithAnyOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with nested 'any of' property with a type null - */ -export type CompositionWithNestedAnyAndTypeNull = { - propA?: (Array<(ModelWithDictionary | null)> | Array<(ModelWithArray | null)>); -}; - -/** - * This is a model with one property with a 'any of' relationship where the options are not $ref - */ -export type CompositionWithNestedAnyOfAndNull = { - propA?: (Array<(_3e_num_1Период | ConstValue)> | null); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOf = { - propA?: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); -}; - -/** - * This is a model that contains a dictionary of complex arrays (composited) within composition - */ -export type CompositionWithOneOfAndComplexArrayDictionary = { - propA?: (boolean | { - [key: string]: Array<(number | string)>; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship - */ -export type CompositionWithOneOfAndNullable = { - propA?: (({ - boolean?: boolean; -} | ModelWithEnum | ModelWithArray | ModelWithDictionary) | null); -}; - -export type CompositionWithOneOfAndProperties = ({ - foo: ParameterSimpleParameter; -} | { - bar: NonAsciiStringæøåÆØÅöôêÊ字符串; -}) & { - baz: (number) | null; - qux: number; -}; - -/** - * This is a model that contains a dictionary of simple arrays within composition - */ -export type CompositionWithOneOfAndSimpleArrayDictionary = { - propA?: (boolean | { - [key: string]: Array; -}); -}; - -/** - * This is a model that contains a simple dictionary within composition - */ -export type CompositionWithOneOfAndSimpleDictionary = { - propA?: (boolean | { - [key: string]: number; -}); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfAnonymous = { - propA?: ({ - propA?: string; -} | string | number); -}; - -/** - * This is a model with one property with a 'one of' relationship where the options are not $ref - */ -export type CompositionWithOneOfDiscriminator = ModelCircle | ModelSquare; - -export type ConstValue = "ConstValue"; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData = string; - -/** - * Model used to test deduplication strategy - */ -export type DeleteFooData2 = string; - -/** - * This is a deprecated model with a deprecated property - * @deprecated - */ -export type DeprecatedModel = { - /** - * This is a deprecated property - * @deprecated - */ - prop?: string; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithArray = { - [key: string]: Array; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithDictionary = { - [key: string]: { - [key: string]: string; - }; -}; - -/** - * This is a complex dictionary - */ -export type DictionaryWithProperties = { - [key: string]: { - foo?: string; - bar?: string; - }; -}; - -export type DictionaryWithPropertiesAndAdditionalProperties = { - foo?: number; - bar?: boolean; - [key: string]: string | number | boolean | undefined; -}; - -/** - * This is a string reference - */ -export type DictionaryWithReference = { - [key: string]: ModelWithString; -}; - -/** - * This is a string dictionary - */ -export type DictionaryWithString = { - [key: string]: string; -}; - -/** - * Success=1,Warning=2,Error=3 - */ -export type EnumFromDescription = number; - -/** - * This is a simple enum with numbers - */ -export type EnumWithExtensions = 200 | 400 | 500; - -/** - * This is a simple enum with numbers - */ -export const EnumWithExtensions = { - /** - * Used when the status of something is successful - */ - CUSTOM_SUCCESS: 200, - /** - * Used when the status of something has a warning - */ - CUSTOM_WARNING: 400, - /** - * Used when the status of something has an error - */ - CUSTOM_ERROR: 500 -} as const; - -/** - * This is a simple enum with numbers - */ -export type EnumWithNumbers = 1 | 2 | 3 | 1.1 | 1.2 | 1.3 | 100 | 200 | 300 | -100 | -200 | -300 | -1.1 | -1.2 | -1.3; - -/** - * This is a simple enum with numbers - */ -export const EnumWithNumbers = { - '_1': 1, - '_2': 2, - '_3': 3, - '_1.1': 1.1, - '_1.2': 1.2, - '_1.3': 1.3, - '_100': 100, - '_200': 200, - '_300': 300, - '_-100': -100, - '_-200': -200, - '_-300': -300, - '_-1.1': -1.1, - '_-1.2': -1.2, - '_-1.3': -1.3 -} as const; - -export type EnumWithReplacedCharacters = "'Single Quote'" | '"Double Quotes"' | 'øæåôöØÆÅÔÖ字符串' | 3.1 | ''; - -export const EnumWithReplacedCharacters = { - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'ØÆÅÔÖ_ØÆÅÔÖ字符串': 'øæåôöØÆÅÔÖ字符串', - '_3.1': 3.1, - EMPTY_STRING: '' -} as const; - -/** - * This is a simple enum with strings - */ -export type EnumWithStrings = 'Success' | 'Warning' | 'Error' | "'Single Quote'" | '"Double Quotes"' | 'Non-ascii: øæåôöØÆÅÔÖ字符串'; - -/** - * This is a simple enum with strings - */ -export const EnumWithStrings = { - SUCCESS: 'Success', - WARNING: 'Warning', - ERROR: 'Error', - _SINGLE_QUOTE_: "'Single Quote'", - _DOUBLE_QUOTES_: '"Double Quotes"', - 'NON_ASCII__ØÆÅÔÖ_ØÆÅÔÖ字符串': 'Non-ascii: øæåôöØÆÅÔÖ字符串' -} as const; - -export type EnumWithXEnumNames = 0 | 1 | 2; - -export const EnumWithXEnumNames = { - zero: 0, - one: 1, - two: 2 -} as const; - -export type File = { - readonly id?: string; - readonly updated_at?: string; - readonly created_at?: string; - mime: string; - readonly file?: string; -}; - -/** - * This is a free-form object with additionalProperties: {}. - */ -export type FreeFormObjectWithAdditionalPropertiesEqEmptyObject = { - [key: string]: unknown; -}; - -/** - * This is a free-form object with additionalProperties: true. - */ -export type FreeFormObjectWithAdditionalPropertiesEqTrue = { - [key: string]: unknown; -}; - -/** - * This is a free-form object without additionalProperties. - */ -export type FreeFormObjectWithoutAdditionalProperties = { - [key: string]: unknown; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_Boolean_ = { - item?: boolean; - error?: (string) | null; - readonly hasError?: boolean; - data?: { - [key: string]: unknown; - }; -}; - -export type Generic_Schema_Duplicate_Issue_1_System_String_ = { - item?: (string) | null; - error?: (string) | null; - readonly hasError?: boolean; -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_DeleteOptions = { - /** - * Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. - */ - preconditions?: (io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions); -}; - -/** - * This schema was giving PascalCase transformations a hard time - */ -export type io_k8s_apimachinery_pkg_apis_meta_v1_Preconditions = { - /** - * Specifies the target ResourceVersion - */ - resourceVersion?: string; - /** - * Specifies the target UID. - */ - uid?: string; -}; - -/** - * `Comment` or `VoiceComment`. The JSON object for adding voice comments to tickets is different. See [Adding voice comments to tickets](/documentation/ticketing/managing-tickets/adding-voice-comments-to-tickets) - */ -export type Model_From_Zendesk = string; - -/** - * Circle - */ -export type ModelCircle = { - kind: 'circle'; - radius?: number; -}; - -/** - * Square - */ -export type ModelSquare = { - kind: 'square'; - sideLength?: number; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtends = ModelWithString & { - propExtendsA?: string; - propExtendsB?: ModelWithString; -}; - -/** - * This is a model that extends another model - */ -export type ModelThatExtendsExtends = ModelWithString & ModelThatExtends & { - propExtendsC?: string; - propExtendsD?: ModelWithString; -}; - -/** - * This is a model with one property and additionalProperties: true - */ -export type ModelWithAdditionalPropertiesEqTrue = { - /** - * This is a simple string property - */ - prop?: string; - [key: string]: unknown | string; -}; - -export type ModelWithAnyOfConstantSizeArray = [ - (number | string), - (number | string), - (number | string) -]; - -export type ModelWithAnyOfConstantSizeArrayAndIntersect = [ - (number & string), - (number & string) -]; - -export type ModelWithAnyOfConstantSizeArrayNullable = [ - ((number) | null | string), - ((number) | null | string), - ((number) | null | string) -]; - -export type ModelWithAnyOfConstantSizeArrayWithNSizeAndOptions = [ - (number | _import), - (number | _import) -]; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArray = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * This is a model with one property containing an array - */ -export type ModelWithArrayReadOnlyAndWriteOnly = { - prop?: Array; - propWithFile?: Array; - propWithNumber?: Array; -}; - -/** - * Some description with `back ticks` - */ -export type ModelWithBackticksInDescription = { - /** - * The template `that` should be used for parsing and importing the contents of the CSV file. - * - *

There is one placeholder currently supported:

  • ${x} - refers to the n-th column in the CSV file, e.g. ${1}, ${2}, ...)

Example of a correct JSON template:

- *
-     * [
-     * {
-     * "resourceType": "Asset",
-     * "identifier": {
-     * "name": "${1}",
-     * "domain": {
-     * "name": "${2}",
-     * "community": {
-     * "name": "Some Community"
-     * }
-     * }
-     * },
-     * "attributes" : {
-     * "00000000-0000-0000-0000-000000003115" : [ {
-     * "value" : "${3}"
-     * } ],
-     * "00000000-0000-0000-0000-000000000222" : [ {
-     * "value" : "${4}"
-     * } ]
-     * }
-     * }
-     * ]
-     * 
- */ - template?: string; -}; - -/** - * This is a model with one boolean property - */ -export type ModelWithBoolean = { - /** - * This is a simple boolean property - */ - prop?: boolean; -}; - -/** - * This is a model with one property containing a circular reference - */ -export type ModelWithCircularReference = { - prop?: ModelWithCircularReference; -}; - -export type ModelWithConst = { - String?: "String"; - number?: 0; - null?: null; - withType?: "Some string"; -}; - -export type ModelWithConstantSizeArray = [ - number, - number -]; - -/** - * This is a model with one property containing a dictionary - */ -export type ModelWithDictionary = { - prop?: { - [key: string]: string; - }; -}; - -/** - * This is a model with duplicated imports - */ -export type ModelWithDuplicateImports = { - propA?: ModelWithString; - propB?: ModelWithString; - propC?: ModelWithString; -}; - -/** - * This is a model with duplicated properties - */ -export type ModelWithDuplicateProperties = { - prop?: ModelWithString; -}; - -/** - * This is a model with one enum - */ -export type ModelWithEnum = { - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; - /** - * These are the HTTP error code enums - */ - statusCode?: '100' | '200 FOO' | '300 FOO_BAR' | '400 foo-bar' | '500 foo.bar' | '600 foo&bar'; - /** - * Simple boolean enum - */ - bool?: boolean; -}; - -export namespace ModelWithEnum { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } - /** - * These are the HTTP error code enums - */ - export enum statusCode { - _100 = '100', - _200_FOO = '200 FOO', - _300_FOO_BAR = '300 FOO_BAR', - _400_FOO_BAR = '400 foo-bar', - _500_FOO_BAR = '500 foo.bar', - _600_FOO_BAR = '600 foo&bar' - } -} - -/** - * This is a model with one enum - */ -export type ModelWithEnumFromDescription = { - /** - * Success=1,Warning=2,Error=3 - */ - test?: number; -}; - -/** - * This is a model with one enum with escaped name - */ -export type ModelWithEnumWithHyphen = { - 'foo-bar-baz-qux'?: '3.0'; -}; - -export namespace ModelWithEnumWithHyphen { - export enum foo_bar_baz_qux { - _3_0 = '3.0' - } -} - -/** - * This is a model with one number property - */ -export type ModelWithInteger = { - /** - * This is a simple number property - */ - prop?: number; -}; - -export type ModelWithNestedArrayEnums = { - array_strings?: Array; - data?: (ModelWithNestedArrayEnumsData); -}; - -export type ModelWithNestedArrayEnumsData = { - foo?: Array; - bar?: Array; -}; - -export type ModelWithNestedArrayEnumsDataBar = 'baz' | 'qux'; - -export const ModelWithNestedArrayEnumsDataBar = { - BAZ: 'baz', - QUX: 'qux' -} as const; - -export type ModelWithNestedArrayEnumsDataFoo = 'foo' | 'bar'; - -export const ModelWithNestedArrayEnumsDataFoo = { - FOO: 'foo', - BAR: 'bar' -} as const; - -export type ModelWithNestedCompositionEnums = { - foo?: (ModelWithNestedArrayEnumsDataFoo); -}; - -/** - * This is a model with nested enums - */ -export type ModelWithNestedEnums = { - dictionaryWithEnum?: { - [key: string]: 'Success' | 'Warning' | 'Error'; - }; - dictionaryWithEnumFromDescription?: { - [key: string]: number; - }; - arrayWithEnum?: Array<'Success' | 'Warning' | 'Error'>; - arrayWithDescription?: Array; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNestedEnums { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -/** - * This is a model with one nested property - */ -export type ModelWithNestedProperties = { - readonly first: { - readonly second: { - readonly third: (string) | null; - } | null; - } | null; -}; - -export type ModelWithNullableObject = { - data?: NullableObject; -}; - -/** - * This is a model with one string property - */ -export type ModelWithNullableString = { - /** - * This is a simple string property - */ - nullableProp1?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp1: (string) | null; - /** - * This is a simple string property - */ - nullableProp2?: (string) | null; - /** - * This is a simple string property - */ - nullableRequiredProp2: (string) | null; - /** - * This is a simple enum with strings - */ - 'foo_bar-enum'?: 'Success' | 'Warning' | 'Error' | 'ØÆÅ字符串'; -}; - -export namespace ModelWithNullableString { - /** - * This is a simple enum with strings - */ - export enum foo_bar_enum { - SUCCESS = 'Success', - WARNING = 'Warning', - ERROR = 'Error', - ØÆÅ字符串 = 'ØÆÅ字符串' - } -} - -export type ModelWithNumericEnumUnion = { - /** - * Период - */ - value?: -10 | -1 | 0 | 1 | 3 | 6 | 12; -}; - -export namespace ModelWithNumericEnumUnion { - /** - * Период - */ - export enum value { - '_-10' = -10, - '_-1' = -1, - '_0' = 0, - '_1' = 1, - '_3' = 3, - '_6' = 6, - '_12' = 12 - } -} - -export type ModelWithOneOfAndProperties = (ParameterSimpleParameter | NonAsciiStringæøåÆØÅöôêÊ字符串) & { - baz: (number) | null; - qux: number; -}; - -export type ModelWithOneOfEnum = { - foo: 'Bar'; -} | { - foo: 'Baz'; -} | { - foo: 'Qux'; -} | { - content: string; - foo: 'Quux'; -} | { - content: [ - (string), - (string) - ]; - foo: 'Corge'; -}; - -export namespace ModelWithOneOfEnum { - export enum foo { - BAR = 'Bar' - } -} - -/** - * This is a model with ordered properties - */ -export type ModelWithOrderedProperties = { - zebra?: string; - apple?: string; - hawaii?: string; -}; - -/** - * This is a model that contains a some patterns - */ -export type ModelWithPattern = { - key: string; - name: string; - readonly enabled?: boolean; - readonly modified?: string; - id?: string; - text?: string; - patternWithSingleQuotes?: string; - patternWithNewline?: string; - patternWithBacktick?: string; -}; - -export type ModelWithPrefixItemsConstantSizeArray = [ - ModelWithInteger, - (number | string), - string -]; - -/** - * This is a model with one nested property - */ -export type ModelWithProperties = { - required: string; - readonly requiredAndReadOnly: string; - requiredAndNullable: (string) | null; - string?: string; - number?: number; - boolean?: boolean; - reference?: ModelWithString; - 'property with space'?: string; - default?: string; - try?: string; - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; -}; - -export type ModelWithReadOnlyAndWriteOnly = { - foo: string; - readonly bar: string; - baz: string; -}; - -/** - * This is a model with one property containing a reference - */ -export type ModelWithReference = { - prop?: ModelWithProperties; -}; - -/** - * This is a model with one string property - */ -export type ModelWithString = { - /** - * This is a simple string property - */ - prop?: string; -}; - -/** - * This is a model with one string property - */ -export type ModelWithStringError = { - /** - * This is a simple string property - */ - prop?: string; -}; - -export type NestedAnyOfArraysNullable = { - nullableArray?: (Array<(string | boolean)> | null); -}; - -/** - * A string with non-ascii (unicode) characters valid in typescript identifiers (æøåÆØÅöÔèÈ字符串) - */ -export type NonAsciiStringæøåÆØÅöôêÊ字符串 = string; - -/** - * An object that can be null - */ -export type NullableObject = { - foo?: string; -} | null; - -export type OneOfAllOfIssue = ((ConstValue | Generic_Schema_Duplicate_Issue_1_System_Boolean_) & _3e_num_1Период) | Generic_Schema_Duplicate_Issue_1_System_String_; - -export type Pageable = { - page?: number; - size?: number; - sort?: Array; -}; - -/** - * This is a reusable parameter - */ -export type ParameterSimpleParameter = string; - -/** - * Model used to test deduplication strategy (unused) - */ -export type ParameterSimpleParameterUnused = string; - -/** - * Parameter with illegal characters - */ -export type Parameterx_Foo_Bar = ModelWithString; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse = string; - -/** - * Model used to test deduplication strategy - */ -export type PostServiceWithEmptyTagResponse2 = string; - -export type SchemaWithFormRestrictedKeys = { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - object?: { - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; - }; - array?: Array<({ - description?: string; - 'x-enum-descriptions'?: string; - 'x-enum-varnames'?: string; - 'x-enumNames'?: string; - title?: string; -})>; -}; - -/** - * This is a simple boolean - */ -export type SimpleBoolean = boolean; - -/** - * This is a simple file - */ -export type SimpleFile = Blob | File; - -/** - * This is a simple number - */ -export type SimpleInteger = number; - -/** - * This is a simple reference - */ -export type SimpleReference = ModelWithString; - -/** - * This is a simple string - */ -export type SimpleString = string; - -/** - * This is a simple string - */ -export type SimpleStringWithPattern = (string) | null; - -export type CollectionFormatData = { - /** - * This is an array parameter that is sent as csv format (comma-separated values) - */ - parameterArrayCsv: Array | null; - /** - * This is an array parameter that is sent as multi format (multiple parameter instances) - */ - parameterArrayMulti: Array | null; - /** - * This is an array parameter that is sent as pipes format (pipe-separated values) - */ - parameterArrayPipes: Array | null; - /** - * This is an array parameter that is sent as ssv format (space-separated values) - */ - parameterArraySsv: Array | null; - /** - * This is an array parameter that is sent as tsv format (tab-separated values) - */ - parameterArrayTsv: Array | null; -}; - -export type ComplexTypesData = { - /** - * Parameter containing object - */ - parameterObject: { - first?: { - second?: { - third?: string; - }; - }; - }; - /** - * Parameter containing reference - */ - parameterReference: ModelWithString; -}; - -export type ComplexTypesResponse = (Array); - -export type ComplexParamsData = { - id: number; - requestBody?: { - readonly key: (string) | null; - name: (string) | null; - enabled?: boolean; - readonly type: 'Monkey' | 'Horse' | 'Bird'; - listOfModels?: Array | null; - listOfStrings?: Array | null; - parameters: (ModelWithString | ModelWithEnum | ModelWithArray | ModelWithDictionary); - readonly user?: { - readonly id?: number; - readonly name?: (string) | null; - }; - }; -}; - -export type ComplexParamsResponse = (ModelWithString); - -export type PatchApiNoTagResponse = (unknown); - -export type ImportData = { - requestBody: (ModelWithReadOnlyAndWriteOnly | ModelWithArrayReadOnlyAndWriteOnly); -}; - -export type ImportResponse = (Model_From_Zendesk | ModelWithReadOnlyAndWriteOnly); - -export type FooWowResponse = (unknown); - -export type GetApiSimpleOperationData = { - /** - * foo in method - */ - fooParam: string; -}; - -export type GetApiSimpleOperationResponse = (number); - -export type CallWithDefaultParametersData = { - /** - * This is a simple boolean with default value - */ - parameterBoolean?: (boolean) | null; - /** - * This is a simple enum with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model with default value - */ - parameterModel?: (ModelWithString) | null; - /** - * This is a simple number with default value - */ - parameterNumber?: (number) | null; - /** - * This is a simple string with default value - */ - parameterString?: (string) | null; -}; - -export type CallWithDefaultOptionalParametersData = { - /** - * This is a simple boolean that is optional with default value - */ - parameterBoolean?: boolean; - /** - * This is a simple enum that is optional with default value - */ - parameterEnum?: 'Success' | 'Warning' | 'Error'; - /** - * This is a simple model that is optional with default value - */ - parameterModel?: ModelWithString; - /** - * This is a simple number that is optional with default value - */ - parameterNumber?: number; - /** - * This is a simple string that is optional with default value - */ - parameterString?: string; -}; - -export type CallToTestOrderOfParamsData = { - /** - * This is a optional string with default - */ - parameterOptionalStringWithDefault?: string; - /** - * This is a optional string with empty default - */ - parameterOptionalStringWithEmptyDefault?: string; - /** - * This is a optional string with no default - */ - parameterOptionalStringWithNoDefault?: string; - /** - * This is a string that can be null with default - */ - parameterStringNullableWithDefault?: (string) | null; - /** - * This is a string that can be null with no default - */ - parameterStringNullableWithNoDefault?: (string) | null; - /** - * This is a string with default - */ - parameterStringWithDefault: string; - /** - * This is a string with empty default - */ - parameterStringWithEmptyDefault: string; - /** - * This is a string with no default - */ - parameterStringWithNoDefault: string; -}; - -export type DeprecatedCallData = { - /** - * This parameter is deprecated - * @deprecated - */ - parameter: (DeprecatedModel) | null; -}; - -export type CallWithDescriptionsData = { - /** - * Testing backticks in string: `backticks` and ```multiple backticks``` should work - */ - parameterWithBackticks?: unknown; - /** - * Testing multiline comments in string: First line - * Second line - * - * Fourth line - */ - parameterWithBreaks?: unknown; - /** - * Testing expression placeholders in string: ${expression} should work - */ - parameterWithExpressionPlaceholders?: unknown; - /** - * Testing quotes in string: 'single quote''' and "double quotes""" should work - */ - parameterWithQuotes?: unknown; - /** - * Testing reserved characters in string: * inline * and ** inline ** should work - */ - parameterWithReservedCharacters?: unknown; - /** - * Testing slashes in string: \backwards\\\ and /forwards/// should work - */ - parameterWithSlashes?: unknown; -}; - -export type TestErrorCodeData = { - /** - * Status code to return - */ - status: number; -}; - -export type TestErrorCodeResponse = (unknown); - -export type FileResponseData = { - id: string; -}; - -export type FileResponseResponse = (Blob | File); - -export type PostApiFormDataData = { - /** - * A reusable request body - */ - formData?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResultFromHeaderResponse = (string); - -export type MultipartRequestData = { - formData?: { - content?: Blob | File; - data?: ((ModelWithString) | null); - }; -}; - -export type MultipartResponseResponse = ({ - file?: Blob | File; - metadata?: { - foo?: string; - bar?: string; - }; -}); - -export type DummyAResponse = (_400); - -export type DummyBResponse = (void); - -export type CallWithNoContentResponseResponse = (void); - -export type CallWithResponseAndNoContentResponseResponse = (number | void); - -export type NonAsciiæøåÆøÅöôêÊ字符串Data = { - /** - * Dummy input param - */ - nonAsciiParamæøåÆøÅöôêÊ: number; -}; - -export type NonAsciiæøåÆøÅöôêÊ字符串Response = (Array); - -export type PutWithFormUrlEncodedData = { - formData: ArrayWithStrings; -}; - -export type DeleteFooData3 = { - /** - * bar in method - */ - barParam: string; - /** - * foo in method - */ - fooParam: string; - /** - * Parameter with illegal characters - */ - xFooBar: ModelWithString; -}; - -export type CallWithParametersData = { - /** - * This is the parameter that goes into the query params - */ - cursor: (string) | null; - fooAllOfEnum: (ModelWithNestedArrayEnumsDataFoo); - fooRefEnum?: ModelWithNestedArrayEnumsDataFoo; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: { - [key: string]: unknown; - } | null; -}; - -export type CallWithWeirdParameterNamesData = { - /** - * This is the parameter with a reserved keyword - */ - _default?: string; - /** - * This is the parameter that goes into the cookie - */ - parameterCookie: (string) | null; - /** - * This is the parameter that goes into the request header - */ - parameterHeader: (string) | null; - /** - * This is the parameter that goes into the path - */ - parameterPath1?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath2?: string; - /** - * This is the parameter that goes into the path - */ - parameterPath3?: string; - /** - * This is the parameter that goes into the request query params - */ - parameterQuery: (string) | null; - /** - * This is the parameter that goes into the body - */ - requestBody: (ModelWithString) | null; -}; - -export type GetCallWithOptionalParamData = { - /** - * This is an optional parameter - */ - page?: number; - /** - * This is a required parameter - */ - requestBody: ModelWithOneOfEnum; -}; - -export type PostCallWithOptionalParamData = { - /** - * This is a required parameter - */ - parameter: Pageable; - /** - * This is an optional parameter - */ - requestBody?: { - offset?: (number) | null; - }; -}; - -export type PostCallWithOptionalParamResponse = (number | void); - -export type PostApiRequestBodyData = { - /** - * A reusable request body - */ - foo?: ModelWithString; - /** - * This is a reusable parameter - */ - parameter?: string; -}; - -export type CallWithResponseResponse = (_import); - -export type CallWithDuplicateResponsesResponse = ((ModelWithBoolean & ModelWithInteger) | ModelWithString); - -export type CallWithResponsesResponse = ({ - readonly '@namespace.string'?: string; - readonly '@namespace.integer'?: number; - readonly value?: Array; -} | ModelThatExtends | ModelThatExtendsExtends); - -export type ApiVVersionODataControllerCountResponse = (Model_From_Zendesk); - -export type TypesData = { - /** - * This is a number parameter - */ - id?: number; - /** - * This is an array parameter - */ - parameterArray: Array | null; - /** - * This is a boolean parameter - */ - parameterBoolean: (boolean) | null; - /** - * This is a dictionary parameter - */ - parameterDictionary: { - [key: string]: unknown; - } | null; - /** - * This is an enum parameter - */ - parameterEnum: ('Success' | 'Warning' | 'Error') | null; - /** - * This is a number parameter - */ - parameterNumber: number; - /** - * This is an object parameter - */ - parameterObject: { - [key: string]: unknown; - } | null; - /** - * This is a string parameter - */ - parameterString: (string) | null; - /** - * This is tuple parameter - */ - parameterTuple: [ - number, - number, - number, - number - ]; -}; - -export type TypesResponse = (number | string | boolean | { - [key: string]: unknown; -}); - -export type UploadFileData = { - formData: Blob | File; -}; - -export type UploadFileResponse = (boolean); \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiError.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiError.ts.snap deleted file mode 100644 index 36675d288..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiError.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiRequestOptions.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiRequestOptions.ts.snap deleted file mode 100644 index 939a0aa4c..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiRequestOptions.ts.snap +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiResult.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiResult.ts.snap deleted file mode 100644 index 4c58e3913..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/ApiResult.ts.snap +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/CancelablePromise.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/CancelablePromise.ts.snap deleted file mode 100644 index d95c755e0..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/CancelablePromise.ts.snap +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/OpenAPI.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/OpenAPI.ts.snap deleted file mode 100644 index 0317507fa..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/OpenAPI.ts.snap +++ /dev/null @@ -1,56 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: 'http://localhost:3000/base', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/request.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/request.ts.snap deleted file mode 100644 index 9b08a59cd..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/core/request.ts.snap +++ /dev/null @@ -1,350 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; - -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; - -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; - -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; - -export const isSuccess = (status: number): boolean => { - return status >= 200 && status < 300; -}; - -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; - -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; - -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; - -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; - -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; - -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; - -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; - -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - let xhr = new XMLHttpRequest(); - xhr.open(options.method, url, true); - xhr.withCredentials = config.WITH_CREDENTIALS; - - headers.forEach((value, key) => { - xhr.setRequestHeader(key, value); - }); - - return new Promise(async (resolve, reject) => { - xhr.onload = () => resolve(xhr); - xhr.onabort = () => reject(new Error('Request aborted')); - xhr.onerror = () => reject(new Error('Network error')); - - for (const fn of config.interceptors.request._fns) { - xhr = await fn(xhr); - } - - xhr.send(body ?? formData); - - onCancel(() => xhr.abort()); - }); -}; - -export const getResponseHeader = (xhr: XMLHttpRequest, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = xhr.getResponseHeader(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; - -export const getResponseBody = (xhr: XMLHttpRequest): unknown => { - if (xhr.status !== 204) { - try { - const contentType = xhr.getResponseHeader('Content-Type'); - if (contentType) { - if (contentType.includes('application/json') || contentType.includes('+json')) { - return JSON.parse(xhr.responseText); - } else { - return xhr.responseText; - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && isSuccess(response.status)) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/index.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/index.ts.snap deleted file mode 100644 index 50a1dd734..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/index.ts.snap +++ /dev/null @@ -1,6 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; -export * from './sdk.gen'; -export * from './types.gen'; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/sdk.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/sdk.gen.ts.snap deleted file mode 100644 index 6789f1a5d..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/sdk.gen.ts.snap +++ /dev/null @@ -1,79 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -import type { CancelablePromise } from './core/CancelablePromise'; -import { OpenAPI } from './core/OpenAPI'; -import { request as __request } from './core/request'; -import { type ParentModelWithDatesResponse, type ModelWithDatesResponse, type ModelWithDatesArrayResponse, type ArrayOfDatesResponse, type DateResponse, type MultipleResponsesResponse, ParentModelWithDatesResponseTransformer, ModelWithDatesResponseTransformer, ModelWithDatesArrayResponseTransformer } from './types.gen'; - -export class Default { - /** - * @returns ParentModelWithDates Success - * @returns unknown Success - * @throws ApiError - */ - public static parentModelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/model-with-dates', - responseTransformer: ParentModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates', - responseTransformer: ModelWithDatesResponseTransformer - }); - } - - /** - * @returns ModelWithDates Success - * @throws ApiError - */ - public static modelWithDatesArray(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/model-with-dates-array', - responseTransformer: ModelWithDatesArrayResponseTransformer - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static arrayOfDates(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/array-of-dates' - }); - } - - /** - * @returns string Success - * @throws ApiError - */ - public static date(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/date' - }); - } - - /** - * @returns ModelWithDates Updated - * @returns SimpleModel Created - * @throws ApiError - */ - public static multipleResponses(): CancelablePromise { - return __request(OpenAPI, { - method: 'PUT', - url: '/api/multiple-responses' - }); - } -} \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/types.gen.ts.snap b/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/types.gen.ts.snap deleted file mode 100644 index 5de1d89cc..000000000 --- a/packages/openapi-ts-tests/main/test/__snapshots__/test/generated/v3_xhr_transform/types.gen.ts.snap +++ /dev/null @@ -1,106 +0,0 @@ -// This file is auto-generated by @hey-api/openapi-ts - -/** - * This is a model that contains a some dates - */ -export type ModelWithDates = { - id: number; - name: string; - readonly enabled: boolean; - readonly modified: Date; - readonly expires?: Date; -}; - -/** - * This is a model that contains a some dates and arrays - */ -export type ParentModelWithDates = { - id: number; - readonly modified?: Date; - items?: Array; - item?: ModelWithDates; - 'nullable-date'?: Array<(Date | null)>; - simpleItems?: Array; - simpleItem?: SimpleModel; - dates?: Array; - strings?: Array; -}; - -/** - * This is a model that contains a some dates - */ -export type SimpleModel = { - id: number; - name: string; - readonly enabled: boolean; -}; - -export type ParentModelWithDatesResponse = (ParentModelWithDates | unknown); - -export type ModelWithDatesResponse = (ModelWithDates); - -export type ModelWithDatesArrayResponse = (Array); - -export type ArrayOfDatesResponse = (Array); - -export type DateResponse = (Date); - -export type MultipleResponsesResponse = (Array | Array); - -export type ParentModelWithDatesResponseTransformer = (data: any) => Promise; - -export type ParentModelWithDatesModelResponseTransformer = (data: any) => ParentModelWithDates; - -export type ModelWithDatesModelResponseTransformer = (data: any) => ModelWithDates; - -export const ModelWithDatesModelResponseTransformer: ModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (data?.expires) { - data.expires = new Date(data.expires); - } - return data; -}; - -export const ParentModelWithDatesModelResponseTransformer: ParentModelWithDatesModelResponseTransformer = data => { - if (data?.modified) { - data.modified = new Date(data.modified); - } - if (Array.isArray(data?.items)) { - data.items.forEach(ModelWithDatesModelResponseTransformer); - } - if (data?.item) { - ModelWithDatesModelResponseTransformer(data.item); - } - if (Array.isArray(data?.['nullable-date'])) { - data['nullable-date'] = data['nullable-date'].map(item => item ? new Date(item) : item); - } - if (Array.isArray(data?.dates)) { - data.dates = data.dates.map(item => item ? new Date(item) : item); - } - return data; -}; - -export const ParentModelWithDatesResponseTransformer: ParentModelWithDatesResponseTransformer = async (data) => { - if (data) { - ParentModelWithDatesModelResponseTransformer(data); - } - return data; -}; - -export type ModelWithDatesResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesResponseTransformer: ModelWithDatesResponseTransformer = async (data) => { - ModelWithDatesModelResponseTransformer(data); - return data; -}; - -export type ModelWithDatesArrayResponseTransformer = (data: any) => Promise; - -export const ModelWithDatesArrayResponseTransformer: ModelWithDatesArrayResponseTransformer = async (data) => { - if (Array.isArray(data)) { - data.forEach(ModelWithDatesModelResponseTransformer); - } - return data; -}; \ No newline at end of file diff --git a/packages/openapi-ts-tests/main/test/index.test.ts b/packages/openapi-ts-tests/main/test/index.test.ts index 69f331245..e4bf4a980 100644 --- a/packages/openapi-ts-tests/main/test/index.test.ts +++ b/packages/openapi-ts-tests/main/test/index.test.ts @@ -1,515 +1,10 @@ -import fs from 'node:fs'; import path from 'node:path'; -import { createClient, type UserConfig } from '@hey-api/openapi-ts'; -import { sync } from 'glob'; +import { createClient } from '@hey-api/openapi-ts'; import { describe, expect, it } from 'vitest'; import { getSpecsPath } from '../../utils'; -const OUTPUT_PREFIX = './test/generated/'; - -const toOutputPath = (name: string) => `${OUTPUT_PREFIX}${name}/`; -const toSnapshotPath = (file: string) => - path.resolve( - __dirname, - '__snapshots__', - `${file.replace(OUTPUT_PREFIX, '')}.snap`, - ); - -describe('OpenAPI v2', () => { - it.each([ - { - config: { - exportCore: true, - input: '', - logs: { - level: 'silent', - }, - output: '', - plugins: [ - 'legacy/fetch', - '@hey-api/schemas', - { - asClass: true, - name: '@hey-api/sdk', - }, - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - ], - useOptions: true, - } as UserConfig, - description: 'generate fetch client', - name: 'v2', - }, - ])('$description', async ({ config, name }) => { - const output = toOutputPath(name); - await createClient({ - ...config, - input: path.join(getSpecsPath(), 'v2.json'), - output, - }); - await Promise.all( - sync(`${output}**/*.ts`).map(async (file) => { - const content = fs.readFileSync(file, 'utf8').toString(); - await expect(content).toMatchFileSnapshot(toSnapshotPath(file)); - }), - ); - }); -}); - -describe('OpenAPI v3', () => { - const config: UserConfig = { - exportCore: true, - input: '', - logs: { - level: 'silent', - }, - output: { - path: '', - }, - parser: { - transforms: { - readWrite: false, - }, - }, - plugins: [ - 'legacy/fetch', - '@hey-api/sdk', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - ], - useOptions: true, - }; - - const createConfig = (userConfig?: Partial): UserConfig => ({ - ...config, - ...userConfig, - }); - - const clientScenarios = [ - { - config: createConfig({ - plugins: [ - 'legacy/fetch', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - { - asClass: true, - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate fetch client', - name: 'v3', - }, - { - config: createConfig({ - plugins: [ - 'legacy/angular', - '@hey-api/typescript', - { - asClass: true, - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate angular client', - name: 'v3_angular', - }, - { - config: createConfig({ - plugins: ['legacy/angular', '@hey-api/typescript', '@hey-api/sdk'], - }), - description: 'generate tree-shakeable angular client', - name: 'v3_angular_tree_shakeable', - }, - { - config: createConfig({ - plugins: [ - 'legacy/node', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - { - asClass: true, - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate node client', - name: 'v3_node', - }, - { - config: createConfig({ - plugins: [ - 'legacy/axios', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - { - asClass: true, - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate axios client', - name: 'v3_axios', - }, - { - config: createConfig({ - plugins: [ - 'legacy/xhr', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - { - asClass: true, - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate xhr client', - name: 'v3_xhr', - }, - { - config: createConfig({ - name: 'ApiClient', - plugins: [ - 'legacy/fetch', - '@hey-api/typescript', - '@hey-api/sdk', - { - dates: true, - name: '@hey-api/transformers', - }, - ], - }), - description: 'generate client', - name: 'v3_client', - }, - ]; - - const allScenarios = [ - { - config: createConfig({ - exportCore: false, - plugins: [ - 'legacy/fetch', - { - dates: true, - name: '@hey-api/transformers', - }, - '@hey-api/typescript', - ], - }), - description: 'generate Date types', - name: 'v3_date', - }, - { - config: createConfig({ - plugins: [ - 'legacy/fetch', - { - include: '^ModelWithString', - name: '@hey-api/typescript', - }, - { - asClass: true, - include: '^Defaults', - name: '@hey-api/sdk', - }, - { - dates: true, - name: '@hey-api/transformers', - }, - ], - useOptions: false, - }), - description: 'generate legacy positional arguments', - name: 'v3_legacy_positional_args', - }, - { - config: createConfig({ - output: { - indexFile: false, - path: '', - }, - parser: { - transforms: { - readWrite: false, - }, - }, - plugins: ['@hey-api/client-fetch', '@hey-api/typescript'], - }), - description: 'generate output without index file', - name: 'v3_no_index', - }, - { - config: createConfig({ - plugins: [ - 'legacy/fetch', - { - include: '^ModelWithString', - name: '@hey-api/typescript', - }, - { - asClass: true, - include: '^Defaults', - name: '@hey-api/sdk', - }, - { - dates: true, - name: '@hey-api/transformers', - }, - ], - }), - description: 'generate optional arguments', - name: 'v3_options', - }, - { - config: createConfig({ - plugins: [ - 'legacy/fetch', - { - enums: 'typescript', - name: '@hey-api/typescript', - }, - { - asClass: true, - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate TypeScript enums', - name: 'v3_enums_typescript', - }, - { - config: createConfig({ - exportCore: false, - parser: { - transforms: { - readWrite: false, - }, - }, - plugins: [ - { - name: '@hey-api/typescript', - style: 'PascalCase', - }, - ], - }), - description: 'generate PascalCase types', - name: 'v3-types-PascalCase', - }, - { - config: createConfig({ - exportCore: false, - plugins: [ - { - name: '@hey-api/schemas', - type: 'form', - }, - ], - }), - description: 'generate form validation schemas', - name: 'v3-schemas-form', - }, - { - config: createConfig({ - exportCore: false, - plugins: [ - { - name: '@hey-api/schemas', - type: 'json', - }, - ], - }), - description: 'generate JSON Schemas', - name: 'v3-schemas-json', - }, - { - config: createConfig({ - exportCore: false, - plugins: [ - { - name: '@hey-api/schemas', - nameBuilder: (name) => `$${name}`, - type: 'json', - }, - ], - }), - description: 'generate JSON Schemas with custom names', - name: 'v3-schemas-name', - }, - { - config: createConfig({ - exportCore: false, - plugins: [ - 'legacy/fetch', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - { - asClass: true, - classNameBuilder: 'myAwesome{{name}}Api', - include: '^(Simple|Parameters)', - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate services with custom name', - name: 'v3_services_name', - }, - { - config: createConfig({ - exportCore: false, - plugins: [ - 'legacy/fetch', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - { - filter: '^\\w+ /api/v{api-version}/simple$', - name: '@hey-api/sdk', - }, - ], - }), - description: 'generate services with specific endpoints', - name: 'v3_services_filter', - }, - { - config: createConfig({ - exportCore: false, - parser: { - transforms: { - readWrite: false, - }, - }, - plugins: [ - 'legacy/fetch', - { - enums: 'javascript', - name: '@hey-api/typescript', - }, - '@hey-api/sdk', - ], - }), - description: 'generate tree-shakeable services', - name: 'v3_tree_shakeable', - }, - { - config: createConfig({ - exportCore: false, - parser: { - transforms: { - readWrite: false, - }, - }, - plugins: ['@hey-api/typescript'], - }), - description: 'generate only types with default settings', - name: 'v3_types', - }, - { - config: createConfig({ - exportCore: false, - parser: { - transforms: { - readWrite: false, - }, - }, - plugins: [ - { - name: '@hey-api/typescript', - tree: false, - }, - ], - }), - description: 'generate only types without tree', - name: 'v3_types_no_tree', - }, - ]; - - it.each(clientScenarios.concat(allScenarios))( - '$description', - async ({ config, name }) => { - const output = toOutputPath(name); - await createClient({ - ...config, - input: path.join(getSpecsPath(), 'v3.json'), - output: { - ...(typeof config.output === 'object' ? config.output : {}), - path: output, - }, - }); - await Promise.all( - sync(`${output}**/*.ts`).map(async (file) => { - const content = fs.readFileSync(file, 'utf8').toString(); - await expect(content).toMatchFileSnapshot(toSnapshotPath(file)); - }), - ); - }, - ); - - it.each(clientScenarios)( - 'transforms $description', - async ({ config, name }) => { - const output = toOutputPath(name + '_transform'); - - await createClient({ - ...config, - input: path.join(getSpecsPath(), 'v3-transforms.json'), - output, - plugins: [ - ...(config.plugins ?? []).map((plugin) => { - if (typeof plugin === 'string') { - if (plugin === '@hey-api/sdk') { - return { - // @ts-expect-error - ...plugin, - name: '@hey-api/sdk', - transformer: true, - }; - } - } else if (plugin.name === '@hey-api/sdk') { - return { - ...plugin, - name: '@hey-api/sdk', - transformer: true, - }; - } - - return plugin; - }), - { - dates: true, - name: '@hey-api/transformers', - }, - ], - }); - - await Promise.all( - sync(`${output}**/*.ts`).map(async (file) => { - const content = fs.readFileSync(file, 'utf8').toString(); - await expect(content).toMatchFileSnapshot(toSnapshotPath(file)); - }), - ); - }, - ); -}); - describe('index', () => { it('parses v2 without issues', async () => { await expect( diff --git a/packages/openapi-ts-tests/main/test/plugins.test.ts b/packages/openapi-ts-tests/main/test/plugins.test.ts index b80e6e166..57946fb94 100644 --- a/packages/openapi-ts-tests/main/test/plugins.test.ts +++ b/packages/openapi-ts-tests/main/test/plugins.test.ts @@ -599,7 +599,6 @@ for (const version of versions) { }, dependencies: ['@hey-api/typescript'], handler: vi.fn(), - handlerLegacy: vi.fn(), name: 'my-plugin', output: 'my-plugin', }; @@ -614,7 +613,6 @@ for (const version of versions) { }); expect(myPlugin.handler).toHaveBeenCalled(); - expect(myPlugin.handlerLegacy).not.toHaveBeenCalled(); }); it('throws on invalid dependency', async () => { @@ -626,7 +624,6 @@ for (const version of versions) { config: {}, dependencies: ['@hey-api/oops'], handler: vi.fn(), - handlerLegacy: vi.fn(), name: 'my-plugin', output: 'my-plugin', }; @@ -643,7 +640,6 @@ for (const version of versions) { ).rejects.toThrowError(/Found 1 configuration error./g); expect(myPlugin.handler).not.toHaveBeenCalled(); - expect(myPlugin.handlerLegacy).not.toHaveBeenCalled(); }); }); } diff --git a/packages/openapi-ts/package.json b/packages/openapi-ts/package.json index 30d119f14..ba2ee7963 100644 --- a/packages/openapi-ts/package.json +++ b/packages/openapi-ts/package.json @@ -78,7 +78,6 @@ "build": "tsdown && pnpm check-exports", "check-exports": "attw --pack . --profile node16", "dev": "tsdown --watch", - "handlebars": "node src/legacy/handlebars/handlebars.cjs", "prepublishOnly": "pnpm build", "test:coverage": "vitest run --coverage", "test:update": "vitest watch --update", @@ -96,7 +95,6 @@ "c12": "3.3.1", "color-support": "1.1.3", "commander": "14.0.1", - "handlebars": "4.7.8", "open": "10.2.0", "semver": "7.7.2" }, @@ -118,7 +116,6 @@ "axios": "1.8.2", "cross-spawn": "7.0.6", "eslint": "9.17.0", - "glob": "11.0.3", "nuxt": "3.14.1592", "ofetch": "1.4.1", "prettier": "3.4.2", diff --git a/packages/openapi-ts/src/__tests__/cli.test.ts b/packages/openapi-ts/src/__tests__/cli.test.ts index e93d475f1..e5db904ee 100755 --- a/packages/openapi-ts/src/__tests__/cli.test.ts +++ b/packages/openapi-ts/src/__tests__/cli.test.ts @@ -206,8 +206,6 @@ describe('cli', () => { 'quux', '--plugins', '--watch', - '--useOptions', - '--exportCore', ]; await runCli(); } finally { @@ -216,8 +214,6 @@ describe('cli', () => { expect(spy).toHaveBeenCalledWith({ configFile: 'bar', dryRun: true, - experimentalParser: true, - exportCore: true, input: 'baz', logs: { file: true, @@ -225,32 +221,10 @@ describe('cli', () => { }, output: 'quux', plugins: ['foo'], - useOptions: true, watch: true, }); }); - it('with false booleans', async () => { - const originalArgv = process.argv.slice(); - try { - process.argv = [ - String(process.argv[0]), - String(process.argv[1]), - '--useOptions', - 'false', - ]; - await runCli(); - } finally { - process.argv = originalArgv; - } - expect(spy).toHaveBeenCalledWith({ - logs: { - file: true, - }, - useOptions: false, - }); - }); - it('exits when not in watch mode', async () => { const originalArgv = process.argv.slice(); try { diff --git a/packages/openapi-ts/src/cli.ts b/packages/openapi-ts/src/cli.ts index 5dd796e60..a8517762d 100644 --- a/packages/openapi-ts/src/cli.ts +++ b/packages/openapi-ts/src/cli.ts @@ -33,16 +33,9 @@ export const runCli = async (): Promise => { .name(Object.keys(pkg.bin)[0]!) .usage('[options]') .version(pkg.version) - .option( - '-c, --client ', - 'HTTP client to generate [@hey-api/client-axios, @hey-api/client-fetch, @hey-api/client-next, @hey-api/client-nuxt, legacy/angular, legacy/axios, legacy/fetch, legacy/node, legacy/xhr]', - ) + .option('-c, --client ', 'HTTP client to generate') .option('-d, --debug', 'Set log level to debug') .option('--dry-run [value]', 'Skip writing files to disk?') - .option( - '-e, --experimental-parser [value]', - 'Opt-in to the experimental parser?', - ) .option('-f, --file [value]', 'Path to the config file') .option( '-i, --input ', @@ -51,10 +44,6 @@ export const runCli = async (): Promise => { .option('-l, --logs [value]', 'Logs folder') .option('-o, --output ', 'Output folder') .option('-p, --plugins [value...]', "List of plugins you'd like to use") - .option( - '--base [value]', - 'DEPRECATED. Manually set base in OpenAPI config instead of inferring from server value', - ) .option('-s, --silent', 'Set log level to silent') .option( '--no-log-file', @@ -64,26 +53,13 @@ export const runCli = async (): Promise => { '-w, --watch [value]', 'Regenerate the client when the input file changes?', ) - .option('--exportCore [value]', 'DEPRECATED. Write core files to disk') - .option('--name ', 'DEPRECATED. Custom client class name') - .option('--request ', 'DEPRECATED. Path to custom request file') - .option( - '--useOptions [value]', - 'DEPRECATED. Use options instead of arguments?', - ) .parse(process.argv) .opts(); let userConfig: Record; try { - userConfig = processParams(params, [ - 'dryRun', - 'experimentalParser', - 'exportCore', - 'logFile', - 'useOptions', - ]); + userConfig = processParams(params, ['dryRun', 'logFile']); if (userConfig.file) { userConfig.configFile = userConfig.file; diff --git a/packages/openapi-ts/src/config/init.ts b/packages/openapi-ts/src/config/init.ts index e7d629d36..0fd2df3c9 100644 --- a/packages/openapi-ts/src/config/init.ts +++ b/packages/openapi-ts/src/config/init.ts @@ -5,7 +5,6 @@ import colors from 'ansi-colors'; import { ConfigError } from '~/error'; import type { Config, UserConfig } from '~/types/config'; import type { ArrayOnly } from '~/types/utils'; -import { isLegacyClient, setConfig } from '~/utils/config'; import type { Logger } from '~/utils/logger'; import { getInput } from './input'; @@ -121,24 +120,7 @@ export const initConfigs = async ({ const eventBuild = logger.timeEvent('build'); for (const userConfig of configs) { - const { - base, - configFile = '', - dryRun = false, - experimentalParser = true, - exportCore = true, - name, - request, - useOptions = true, - } = userConfig; - - const interactive = - userConfig.interactive !== undefined - ? userConfig.interactive - : detectInteractiveSession(); - const logs = getLogs(userConfig); - const input = getInput(userConfig); const output = getOutput(userConfig); const parser = getParser(userConfig); @@ -161,12 +143,6 @@ export const initConfigs = async ({ ); } - if (!useOptions && logs.level !== 'silent') { - console.warn( - '❗️ Deprecation warning: useOptions set to false. This setting will be removed in future versions. Please migrate useOptions to true https://heyapi.dev/openapi-ts/migrating.html#v0-27-38', - ); - } - output.path = path.resolve(process.cwd(), output.path); let plugins: Pick; @@ -181,23 +157,17 @@ export const initConfigs = async ({ }; } - const config = setConfig({ - ...plugins, - base, - configFile, - dryRun, - experimentalParser, - exportCore: false, + const config: Config = { + configFile: userConfig.configFile ?? '', + dryRun: userConfig.dryRun ?? false, input, - interactive, + interactive: userConfig.interactive ?? detectInteractiveSession(), logs, - name, output, parser, - request, - useOptions, - }); - config.exportCore = isLegacyClient(config) ? exportCore : false; + pluginOrder: plugins.pluginOrder, + plugins: plugins.plugins, + }; const jobIndex = results.length; diff --git a/packages/openapi-ts/src/config/plugins.ts b/packages/openapi-ts/src/config/plugins.ts index 7ffb90b21..17a8444a3 100644 --- a/packages/openapi-ts/src/config/plugins.ts +++ b/packages/openapi-ts/src/config/plugins.ts @@ -129,12 +129,11 @@ const getPluginsConfig = ({ const isPluginClient = (plugin: Required['plugins'][number]) => { if (typeof plugin === 'string') { - return plugin.startsWith('@hey-api/client') || plugin.startsWith('legacy/'); + return plugin.startsWith('@hey-api/client'); } return ( plugin.name.startsWith('@hey-api/client') || - plugin.name.startsWith('legacy/') || // @ts-expect-error (plugin.tags && plugin.tags.includes('client')) ); diff --git a/packages/openapi-ts/src/createClient.ts b/packages/openapi-ts/src/createClient.ts index f555b2c10..2ce32962f 100644 --- a/packages/openapi-ts/src/createClient.ts +++ b/packages/openapi-ts/src/createClient.ts @@ -3,22 +3,17 @@ import path from 'node:path'; import { $RefParser } from '@hey-api/json-schema-ref-parser'; import colors from 'ansi-colors'; -import { generateLegacyOutput } from '~/generate/legacy/output'; import { generateOutput } from '~/generate/output'; import { getSpec } from '~/getSpec'; import type { Context } from '~/ir/context'; -import { parseLegacy, parseOpenApiSpec } from '~/openApi'; +import { parseOpenApiSpec } from '~/openApi'; import { buildGraph } from '~/openApi/shared/utils/graph'; import { patchOpenApiSpec } from '~/openApi/shared/utils/patch'; import { processOutput } from '~/processOutput'; -import type { Client } from '~/types/client'; import type { Config } from '~/types/config'; import type { Input } from '~/types/input'; import type { WatchValues } from '~/types/types'; -import { isLegacyClient, legacyNameFromConfig } from '~/utils/config'; -import type { Templates } from '~/utils/handlebars'; import type { Logger } from '~/utils/logger'; -import { postProcessClient } from '~/utils/postprocess'; export const compileInputPath = (input: Omit) => { const result: Pick< @@ -242,19 +237,17 @@ export const createClient = async ({ dependencies, jobIndex, logger, - templates, watches: _watches, }: { config: Config; dependencies: Record; jobIndex: number; logger: Logger; - templates: Templates; /** * Always undefined on the first run, defined on subsequent runs. */ watches?: ReadonlyArray; -}): Promise => { +}): Promise => { const watches: ReadonlyArray = _watches || Array.from({ length: config.input.length }, () => ({ @@ -295,7 +288,6 @@ export const createClient = async ({ ) ).filter((data) => data.arrayBuffer || data.resolvedInput); - let client: Client | undefined; let context: Context | undefined; if (specData.length) { @@ -325,29 +317,12 @@ export const createClient = async ({ eventInputPatch.timeEnd(); const eventParser = logger.timeEvent('parser'); - if ( - config.experimentalParser && - !isLegacyClient(config) && - !legacyNameFromConfig(config) - ) { - context = parseOpenApiSpec({ config, dependencies, logger, spec: data }); - } - - if (context) { - context.graph = buildGraph(context.ir, logger).graph; - } else { - // fallback to legacy parser - const parsed = parseLegacy({ openApi: data }); - client = postProcessClient(parsed, config); - } + context = parseOpenApiSpec({ config, dependencies, logger, spec: data }); + context.graph = buildGraph(context.ir, logger).graph; eventParser.timeEnd(); const eventGenerator = logger.timeEvent('generator'); - if (context) { - await generateOutput({ context }); - } else if (client) { - await generateLegacyOutput({ client, openApi: data, templates }); - } + await generateOutput({ context }); eventGenerator.timeEnd(); const eventPostprocess = logger.timeEvent('postprocess'); @@ -379,11 +354,10 @@ export const createClient = async ({ dependencies, jobIndex, logger, - templates, watches, }); }, watchedInput.watch.interval); } - return context || client; + return context; }; diff --git a/packages/openapi-ts/src/generate.ts b/packages/openapi-ts/src/generate.ts index 3c2c62e39..5793ebd83 100644 --- a/packages/openapi-ts/src/generate.ts +++ b/packages/openapi-ts/src/generate.ts @@ -12,11 +12,9 @@ import { shouldReportCrash, } from '~/error'; import type { Context } from '~/ir/context'; -import type { Client } from '~/types/client'; import type { UserConfig } from '~/types/config'; import type { LazyOrAsync, MaybeArray } from '~/types/utils'; import { printCliIntro } from '~/utils/cli'; -import { registerHandlebarTemplates } from '~/utils/handlebars'; import { Logger } from '~/utils/logger'; /** @@ -27,7 +25,7 @@ import { Logger } from '~/utils/logger'; export const createClient = async ( userConfig?: LazyOrAsync>, logger = new Logger(), -): Promise> => { +): Promise> => { const resolvedConfig = typeof userConfig === 'function' ? await userConfig() : userConfig; const userConfigs = resolvedConfig @@ -67,10 +65,6 @@ export const createClient = async ( throw new ConfigValidationError(allConfigErrors); } - const eventHandlebars = logger.timeEvent('handlebars'); - const templates = registerHandlebarTemplates(); - eventHandlebars.timeEnd(); - const clients = await Promise.all( configs.results.map(async (result) => { try { @@ -79,7 +73,6 @@ export const createClient = async ( dependencies: configs!.dependencies, jobIndex: result.jobIndex, logger, - templates, }); } catch (error) { throw new JobError('', { @@ -89,9 +82,9 @@ export const createClient = async ( } }), ); - const result = clients.filter((client) => Boolean(client)) as ReadonlyArray< - Client | Context - >; + const result = clients.filter((client) => + Boolean(client), + ) as ReadonlyArray; eventCreateClient.timeEnd(); diff --git a/packages/openapi-ts/src/generate/__tests__/class.test.ts b/packages/openapi-ts/src/generate/__tests__/class.test.ts deleted file mode 100644 index a4ef247c1..000000000 --- a/packages/openapi-ts/src/generate/__tests__/class.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -import fs from 'node:fs'; - -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import type { Config } from '~/types/config'; -import { setConfig } from '~/utils/config'; - -import { generateLegacyClientClass } from '../class'; -import { mockTemplates, openApi } from './mocks'; - -vi.mock('node:fs'); - -describe('generateLegacyClientClass', () => { - it('writes to filesystem', async () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - name: 'AppClient', - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - 'legacy/fetch', - '@hey-api/schemas', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - const client: Parameters[2] = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [], - types: {}, - version: 'v1', - }; - - await generateLegacyClientClass(openApi, './dist', client, mockTemplates); - - expect(fs.writeFileSync).toHaveBeenCalled(); - }); -}); diff --git a/packages/openapi-ts/src/generate/__tests__/core.test.ts b/packages/openapi-ts/src/generate/__tests__/core.test.ts deleted file mode 100644 index 4422ebdb0..000000000 --- a/packages/openapi-ts/src/generate/__tests__/core.test.ts +++ /dev/null @@ -1,441 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import type ts from 'typescript'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -import type { Config } from '~/types/config'; -import { setConfig } from '~/utils/config'; - -import { generateLegacyCore } from '../core'; -import { mockTemplates } from './mocks'; - -vi.mock('node:fs'); - -describe('generateLegacyCore', () => { - let templates: Parameters[2]; - beforeEach(() => { - templates = mockTemplates; - }); - - it('writes to filesystem', async () => { - const client: Parameters[1] = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [], - types: {}, - version: '1.0', - }; - - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - name: 'AppClient', - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - await generateLegacyCore('/', client, templates); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - path.resolve('/', '/OpenAPI.ts'), - 'settings', - ); - expect(fs.writeFileSync).toHaveBeenCalledWith( - path.resolve('/', '/ApiError.ts'), - 'apiError', - ); - expect(fs.writeFileSync).toHaveBeenCalledWith( - path.resolve('/', '/ApiRequestOptions.ts'), - 'apiRequestOptions', - ); - expect(fs.writeFileSync).toHaveBeenCalledWith( - path.resolve('/', '/ApiResult.ts'), - 'apiResult', - ); - expect(fs.writeFileSync).toHaveBeenCalledWith( - path.resolve('/', '/CancelablePromise.ts'), - 'cancelablePromise', - ); - expect(fs.writeFileSync).toHaveBeenCalledWith( - path.resolve('/', '/request.ts'), - 'request', - ); - }); - - it('uses client server value for base', async () => { - const client: Parameters[1] = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [], - types: {}, - version: '1.0', - }; - - const config = setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - name: 'AppClient', - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - await generateLegacyCore('/', client, templates); - - expect(templates.core.settings).toHaveBeenCalledWith({ - $config: config, - httpRequest: 'FetchHttpRequest', - server: 'http://localhost:8080', - version: '1.0', - }); - }); - - it('uses custom value for base', async () => { - const client: Parameters[1] = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [], - types: {}, - version: '1.0', - }; - - const config = setConfig({ - base: 'foo', - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - name: 'AppClient', - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - await generateLegacyCore('/', client, templates); - - expect(templates.core.settings).toHaveBeenCalledWith({ - $config: config, - httpRequest: 'FetchHttpRequest', - server: 'foo', - version: '1.0', - }); - }); -}); diff --git a/packages/openapi-ts/src/generate/__tests__/file.test.ts b/packages/openapi-ts/src/generate/__tests__/file.test.ts deleted file mode 100644 index ea001c323..000000000 --- a/packages/openapi-ts/src/generate/__tests__/file.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { splitNameAndExtension } from '../file'; - -describe('splitNameAndExtension', () => { - it('should split filename with extension correctly', () => { - const result = splitNameAndExtension('document.pdf'); - expect(result).toEqual({ extension: 'pdf', name: 'document' }); - }); - - it('should handle filename without extension', () => { - const result = splitNameAndExtension('README'); - expect(result).toEqual({ extension: '', name: 'README' }); - }); - - it('should handle filename with multiple dots', () => { - const result = splitNameAndExtension('my.file.name.txt'); - expect(result).toEqual({ extension: 'txt', name: 'my.file.name' }); - }); - - it('should handle empty string', () => { - const result = splitNameAndExtension(''); - expect(result).toEqual({ extension: '', name: '' }); - }); - - it('should handle filename with uppercase extension', () => { - const result = splitNameAndExtension('image.PNG'); - expect(result).toEqual({ extension: 'PNG', name: 'image' }); - }); - - it('should handle extension with numbers', () => { - const result = splitNameAndExtension('video.mp4'); - expect(result).toEqual({ extension: 'mp4', name: 'video' }); - }); -}); diff --git a/packages/openapi-ts/src/generate/__tests__/mocks.ts b/packages/openapi-ts/src/generate/__tests__/mocks.ts deleted file mode 100644 index fdffc1900..000000000 --- a/packages/openapi-ts/src/generate/__tests__/mocks.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { vi } from 'vitest'; - -import type { OpenApi } from '~/openApi'; -import type { Client } from '~/types/client'; -import type { Config } from '~/types/config'; -import type { Templates } from '~/utils/handlebars'; - -export const client: Client = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [], - types: {}, - version: 'v1', -}; - -export const mockTemplates: Templates = { - client: vi.fn().mockReturnValue('client'), - core: { - apiError: vi.fn().mockReturnValue('apiError'), - apiRequestOptions: vi.fn().mockReturnValue('apiRequestOptions'), - apiResult: vi.fn().mockReturnValue('apiResult'), - baseHttpRequest: vi.fn().mockReturnValue('baseHttpRequest'), - cancelablePromise: vi.fn().mockReturnValue('cancelablePromise'), - httpRequest: vi.fn().mockReturnValue('httpRequest'), - request: vi.fn().mockReturnValue('request'), - settings: vi.fn().mockReturnValue('settings'), - }, -}; - -export const openApi: OpenApi = { - info: { - title: '', - version: '', - }, - openapi: '', - paths: {}, - swagger: '', -}; diff --git a/packages/openapi-ts/src/generate/class.ts b/packages/openapi-ts/src/generate/class.ts deleted file mode 100644 index e40b9f0bb..000000000 --- a/packages/openapi-ts/src/generate/class.ts +++ /dev/null @@ -1,47 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import type { OpenApi } from '~/openApi'; -import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; -import type { Client } from '~/types/client'; -import { getConfig, legacyNameFromConfig } from '~/utils/config'; -import { getHttpRequestName } from '~/utils/getHttpRequestName'; -import type { Templates } from '~/utils/handlebars'; -import { sortByName } from '~/utils/sort'; - -import { ensureDirSync } from './utils'; - -/** - * Generate the OpenAPI client index file using the Handlebar template and write it to disk. - * The index file just contains all the exports you need to use the client as a standalone - * library. But you can also import individual models and services directly. - * @param openApi {@link OpenApi} Dereferenced OpenAPI specification - * @param outputPath Directory to write the generated files to - * @param client Client containing models, schemas, and services - * @param templates The loaded handlebar templates - */ -export const generateLegacyClientClass = async ( - _openApi: OpenApi, - outputPath: string, - client: Client, - templates: Templates, -) => { - const config = getConfig(); - - const clientPlugin = getClientPlugin(config); - const templateResult = templates.client({ - $config: config, - ...client, - httpRequest: getHttpRequestName(clientPlugin.name), - models: sortByName(client.models), - services: sortByName(client.services), - }); - - if (legacyNameFromConfig(config)) { - ensureDirSync(outputPath); - fs.writeFileSync( - path.resolve(outputPath, `${legacyNameFromConfig(config)}.ts`), - templateResult, - ); - } -}; diff --git a/packages/openapi-ts/src/generate/client.ts b/packages/openapi-ts/src/generate/client.ts index d8bc028c9..c0cbb4756 100644 --- a/packages/openapi-ts/src/generate/client.ts +++ b/packages/openapi-ts/src/generate/client.ts @@ -9,43 +9,11 @@ import type { Client } from '~/plugins/@hey-api/client-core/types'; import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; import type { Config } from '~/types/config'; -import { ensureDirSync, relativeModulePath } from './utils'; +import { ensureDirSync } from './utils'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -/** - * Returns path to the client module. When using client packages, this will be - * simply the name of the package. When bundling a client, this will be a - * relative path to the bundled client folder. - * - * @deprecated - */ -export const clientModulePath = ({ - config, - sourceOutput, -}: { - config: Config; - sourceOutput: string; -}): string => { - const client = getClientPlugin(config); - - if ('bundle' in client.config && client.config.bundle) { - return relativeModulePath({ - moduleOutput: 'client', - sourceOutput, - }); - } - - if (path.isAbsolute(client.name)) { - const clientSrcPath = path.dirname(client.name); - const outputPath = path.resolve(config.output.path); - return path.relative(outputPath, clientSrcPath).replace(/\\/g, '/'); - } - - return client.name; -}; - /** * Returns absolute path to the client folder. This is hard-coded for now. */ diff --git a/packages/openapi-ts/src/generate/core.ts b/packages/openapi-ts/src/generate/core.ts deleted file mode 100644 index ba4581bbc..000000000 --- a/packages/openapi-ts/src/generate/core.ts +++ /dev/null @@ -1,113 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; -import type { Client } from '~/types/client'; -import { getConfig, legacyNameFromConfig } from '~/utils/config'; -import { getHttpRequestName } from '~/utils/getHttpRequestName'; -import type { Templates } from '~/utils/handlebars'; - -/** - * Generate OpenAPI core files, this includes the basic boilerplate code to handle requests. - * @param outputPath Directory to write the generated files to - * @param client Client containing models, schemas, and services - * @param templates The loaded handlebar templates - */ -export const generateLegacyCore = async ( - outputPath: string, - client: Client, - templates: Templates, -): Promise => { - const config = getConfig(); - - if (config.exportCore) { - const clientPlugin = getClientPlugin(config); - const context = { - httpRequest: getHttpRequestName(clientPlugin.name), - server: config.base !== undefined ? config.base : client.server, - version: client.version, - }; - - fs.rmSync(path.resolve(outputPath), { - force: true, - recursive: true, - }); - fs.mkdirSync(path.resolve(outputPath), { - recursive: true, - }); - - await fs.writeFileSync( - path.resolve(outputPath, 'OpenAPI.ts'), - templates.core.settings({ - $config: config, - ...context, - }), - ); - await fs.writeFileSync( - path.resolve(outputPath, 'ApiError.ts'), - templates.core.apiError({ - $config: config, - ...context, - }), - ); - await fs.writeFileSync( - path.resolve(outputPath, 'ApiRequestOptions.ts'), - templates.core.apiRequestOptions({ - $config: config, - ...context, - }), - ); - await fs.writeFileSync( - path.resolve(outputPath, 'ApiResult.ts'), - templates.core.apiResult({ - $config: config, - ...context, - }), - ); - if (clientPlugin.name !== 'legacy/angular') { - await fs.writeFileSync( - path.resolve(outputPath, 'CancelablePromise.ts'), - templates.core.cancelablePromise({ - $config: config, - ...context, - }), - ); - } - await fs.writeFileSync( - path.resolve(outputPath, 'request.ts'), - templates.core.request({ - $config: config, - ...context, - }), - ); - - if (legacyNameFromConfig(config)) { - await fs.writeFileSync( - path.resolve(outputPath, 'BaseHttpRequest.ts'), - templates.core.baseHttpRequest({ - $config: config, - ...context, - }), - ); - await fs.writeFileSync( - path.resolve(outputPath, `${context.httpRequest}.ts`), - templates.core.httpRequest({ - $config: config, - ...context, - }), - ); - } - - if (config.request) { - const requestFile = path.resolve(process.cwd(), config.request); - const requestFileExists = await fs.existsSync(requestFile); - if (!requestFileExists) { - throw new Error(`Custom request file "${requestFile}" does not exists`); - } - await fs.copyFileSync( - requestFile, - path.resolve(outputPath, 'request.ts'), - ); - } - } -}; diff --git a/packages/openapi-ts/src/generate/file.ts b/packages/openapi-ts/src/generate/file.ts deleted file mode 100644 index 684ad95ca..000000000 --- a/packages/openapi-ts/src/generate/file.ts +++ /dev/null @@ -1,223 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import ts from 'typescript'; - -import { tsc } from '~/tsc'; -import { type ImportExportItemObject, tsNodeToString } from '~/tsc/utils'; - -import { ensureDirSync } from './utils'; - -type FileImportResult< - Name extends string | undefined = string | undefined, - Alias extends string | undefined = undefined, -> = { - asType?: boolean; - name: Alias extends string ? Alias : Name; -}; - -/** - * TODO: remove, it's used by legacy plugins - * - * @deprecated - */ -export class GeneratedFile { - /** - * Should the exports from this file be re-exported in the index barrel file? - */ - private _exportFromIndex: boolean; - private _headers: Array = []; - private _id: string; - private _imports = new Map>(); - private _items: Array = []; - private _name: string; - private _path: string; - - public constructor({ - dir, - exportFromIndex = false, - header = true, - id, - name, - }: { - dir: string; - /** - * Should the exports from this file be re-exported in the index barrel file? - */ - exportFromIndex?: boolean; - header?: boolean; - /** - * Unique file ID. Used to generate correct relative paths to the file. - * This should be refactored later as it's basically the file name unless - * nested inside another folder. - */ - id: string; - name: string; - }) { - this._exportFromIndex = exportFromIndex; - this._id = id; - this._name = this._setName(name); - this._path = path.resolve(dir, this._name); - - if (header) { - this._headers.push( - '// This file is auto-generated by @hey-api/openapi-ts', - ); - } - } - - public add(...nodes: Array) { - this._items = this._items.concat(nodes); - } - - public get exportFromIndex(): boolean { - return this._exportFromIndex; - } - - public get id(): string { - return this._id; - } - - /** - * Adds an import to the provided module. Handles duplication, returns added - * import. Returns the imported name. If we import an aliased export, `name` - * will be equal to the specified `alias`. - */ - public import< - Name extends string | undefined = string | undefined, - Alias extends string | undefined = undefined, - >({ - module, - ...importedItem - }: ImportExportItemObject & { - module: string; - }): FileImportResult { - if (!importedItem.name) { - return { - name: undefined as any, - }; - } - - let moduleMap = this._imports.get(module); - - if (!moduleMap) { - moduleMap = new Map(); - this._imports.set(module, moduleMap); - } - - const match = moduleMap.get(importedItem.name); - if (match) { - return { - ...match, - name: (match.alias || match.name) as any, - }; - } - - moduleMap.set(importedItem.name, importedItem as any); - return { - ...importedItem, - name: (importedItem.alias || importedItem.name) as any, - }; - } - - public isEmpty() { - return !this._items.length; - } - - public nameWithoutExtension() { - const { name } = splitNameAndExtension(this._name); - return name; - } - - public remove(options?: Parameters[1]) { - fs.rmSync(this._path, options); - } - - /** - * Removes last node form the stack. Works as undo. - * - * @deprecated - */ - public removeNode_LEGACY() { - this._items = this._items.slice(0, this._items.length - 1); - } - - private _setName(fileName: string) { - if (fileName.includes('index')) { - return fileName; - } - - const { extension, name } = splitNameAndExtension(fileName); - return [name, 'gen', extension].filter(Boolean).join('.'); - } - - private _toString(separator: string, tsConfig: ts.ParsedCommandLine | null) { - let output: Array = []; - if (this._headers.length) { - output.push(this._headers.join('\n')); - } - - const shouldAppendJs = - tsConfig?.options.moduleResolution === ts.ModuleResolutionKind.NodeNext; - - const importsStringArray: Array = []; - - for (const [_module, moduleMap] of this._imports.entries()) { - const imports = Array.from(moduleMap.values()); - - let resolvedModule = _module; - if ( - shouldAppendJs && - (resolvedModule.startsWith('./') || resolvedModule.startsWith('../')) - ) { - if (resolvedModule === './client') { - resolvedModule = './client/index.js'; - } else { - resolvedModule = `${resolvedModule}.js`; - } - } - - const node = tsc.namedImportDeclarations({ - imports, - module: resolvedModule, - }); - importsStringArray.push(tsNodeToString({ node })); - } - if (importsStringArray.length) { - output.push(importsStringArray.join('\n')); - } - output = output.concat( - this._items.map((node) => - typeof node === 'string' - ? node - : tsNodeToString({ node, unescape: true }), - ), - ); - return output.join(separator); - } - - public write(separator = '\n', tsConfig: ts.ParsedCommandLine | null = null) { - if (this.isEmpty()) { - this.remove({ force: true }); - return; - } - - let dir = this._path; - if (typeof this._path === 'string') { - const parts = this._path.split(path.sep); - dir = parts.slice(0, parts.length - 1).join(path.sep); - } - ensureDirSync(dir); - fs.writeFileSync(this._path, this._toString(separator, tsConfig)); - } -} - -export const splitNameAndExtension = (fileName: string) => { - const match = fileName.match(/\.[0-9a-z]+$/i); - const extension = match ? match[0].slice(1) : ''; - const name = fileName.slice( - 0, - fileName.length - (extension ? extension.length + 1 : 0), - ); - return { extension, name }; -}; diff --git a/packages/openapi-ts/src/generate/legacy/__tests__/index.test.ts b/packages/openapi-ts/src/generate/legacy/__tests__/index.test.ts deleted file mode 100644 index 63da2a694..000000000 --- a/packages/openapi-ts/src/generate/legacy/__tests__/index.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import { setConfig } from '~/utils/config'; - -import { GeneratedFile } from '../../file'; -import { generateIndexFile } from '../indexFile'; - -vi.mock('node:fs'); - -describe('generateIndexFile', () => { - it('writes to filesystem', async () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - const files: Parameters[0]['files'] = { - schemas: new GeneratedFile({ - dir: '/', - id: 'schemas', - name: 'schemas.ts', - }), - sdk: new GeneratedFile({ - dir: '/', - id: 'sdk', - name: 'sdk.ts', - }), - types: new GeneratedFile({ - dir: '/', - id: 'types', - name: 'types.ts', - }), - }; - - generateIndexFile({ files }); - - files.index!.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining(path.resolve('index.ts')), - expect.anything(), - ); - }); -}); diff --git a/packages/openapi-ts/src/generate/legacy/__tests__/output.test.ts b/packages/openapi-ts/src/generate/legacy/__tests__/output.test.ts deleted file mode 100644 index 3fc012aa1..000000000 --- a/packages/openapi-ts/src/generate/legacy/__tests__/output.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -import fs from 'node:fs'; - -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import type { Client } from '~/types/client'; -import type { Config } from '~/types/config'; -import { setConfig } from '~/utils/config'; - -import { mockTemplates, openApi } from '../../__tests__/mocks'; -import { generateLegacyOutput } from '../output'; - -vi.mock('node:fs', () => { - const exports = { - existsSync: vi.fn(), - mkdirSync: vi.fn(), - readdirSync: vi.fn().mockReturnValue([]), - rmSync: vi.fn(), - writeFileSync: vi.fn(), - }; - return { - ...exports, - default: exports, - }; -}); - -describe('generateLegacyOutput', () => { - it('writes to filesystem', async () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: 'prettier', - importFileExtension: undefined, - indexFile: true, - lint: null, - path: './dist', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }); - - const client: Client = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [], - types: {}, - version: 'v1', - }; - - await generateLegacyOutput({ - client, - openApi, - templates: mockTemplates, - }); - - expect(fs.rmSync).toHaveBeenCalled(); - expect(fs.mkdirSync).toHaveBeenCalled(); - expect(fs.writeFileSync).toHaveBeenCalled(); - }); -}); diff --git a/packages/openapi-ts/src/generate/legacy/indexFile.ts b/packages/openapi-ts/src/generate/legacy/indexFile.ts deleted file mode 100644 index f7b68184c..000000000 --- a/packages/openapi-ts/src/generate/legacy/indexFile.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; -import { tsc } from '~/tsc'; -import type { Files } from '~/types/utils'; -import { getConfig, legacyNameFromConfig } from '~/utils/config'; - -import { GeneratedFile } from '../file'; - -export const generateIndexFile = ({ files }: { files: Files }): void => { - const config = getConfig(); - - files.index = new GeneratedFile({ - dir: config.output.path, - id: 'index', - name: 'index.ts', - }); - - if (legacyNameFromConfig(config)) { - files.index.add( - tsc.exportNamedDeclaration({ - exports: legacyNameFromConfig(config)!, - module: `./${legacyNameFromConfig(config)}`, - }), - ); - } - - if (config.exportCore) { - files.index.add( - tsc.exportNamedDeclaration({ - exports: 'ApiError', - module: './core/ApiError', - }), - ); - if (config.plugins['@hey-api/sdk']?.config.response === 'response') { - files.index.add( - tsc.exportNamedDeclaration({ - exports: { asType: true, name: 'ApiResult' }, - module: './core/ApiResult', - }), - ); - } - if (legacyNameFromConfig(config)) { - files.index.add( - tsc.exportNamedDeclaration({ - exports: 'BaseHttpRequest', - module: './core/BaseHttpRequest', - }), - ); - } - const clientPlugin = getClientPlugin(config); - if (clientPlugin.name !== 'legacy/angular') { - files.index.add( - tsc.exportNamedDeclaration({ - exports: ['CancelablePromise', 'CancelError'], - module: './core/CancelablePromise', - }), - ); - } - files.index.add( - tsc.exportNamedDeclaration({ - exports: ['OpenAPI', { asType: true, name: 'OpenAPIConfig' }], - module: './core/OpenAPI', - }), - ); - } - - Object.keys(files) - .sort() - .forEach((name) => { - const file = files[name]!; - - if (name === 'index' || file.isEmpty()) { - return; - } - - if (file.exportFromIndex) { - files.index!.add( - tsc.exportAllDeclaration({ - module: `./${file.nameWithoutExtension()}`, - }), - ); - } - }); -}; diff --git a/packages/openapi-ts/src/generate/legacy/output.ts b/packages/openapi-ts/src/generate/legacy/output.ts deleted file mode 100644 index 38d4a56b8..000000000 --- a/packages/openapi-ts/src/generate/legacy/output.ts +++ /dev/null @@ -1,127 +0,0 @@ -import path from 'node:path'; - -import type { ProjectRenderMeta } from '@hey-api/codegen-core'; - -import type { OpenApi } from '~/openApi'; -import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; -import type { Client } from '~/types/client'; -import type { Files } from '~/types/utils'; -import { getConfig, isLegacyClient } from '~/utils/config'; -import type { Templates } from '~/utils/handlebars'; - -import { generateLegacyClientClass } from '../class'; -import { generateClientBundle } from '../client'; -import { generateLegacyCore } from '../core'; -import { GeneratedFile } from '../file'; -import { removeDirSync } from '../utils'; -import { generateIndexFile } from './indexFile'; - -/** - * Write our OpenAPI client, using the given templates at the given output - * @param openApi {@link OpenApi} Dereferenced OpenAPI specification - * @param client Client containing models, schemas, and services - * @param templates Templates wrapper with all loaded Handlebars templates - */ -export const generateLegacyOutput = async ({ - client, - openApi, - templates, -}: { - client: Client; - openApi: unknown; - templates: Templates; -}): Promise => { - const config = getConfig(); - - const spec = openApi as OpenApi; - - // TODO: parser - move to config.input - if (client) { - if ( - config.plugins['@hey-api/sdk']?.config.include && - config.plugins['@hey-api/sdk'].config.asClass - ) { - const regexp = new RegExp(config.plugins['@hey-api/sdk'].config.include); - client.services = client.services.filter((service) => - regexp.test(service.name), - ); - } - - if (config.plugins['@hey-api/typescript']?.config.include) { - const regexp = new RegExp( - config.plugins['@hey-api/typescript'].config.include, - ); - client.models = client.models.filter((model) => regexp.test(model.name)); - } - } - - const outputPath = path.resolve(config.output.path); - - if (config.output.clean) { - removeDirSync(outputPath); - } - - const clientPlugin = getClientPlugin(config); - if ( - !isLegacyClient(config) && - 'bundle' in clientPlugin.config && - clientPlugin.config.bundle && - !config.dryRun - ) { - const meta: ProjectRenderMeta = { - importFileExtension: config.output.importFileExtension, - }; - - generateClientBundle({ - meta, - outputPath, - // @ts-expect-error - plugin: clientPlugin, - }); - } - - // deprecated files - await generateLegacyClientClass(spec, outputPath, client, templates); - await generateLegacyCore( - path.resolve(config.output.path, 'core'), - client, - templates, - ); - - const files: Files = {}; - - for (const name of config.pluginOrder) { - const plugin = config.plugins[name]!; - const outputParts = ((plugin.output as string) ?? '').split('/'); - const outputDir = path.resolve( - config.output.path, - ...outputParts.slice(0, outputParts.length - 1), - ); - files[plugin.name] = new GeneratedFile({ - dir: outputDir, - id: `legacy-unused-${plugin.name}`, - name: `${outputParts[outputParts.length - 1]}.ts`, - }); - plugin.handlerLegacy?.({ - client, - files, - openApi: spec, - plugin: plugin as never, - }); - } - - // TODO: exports do not support .js extensions - generateIndexFile({ files }); - - Object.entries(files).forEach(([name, file]) => { - if (config.dryRun) { - return; - } - - if (name === 'index') { - file.write('\n', config.output.tsConfig); - } else { - file.write('\n\n', config.output.tsConfig); - } - }); -}; diff --git a/packages/openapi-ts/src/generate/output.ts b/packages/openapi-ts/src/generate/output.ts index 123978984..e8bb64192 100644 --- a/packages/openapi-ts/src/generate/output.ts +++ b/packages/openapi-ts/src/generate/output.ts @@ -7,13 +7,14 @@ import type { Context } from '~/ir/context'; import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; import { generateClientBundle } from './client'; -import { removeDirSync } from './utils'; export const generateOutput = async ({ context }: { context: Context }) => { const outputPath = path.resolve(context.config.output.path); if (context.config.output.clean) { - removeDirSync(outputPath); + if (fs.existsSync(outputPath)) { + fs.rmSync(outputPath, { force: true, recursive: true }); + } } const meta: ProjectRenderMeta = { diff --git a/packages/openapi-ts/src/generate/utils.ts b/packages/openapi-ts/src/generate/utils.ts index 508efbc0b..669540955 100644 --- a/packages/openapi-ts/src/generate/utils.ts +++ b/packages/openapi-ts/src/generate/utils.ts @@ -6,36 +6,3 @@ export const ensureDirSync = (path: PathLike) => { fs.mkdirSync(path, { recursive: true }); } }; - -export const removeDirSync = (path: PathLike) => { - if (fs.existsSync(path)) { - fs.rmSync(path, { force: true, recursive: true }); - } -}; - -/** - * Construct a relative import path to modules. This is used for example - * in plugins to import types or SDK module. - */ -export const relativeModulePath = ({ - moduleOutput, - sourceOutput, -}: { - /** - * Output path to the imported module. - * @example - * 'types' - */ - moduleOutput: string; - /** - * Output path to the source module. - * @example - * '@tanstack/react-query' - */ - sourceOutput: string; -}): string => { - const outputParts = sourceOutput.split('/'); - const relativePath = - Array.from({ length: outputParts.length }).fill('').join('../') || './'; - return `${relativePath}${moduleOutput}`; -}; diff --git a/packages/openapi-ts/src/index.ts b/packages/openapi-ts/src/index.ts index eb3deb813..9388b7700 100644 --- a/packages/openapi-ts/src/index.ts +++ b/packages/openapi-ts/src/index.ts @@ -114,8 +114,6 @@ export type { ExpressionTransformer } from './plugins/@hey-api/transformers/expr export type { TypeTransformer } from './plugins/@hey-api/transformers/types'; export { definePluginConfig } from './plugins/shared/utils/config'; export { compiler, tsc } from './tsc'; -export type { Operation } from './types/client'; export type { UserConfig } from './types/config'; -export type { LegacyIR } from './types/types'; export { utils } from './utils/exports'; export { Logger } from './utils/logger'; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/client.js b/packages/openapi-ts/src/legacy/handlebars/compiled/client.js deleted file mode 100644 index 66155fce4..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/client.js +++ /dev/null @@ -1,457 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return "import { NgModule} from '@angular/core';\nimport { HttpClientModule } from '@angular/common/http';\n\nimport { AngularHttpRequest } from './core/AngularHttpRequest';\nimport { BaseHttpRequest } from './core/BaseHttpRequest';\nimport type { OpenAPIConfig } from './core/OpenAPI';\nimport { OpenAPI } from './core/OpenAPI';\nimport { Interceptors } from './core/OpenAPI';\n"; - }, - 3: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = container.strict, - alias2 = container.lambda; - - return ( - "import type { BaseHttpRequest } from './core/BaseHttpRequest';\nimport type { OpenAPIConfig } from './core/OpenAPI';\nimport { Interceptors } from './core/OpenAPI';\nimport { " + - ((stack1 = alias2( - alias1(depth0, 'httpRequest', { - start: { line: 14, column: 12 }, - end: { line: 14, column: 23 }, - }), - depth0, - )) != null - ? stack1 - : '') + - " } from './core/" + - ((stack1 = alias2( - alias1(depth0, 'httpRequest', { - start: { line: 14, column: 45 }, - end: { line: 14, column: 56 }, - }), - depth0, - )) != null - ? stack1 - : '') + - "';\n" - ); - }, - 5: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return (stack1 = lookupProperty(helpers, 'each').call( - depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty(depth0, 'services'), - { - name: 'each', - hash: {}, - fn: container.program(6, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 18, column: 0 }, end: { line: 20, column: 9 } }, - }, - )) != null - ? stack1 - : ''; - }, - 6: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - 'import { ' + - ((stack1 = lookupProperty(helpers, 'transformServiceName').call( - depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty(depth0, 'name'), - { - name: 'transformServiceName', - hash: {}, - data: data, - loc: { - start: { line: 19, column: 9 }, - end: { line: 19, column: 40 }, - }, - }, - )) != null - ? stack1 - : '') + - " } from './sdk.gen';\n" - ); - }, - 8: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = container.strict, - alias2 = container.lambda, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - "@NgModule({\n imports: [HttpClientModule],\n providers: [\n {\n provide: OpenAPI,\n useValue: {\n BASE: OpenAPI?.BASE ?? '" + - ((stack1 = alias2( - alias1(depth0, 'server', { - start: { line: 30, column: 31 }, - end: { line: 30, column: 37 }, - }), - depth0, - )) != null - ? stack1 - : '') + - "',\n VERSION: OpenAPI?.VERSION ?? '" + - ((stack1 = alias2( - alias1(depth0, 'version', { - start: { line: 31, column: 37 }, - end: { line: 31, column: 44 }, - }), - depth0, - )) != null - ? stack1 - : '') + - "',\n WITH_CREDENTIALS: OpenAPI?.WITH_CREDENTIALS ?? false,\n CREDENTIALS: OpenAPI?.CREDENTIALS ?? 'include',\n TOKEN: OpenAPI?.TOKEN,\n USERNAME: OpenAPI?.USERNAME,\n PASSWORD: OpenAPI?.PASSWORD,\n HEADERS: OpenAPI?.HEADERS,\n ENCODE_PATH: OpenAPI?.ENCODE_PATH,\n interceptors: {\n response: OpenAPI?.interceptors?.response ?? new Interceptors(),\n },\n } as OpenAPIConfig,\n },\n {\n provide: BaseHttpRequest,\n useClass: AngularHttpRequest,\n },\n" + - ((stack1 = lookupProperty(helpers, 'each').call( - depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty(depth0, 'services'), - { - name: 'each', - hash: {}, - fn: container.program(9, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 48, column: 2 }, - end: { line: 50, column: 11 }, - }, - }, - )) != null - ? stack1 - : '') + - ' ]\n})\nexport class ' + - ((stack1 = alias2( - alias1( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'name', - { start: { line: 53, column: 16 }, end: { line: 53, column: 34 } }, - ), - depth0, - )) != null - ? stack1 - : '') + - ' {}\n' - ); - }, - 9: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ' ' + - ((stack1 = lookupProperty(helpers, 'transformServiceName').call( - depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty(depth0, 'name'), - { - name: 'transformServiceName', - hash: {}, - data: data, - loc: { - start: { line: 49, column: 2 }, - end: { line: 49, column: 33 }, - }, - }, - )) != null - ? stack1 - : '') + - ',\n' - ); - }, - 11: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = container.strict, - alias2 = container.lambda, - alias3 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - 'type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest;\n\nexport class ' + - ((stack1 = alias2( - alias1( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'name', - { start: { line: 57, column: 16 }, end: { line: 57, column: 34 } }, - ), - depth0, - )) != null - ? stack1 - : '') + - ' {\n\n' + - ((stack1 = lookupProperty(helpers, 'each').call( - alias3, - lookupProperty(depth0, 'services'), - { - name: 'each', - hash: {}, - fn: container.program(12, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 59, column: 1 }, - end: { line: 61, column: 10 }, - }, - }, - )) != null - ? stack1 - : '') + - '\n public readonly request: BaseHttpRequest;\n\n constructor(config?: Partial, HttpRequest: HttpRequestConstructor = ' + - ((stack1 = alias2( - alias1(depth0, 'httpRequest', { - start: { line: 65, column: 87 }, - end: { line: 65, column: 98 }, - }), - depth0, - )) != null - ? stack1 - : '') + - ") {\n this.request = new HttpRequest({\n BASE: config?.BASE ?? '" + - ((stack1 = alias2( - alias1(depth0, 'server', { - start: { line: 67, column: 29 }, - end: { line: 67, column: 35 }, - }), - depth0, - )) != null - ? stack1 - : '') + - "',\n VERSION: config?.VERSION ?? '" + - ((stack1 = alias2( - alias1(depth0, 'version', { - start: { line: 68, column: 35 }, - end: { line: 68, column: 42 }, - }), - depth0, - )) != null - ? stack1 - : '') + - "',\n WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,\n CREDENTIALS: config?.CREDENTIALS ?? 'include',\n TOKEN: config?.TOKEN,\n USERNAME: config?.USERNAME,\n PASSWORD: config?.PASSWORD,\n HEADERS: config?.HEADERS,\n ENCODE_PATH: config?.ENCODE_PATH,\n interceptors: {\n request: config?.interceptors?.request ?? new Interceptors(),\n response: config?.interceptors?.response ?? new Interceptors(),\n },\n });\n\n" + - ((stack1 = lookupProperty(helpers, 'each').call( - alias3, - lookupProperty(depth0, 'services'), - { - name: 'each', - hash: {}, - fn: container.program(14, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 82, column: 2 }, - end: { line: 84, column: 11 }, - }, - }, - )) != null - ? stack1 - : '') + - ' }\n}\n' - ); - }, - 12: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ' public readonly ' + - ((stack1 = lookupProperty(helpers, 'camelCase').call( - alias1, - lookupProperty(depth0, 'name'), - { - name: 'camelCase', - hash: {}, - data: data, - loc: { - start: { line: 60, column: 17 }, - end: { line: 60, column: 37 }, - }, - }, - )) != null - ? stack1 - : '') + - ': ' + - ((stack1 = lookupProperty(helpers, 'transformServiceName').call( - alias1, - lookupProperty(depth0, 'name'), - { - name: 'transformServiceName', - hash: {}, - data: data, - loc: { - start: { line: 60, column: 39 }, - end: { line: 60, column: 70 }, - }, - }, - )) != null - ? stack1 - : '') + - ';\n' - ); - }, - 14: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ' this.' + - ((stack1 = lookupProperty(helpers, 'camelCase').call( - alias1, - lookupProperty(depth0, 'name'), - { - name: 'camelCase', - hash: {}, - data: data, - loc: { - start: { line: 83, column: 7 }, - end: { line: 83, column: 27 }, - }, - }, - )) != null - ? stack1 - : '') + - ' = new ' + - ((stack1 = lookupProperty(helpers, 'transformServiceName').call( - alias1, - lookupProperty(depth0, 'name'), - { - name: 'transformServiceName', - hash: {}, - data: data, - loc: { - start: { line: 83, column: 34 }, - end: { line: 83, column: 65 }, - }, - }, - )) != null - ? stack1 - : '') + - '(this.request);\n' - ); - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.program(3, data, 0), - data: data, - loc: { start: { line: 1, column: 0 }, end: { line: 15, column: 11 } }, - }, - )) != null - ? stack1 - : '') + - '\n' + - ((stack1 = lookupProperty(helpers, 'if').call( - alias1, - lookupProperty(depth0, 'services'), - { - name: 'if', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 17, column: 0 }, end: { line: 21, column: 7 } }, - }, - )) != null - ? stack1 - : '') + - '\n' + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(8, data, 0), - inverse: container.program(11, data, 0), - data: data, - loc: { - start: { line: 23, column: 0 }, - end: { line: 87, column: 11 }, - }, - }, - )) != null - ? stack1 - : '') - ); - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiError.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiError.js deleted file mode 100644 index 4cb06ccc6..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiError.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "import type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { ApiResult } from './ApiResult';\n\nexport class ApiError extends Error {\n public readonly url: string;\n public readonly status: number;\n public readonly statusText: string;\n public readonly body: unknown;\n public readonly request: ApiRequestOptions;\n\n constructor(request: ApiRequestOptions, response: ApiResult, message: string) {\n super(message);\n\n this.name = 'ApiError';\n this.url = response.url;\n this.status = response.status;\n this.statusText = response.statusText;\n this.body = response.body;\n this.request = request;\n }\n}"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiRequestOptions.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiRequestOptions.js deleted file mode 100644 index b63eb8a02..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiRequestOptions.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export type ApiRequestOptions = {\n readonly body?: any;\n readonly cookies?: Record;\n readonly errors?: Record;\n readonly formData?: Record | any[] | Blob | File;\n readonly headers?: Record;\n readonly mediaType?: string;\n readonly method:\n | 'DELETE'\n | 'GET'\n | 'HEAD'\n | 'OPTIONS'\n | 'PATCH'\n | 'POST'\n | 'PUT';\n readonly path?: Record;\n readonly query?: Record;\n readonly responseHeader?: string;\n readonly responseTransformer?: (data: unknown) => Promise;\n readonly url: string;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiResult.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiResult.js deleted file mode 100644 index 6d87d8336..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/ApiResult.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export type ApiResult = {\n readonly body: TData;\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/BaseHttpRequest.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/BaseHttpRequest.js deleted file mode 100644 index 2d4bf78e2..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/BaseHttpRequest.js +++ /dev/null @@ -1,109 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return "import type { HttpClient } from '@angular/common/http';\nimport type { Observable } from 'rxjs';\n\nimport type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { OpenAPIConfig } from './OpenAPI';\n"; - }, - 3: function (container, depth0, helpers, partials, data) { - return "import type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { CancelablePromise } from './CancelablePromise';\nimport type { OpenAPIConfig } from './OpenAPI';\n"; - }, - 5: function (container, depth0, helpers, partials, data) { - return ' constructor(\n public readonly config: OpenAPIConfig,\n public readonly http: HttpClient,\n ) {}\n'; - }, - 7: function (container, depth0, helpers, partials, data) { - return ' constructor(public readonly config: OpenAPIConfig) {}\n'; - }, - 9: function (container, depth0, helpers, partials, data) { - return ' public abstract request(options: ApiRequestOptions): Observable;\n'; - }, - 11: function (container, depth0, helpers, partials, data) { - return ' public abstract request(options: ApiRequestOptions): CancelablePromise;\n'; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.program(3, data, 0), - data: data, - loc: { start: { line: 1, column: 0 }, end: { line: 11, column: 11 } }, - }, - )) != null - ? stack1 - : '') + - '\nexport abstract class BaseHttpRequest {\n\n' + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.program(7, data, 0), - data: data, - loc: { - start: { line: 15, column: 1 }, - end: { line: 22, column: 12 }, - }, - }, - )) != null - ? stack1 - : '') + - '\n' + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(9, data, 0), - inverse: container.program(11, data, 0), - data: data, - loc: { - start: { line: 24, column: 1 }, - end: { line: 28, column: 12 }, - }, - }, - )) != null - ? stack1 - : '') + - '}' - ); - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/CancelablePromise.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/CancelablePromise.js deleted file mode 100644 index 3da29856a..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/CancelablePromise.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export class CancelError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CancelError';\n }\n\n public get isCancelled(): boolean {\n return true;\n }\n}\n\nexport interface OnCancel {\n readonly isResolved: boolean;\n readonly isRejected: boolean;\n readonly isCancelled: boolean;\n\n (cancelHandler: () => void): void;\n}\n\nexport class CancelablePromise implements Promise {\n private _isResolved: boolean;\n private _isRejected: boolean;\n private _isCancelled: boolean;\n readonly cancelHandlers: (() => void)[];\n readonly promise: Promise;\n private _resolve?: (value: T | PromiseLike) => void;\n private _reject?: (reason?: unknown) => void;\n\n constructor(\n executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: unknown) => void,\n onCancel: OnCancel\n ) => void\n ) {\n this._isResolved = false;\n this._isRejected = false;\n this._isCancelled = false;\n this.cancelHandlers = [];\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n\n const onResolve = (value: T | PromiseLike): void => {\n if (this._isResolved || this._isRejected || this._isCancelled) {\n return;\n }\n this._isResolved = true;\n if (this._resolve) this._resolve(value);\n };\n\n const onReject = (reason?: unknown): void => {\n if (this._isResolved || this._isRejected || this._isCancelled) {\n return;\n }\n this._isRejected = true;\n if (this._reject) this._reject(reason);\n };\n\n const onCancel = (cancelHandler: () => void): void => {\n if (this._isResolved || this._isRejected || this._isCancelled) {\n return;\n }\n this.cancelHandlers.push(cancelHandler);\n };\n\n Object.defineProperty(onCancel, 'isResolved', {\n get: (): boolean => this._isResolved,\n });\n\n Object.defineProperty(onCancel, 'isRejected', {\n get: (): boolean => this._isRejected,\n });\n\n Object.defineProperty(onCancel, 'isCancelled', {\n get: (): boolean => this._isCancelled,\n });\n\n return executor(onResolve, onReject, onCancel as OnCancel);\n });\n }\n\n get [Symbol.toStringTag](): string {\n return \"Cancellable Promise\";\n }\n\n public then(\n onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null\n ): Promise {\n return this.promise.then(onFulfilled, onRejected);\n }\n\n public catch(\n onRejected?: ((reason: unknown) => TResult | PromiseLike) | null\n ): Promise {\n return this.promise.catch(onRejected);\n }\n\n public finally(onFinally?: (() => void) | null): Promise {\n return this.promise.finally(onFinally);\n }\n\n public cancel(): void {\n if (this._isResolved || this._isRejected || this._isCancelled) {\n return;\n }\n this._isCancelled = true;\n if (this.cancelHandlers.length) {\n try {\n for (const cancelHandler of this.cancelHandlers) {\n cancelHandler();\n }\n } catch (error) {\n console.warn('Cancellation threw an error', error);\n return;\n }\n }\n this.cancelHandlers.length = 0;\n if (this._reject) this._reject(new CancelError('Request aborted'));\n }\n\n public get isCancelled(): boolean {\n return this._isCancelled;\n }\n}"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/HttpRequest.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/HttpRequest.js deleted file mode 100644 index de89e82e7..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/HttpRequest.js +++ /dev/null @@ -1,147 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return "import { Inject, Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport type { Observable } from 'rxjs';\n\nimport type { ApiRequestOptions } from './ApiRequestOptions';\nimport { BaseHttpRequest } from './BaseHttpRequest';\nimport type { OpenAPIConfig } from './OpenAPI';\nimport { OpenAPI } from './OpenAPI';\nimport { request as __request } from './request';\n"; - }, - 3: function (container, depth0, helpers, partials, data) { - return "import type { ApiRequestOptions } from './ApiRequestOptions';\nimport { BaseHttpRequest } from './BaseHttpRequest';\nimport type { CancelablePromise } from './CancelablePromise';\nimport type { OpenAPIConfig } from './OpenAPI';\nimport { request as __request } from './request';\n"; - }, - 5: function (container, depth0, helpers, partials, data) { - return '@Injectable()\n'; - }, - 7: function (container, depth0, helpers, partials, data) { - return ' constructor(\n @Inject(OpenAPI)\n config: OpenAPIConfig,\n http: HttpClient,\n ) {\n super(config, http);\n }\n'; - }, - 9: function (container, depth0, helpers, partials, data) { - return ' constructor(config: OpenAPIConfig) {\n super(config);\n }\n'; - }, - 11: function (container, depth0, helpers, partials, data) { - return ' /**\n * Request method\n * @param options The request options from the service\n * @returns Observable\n * @throws ApiError\n */\n public override request(options: ApiRequestOptions): Observable {\n return __request(this.config, this.http, options);\n }\n'; - }, - 13: function (container, depth0, helpers, partials, data) { - return ' /**\n * Request method\n * @param options The request options from the service\n * @returns CancelablePromise\n * @throws ApiError\n */\n public override request(options: ApiRequestOptions): CancelablePromise {\n return __request(this.config, options);\n }\n'; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.program(3, data, 0), - data: data, - loc: { start: { line: 1, column: 0 }, end: { line: 17, column: 11 } }, - }, - )) != null - ? stack1 - : '') + - '\n' + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 19, column: 0 }, - end: { line: 21, column: 11 }, - }, - }, - )) != null - ? stack1 - : '') + - 'export class ' + - ((stack1 = container.lambda( - container.strict(depth0, 'httpRequest', { - start: { line: 22, column: 15 }, - end: { line: 22, column: 26 }, - }), - depth0, - )) != null - ? stack1 - : '') + - ' extends BaseHttpRequest {\n\n' + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(7, data, 0), - inverse: container.program(9, data, 0), - data: data, - loc: { - start: { line: 24, column: 1 }, - end: { line: 36, column: 12 }, - }, - }, - )) != null - ? stack1 - : '') + - '\n' + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(11, data, 0), - inverse: container.program(13, data, 0), - data: data, - loc: { - start: { line: 38, column: 1 }, - end: { line: 58, column: 12 }, - }, - }, - )) != null - ? stack1 - : '') + - '}' - ); - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/OpenAPI.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/OpenAPI.js deleted file mode 100644 index 6fef4a7c3..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/OpenAPI.js +++ /dev/null @@ -1,275 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return "import type { HttpResponse } from '@angular/common/http';\n"; - }, - 3: function (container, depth0, helpers, partials, data) { - return "import type { AxiosRequestConfig, AxiosResponse } from 'axios';\n"; - }, - 5: function (container, depth0, helpers, partials, data) { - return "import type { RequestInit, Response } from 'node-fetch';\n"; - }, - 7: function (container, depth0, helpers, partials, data) { - return ' response: Interceptors>;\n'; - }, - 9: function (container, depth0, helpers, partials, data) { - return ' request: Interceptors;\n response: Interceptors;\n'; - }, - 11: function (container, depth0, helpers, partials, data) { - return ' request: Interceptors;\n response: Interceptors;\n'; - }, - 13: function (container, depth0, helpers, partials, data) { - return ' request: Interceptors;\n response: Interceptors;\n'; - }, - 15: function (container, depth0, helpers, partials, data) { - return ' request: new Interceptors(),\n'; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - alias2 = container.strict, - alias3 = container.lambda, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 1, column: 0 }, end: { line: 3, column: 11 } }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/axios', - { - name: 'equals', - hash: {}, - fn: container.program(3, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 4, column: 0 }, end: { line: 6, column: 11 } }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/node', - { - name: 'equals', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 7, column: 0 }, end: { line: 9, column: 11 } }, - }, - )) != null - ? stack1 - : '') + - "import type { ApiRequestOptions } from './ApiRequestOptions';\n\ntype Headers = Record;\ntype Middleware = (value: T) => T | Promise;\ntype Resolver = (options: ApiRequestOptions) => Promise;\n\nexport class Interceptors {\n _fns: Middleware[];\n\n constructor() {\n this._fns = [];\n }\n\n eject(fn: Middleware): void {\n const index = this._fns.indexOf(fn);\n if (index !== -1) {\n this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)];\n }\n }\n\n use(fn: Middleware): void {\n this._fns = [...this._fns, fn];\n }\n}\n\nexport type OpenAPIConfig = {\n BASE: string;\n CREDENTIALS: 'include' | 'omit' | 'same-origin';\n ENCODE_PATH?: ((path: string) => string) | undefined;\n HEADERS?: Headers | Resolver | undefined;\n PASSWORD?: string | Resolver | undefined;\n TOKEN?: string | Resolver | undefined;\n USERNAME?: string | Resolver | undefined;\n VERSION: string;\n WITH_CREDENTIALS: boolean;\n interceptors: {\n" + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(7, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 46, column: 2 }, - end: { line: 48, column: 13 }, - }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/axios', - { - name: 'equals', - hash: {}, - fn: container.program(9, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 49, column: 2 }, - end: { line: 52, column: 13 }, - }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/fetch', - { - name: 'equals', - hash: {}, - fn: container.program(11, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 53, column: 2 }, - end: { line: 56, column: 13 }, - }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/node', - { - name: 'equals', - hash: {}, - fn: container.program(11, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 57, column: 2 }, - end: { line: 60, column: 13 }, - }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/xhr', - { - name: 'equals', - hash: {}, - fn: container.program(13, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 61, column: 2 }, - end: { line: 64, column: 13 }, - }, - }, - )) != null - ? stack1 - : '') + - " };\n};\n\nexport const OpenAPI: OpenAPIConfig = {\n BASE: '" + - ((stack1 = alias3( - alias2(depth0, 'server', { - start: { line: 69, column: 11 }, - end: { line: 69, column: 17 }, - }), - depth0, - )) != null - ? stack1 - : '') + - "',\n CREDENTIALS: 'include',\n ENCODE_PATH: undefined,\n HEADERS: undefined,\n PASSWORD: undefined,\n TOKEN: undefined,\n USERNAME: undefined,\n VERSION: '" + - ((stack1 = alias3( - alias2(depth0, 'version', { - start: { line: 76, column: 14 }, - end: { line: 76, column: 21 }, - }), - depth0, - )) != null - ? stack1 - : '') + - "',\n WITH_CREDENTIALS: false,\n interceptors: {\n" + - ((stack1 = lookupProperty(helpers, 'notEquals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'notEquals', - hash: {}, - fn: container.program(15, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 79, column: 2 }, - end: { line: 81, column: 16 }, - }, - }, - )) != null - ? stack1 - : '') + - ' response: new Interceptors(),\n },\n};' - ); - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getHeaders.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getHeaders.js deleted file mode 100644 index 107171f6b..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getHeaders.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getHeaders = (config: OpenAPIConfig, options: ApiRequestOptions): Observable => {\n return forkJoin({\n // @ts-ignore\n token: resolve(options, config.TOKEN),\n // @ts-ignore\n username: resolve(options, config.USERNAME),\n // @ts-ignore\n password: resolve(options, config.PASSWORD),\n // @ts-ignore\n additionalHeaders: resolve(options, config.HEADERS),\n }).pipe(\n map(({ token, username, password, additionalHeaders }) => {\n const headers = Object.entries({\n Accept: 'application/json',\n ...additionalHeaders,\n ...options.headers,\n })\n .filter(([, value]) => value !== undefined && value !== null)\n .reduce((headers, [key, value]) => ({\n ...headers,\n [key]: String(value),\n }), {} as Record);\n\n if (isStringWithValue(token)) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n if (isStringWithValue(username) && isStringWithValue(password)) {\n const credentials = base64(`${username}:${password}`);\n headers['Authorization'] = `Basic ${credentials}`;\n }\n\n if (options.body !== undefined) {\n if (options.mediaType) {\n headers['Content-Type'] = options.mediaType;\n } else if (isBlob(options.body)) {\n headers['Content-Type'] = options.body.type || 'application/octet-stream';\n } else if (isString(options.body)) {\n headers['Content-Type'] = 'text/plain';\n } else if (!isFormData(options.body)) {\n headers['Content-Type'] = 'application/json';\n }\n }\n\n return new HttpHeaders(headers);\n }),\n );\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getRequestBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getRequestBody.js deleted file mode 100644 index 180b22abe..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getRequestBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getRequestBody = (options: ApiRequestOptions): unknown => {\n if (options.body) {\n if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) {\n return JSON.stringify(options.body);\n } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {\n return options.body;\n } else {\n return JSON.stringify(options.body);\n }\n }\n return undefined;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseBody.js deleted file mode 100644 index 42fe81e07..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getResponseBody = (response: HttpResponse): T | undefined => {\n if (response.status !== 204 && response.body !== null) {\n return response.body;\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseHeader.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseHeader.js deleted file mode 100644 index 6fdbaff37..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/getResponseHeader.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getResponseHeader = (response: HttpResponse, responseHeader?: string): string | undefined => {\n if (responseHeader) {\n const value = response.headers.get(responseHeader);\n if (isString(value)) {\n return value;\n }\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/request.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/request.js deleted file mode 100644 index f9fe239aa..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/request.js +++ /dev/null @@ -1,230 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - "import { HttpClient, HttpHeaders } from '@angular/common/http';\nimport type { HttpResponse, HttpErrorResponse } from '@angular/common/http';\nimport { forkJoin, of, throwError } from 'rxjs';\nimport { catchError, map, switchMap } from 'rxjs/operators';\nimport type { Observable } from 'rxjs';\n\nimport { ApiError } from './ApiError';\nimport type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { ApiResult } from './ApiResult';\nimport type { OpenAPIConfig } from './OpenAPI';\n\n" + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isString'), - depth0, - { - name: 'functions/isString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isStringWithValue'), - depth0, - { - name: 'functions/isStringWithValue', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isBlob'), - depth0, - { - name: 'functions/isBlob', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isFormData'), - depth0, - { - name: 'functions/isFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/base64'), - depth0, - { - name: 'functions/base64', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getQueryString'), - depth0, - { - name: 'functions/getQueryString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getUrl'), - depth0, - { - name: 'functions/getUrl', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getFormData'), - depth0, - { - name: 'functions/getFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/resolve'), - depth0, - { - name: 'functions/resolve', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'angular/getHeaders'), - depth0, - { - name: 'angular/getHeaders', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'angular/getRequestBody'), - depth0, - { - name: 'angular/getRequestBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'angular/sendRequest'), - depth0, - { - name: 'angular/sendRequest', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'angular/getResponseHeader'), - depth0, - { - name: 'angular/getResponseHeader', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'angular/getResponseBody'), - depth0, - { - name: 'angular/getResponseBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/catchErrorCodes'), - depth0, - { - name: 'functions/catchErrorCodes', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n/**\n * Request method\n * @param config The OpenAPI configuration object\n * @param http The Angular HTTP client\n * @param options The request options from the service\n * @returns Observable\n * @throws ApiError\n */\nexport const request = (config: OpenAPIConfig, http: HttpClient, options: ApiRequestOptions): Observable => {\n const url = getUrl(config, options);\n const formData = getFormData(options);\n const body = getRequestBody(options);\n\n return getHeaders(config, options).pipe(\n switchMap(headers => {\n return sendRequest(config, options, http, url, body, formData, headers);\n }),\n switchMap(async response => {\n for (const fn of config.interceptors.response._fns) {\n response = await fn(response);\n }\n const responseBody = getResponseBody(response);\n const responseHeader = getResponseHeader(response, options.responseHeader);\n\n let transformedBody = responseBody;\n if (options.responseTransformer && response.ok) {\n transformedBody = await options.responseTransformer(responseBody)\n }\n\n return {\n url,\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n body: responseHeader ?? transformedBody,\n } as ApiResult;\n }),\n catchError((error: HttpErrorResponse) => {\n if (!error.status) {\n return throwError(() => error);\n }\n return of({\n url,\n ok: error.ok,\n status: error.status,\n statusText: error.statusText,\n body: error.error ?? error.statusText,\n } as ApiResult);\n }),\n map(result => {\n catchErrorCodes(options, result);\n return result.body as T;\n }),\n catchError((error: ApiError) => {\n return throwError(() => error);\n }),\n );\n};' - ); - }, - usePartial: true, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/sendRequest.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/sendRequest.js deleted file mode 100644 index 509435921..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/angular/sendRequest.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const sendRequest = (\n config: OpenAPIConfig,\n options: ApiRequestOptions,\n http: HttpClient,\n url: string,\n body: unknown,\n formData: FormData | undefined,\n headers: HttpHeaders\n): Observable> => {\n return http.request(options.method, url, {\n headers,\n body: body ?? formData,\n withCredentials: config.WITH_CREDENTIALS,\n observe: 'response',\n });\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getHeaders.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getHeaders.js deleted file mode 100644 index b6bbde16d..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getHeaders.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise> => {\n const [token, username, password, additionalHeaders] = await Promise.all([\n // @ts-ignore\n resolve(options, config.TOKEN),\n // @ts-ignore\n resolve(options, config.USERNAME),\n // @ts-ignore\n resolve(options, config.PASSWORD),\n // @ts-ignore\n resolve(options, config.HEADERS),\n ]);\n\n const headers = Object.entries({\n Accept: 'application/json',\n ...additionalHeaders,\n ...options.headers,\n })\n .filter(([, value]) => value !== undefined && value !== null)\n .reduce((headers, [key, value]) => ({\n ...headers,\n [key]: String(value),\n }), {} as Record);\n\n if (isStringWithValue(token)) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n if (isStringWithValue(username) && isStringWithValue(password)) {\n const credentials = base64(`${username}:${password}`);\n headers['Authorization'] = `Basic ${credentials}`;\n }\n\n if (options.body !== undefined) {\n if (options.mediaType) {\n headers['Content-Type'] = options.mediaType;\n } else if (isBlob(options.body)) {\n headers['Content-Type'] = options.body.type || 'application/octet-stream';\n } else if (isString(options.body)) {\n headers['Content-Type'] = 'text/plain';\n } else if (!isFormData(options.body)) {\n headers['Content-Type'] = 'application/json';\n }\n } else if (options.formData !== undefined) {\n if (options.mediaType) {\n headers['Content-Type'] = options.mediaType;\n }\n }\n\n return headers;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getRequestBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getRequestBody.js deleted file mode 100644 index 063582829..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getRequestBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getRequestBody = (options: ApiRequestOptions): unknown => {\n if (options.body) {\n return options.body;\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseBody.js deleted file mode 100644 index 800f8ddbe..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getResponseBody = (response: AxiosResponse): unknown => {\n if (response.status !== 204) {\n return response.data;\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseHeader.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseHeader.js deleted file mode 100644 index 3d79fee5e..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/getResponseHeader.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => {\n if (responseHeader) {\n const content = response.headers[responseHeader];\n if (isString(content)) {\n return content;\n }\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/request.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/request.js deleted file mode 100644 index 0993bd66e..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/request.js +++ /dev/null @@ -1,311 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return 'ApiResult'; - }, - 3: function (container, depth0, helpers, partials, data) { - return 'T'; - }, - 5: function (container, depth0, helpers, partials, data) { - return 'result.body'; - }, - 7: function (container, depth0, helpers, partials, data) { - return 'result'; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - "import axios from 'axios';\nimport type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios';\n\nimport { ApiError } from './ApiError';\nimport type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { ApiResult } from './ApiResult';\nimport { CancelablePromise } from './CancelablePromise';\nimport type { OnCancel } from './CancelablePromise';\nimport type { OpenAPIConfig } from './OpenAPI';\n\n" + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isString'), - depth0, - { - name: 'functions/isString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isStringWithValue'), - depth0, - { - name: 'functions/isStringWithValue', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isBlob'), - depth0, - { - name: 'functions/isBlob', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isFormData'), - depth0, - { - name: 'functions/isFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isSuccess'), - depth0, - { - name: 'functions/isSuccess', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/base64'), - depth0, - { - name: 'functions/base64', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getQueryString'), - depth0, - { - name: 'functions/getQueryString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getUrl'), - depth0, - { - name: 'functions/getUrl', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getFormData'), - depth0, - { - name: 'functions/getFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/resolve'), - depth0, - { - name: 'functions/resolve', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'axios/getHeaders'), - depth0, - { - name: 'axios/getHeaders', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'axios/getRequestBody'), - depth0, - { - name: 'axios/getRequestBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'axios/sendRequest'), - depth0, - { - name: 'axios/sendRequest', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'axios/getResponseHeader'), - depth0, - { - name: 'axios/getResponseHeader', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'axios/getResponseBody'), - depth0, - { - name: 'axios/getResponseBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/catchErrorCodes'), - depth0, - { - name: 'functions/catchErrorCodes', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n/**\n * Request method\n * @param config The OpenAPI configuration object\n * @param options The request options from the service\n * @param axiosClient The axios client instance to use\n * @returns CancelablePromise<' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'response', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.program(3, data, 0), - data: data, - loc: { - start: { line: 64, column: 30 }, - end: { line: 64, column: 108 }, - }, - }, - )) != null - ? stack1 - : '') + - '>\n * @throws ApiError\n */\nexport const request = (config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise<' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'response', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.program(3, data, 0), - data: data, - loc: { - start: { line: 67, column: 136 }, - end: { line: 67, column: 214 }, - }, - }, - )) != null - ? stack1 - : '') + - '> => {\n return new CancelablePromise(async (resolve, reject, onCancel) => {\n try {\n const url = getUrl(config, options);\n const formData = getFormData(options);\n const body = getRequestBody(options);\n const headers = await getHeaders(config, options);\n\n if (!onCancel.isCancelled) {\n let response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient);\n\n for (const fn of config.interceptors.response._fns) {\n response = await fn(response);\n }\n\n const responseBody = getResponseBody(response);\n const responseHeader = getResponseHeader(response, options.responseHeader);\n\n let transformedBody = responseBody;\n if (options.responseTransformer && isSuccess(response.status)) {\n transformedBody = await options.responseTransformer(responseBody)\n }\n\n const result: ApiResult = {\n url,\n ok: isSuccess(response.status),\n status: response.status,\n statusText: response.statusText,\n body: responseHeader ?? transformedBody,\n };\n\n catchErrorCodes(options, result);\n\n resolve(' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'body', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.program(7, data, 0), - data: data, - loc: { - start: { line: 100, column: 12 }, - end: { line: 100, column: 90 }, - }, - }, - )) != null - ? stack1 - : '') + - ');\n }\n } catch (error) {\n reject(error);\n }\n });\n};' - ); - }, - usePartial: true, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/sendRequest.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/sendRequest.js deleted file mode 100644 index 448fd04f1..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/axios/sendRequest.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const sendRequest = async (\n config: OpenAPIConfig,\n options: ApiRequestOptions,\n url: string,\n body: unknown,\n formData: FormData | undefined,\n headers: Record,\n onCancel: OnCancel,\n axiosClient: AxiosInstance\n): Promise> => {\n const controller = new AbortController();\n\n let requestConfig: AxiosRequestConfig = {\n data: body ?? formData,\n headers,\n method: options.method,\n signal: controller.signal,\n url,\n withCredentials: config.WITH_CREDENTIALS,\n };\n\n onCancel(() => controller.abort());\n\n for (const fn of config.interceptors.request._fns) {\n requestConfig = await fn(requestConfig);\n }\n\n try {\n return await axiosClient.request(requestConfig);\n } catch (error) {\n const axiosError = error as AxiosError;\n if (axiosError.response) {\n return axiosError.response;\n }\n throw error;\n }\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getHeaders.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getHeaders.js deleted file mode 100644 index ba30baa44..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getHeaders.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => {\n const [token, username, password, additionalHeaders] = await Promise.all([\n // @ts-ignore\n resolve(options, config.TOKEN),\n // @ts-ignore\n resolve(options, config.USERNAME),\n // @ts-ignore\n resolve(options, config.PASSWORD),\n // @ts-ignore\n resolve(options, config.HEADERS),\n ]);\n\n const headers = Object.entries({\n Accept: 'application/json',\n ...additionalHeaders,\n ...options.headers,\n })\n .filter(([, value]) => value !== undefined && value !== null)\n .reduce((headers, [key, value]) => ({\n ...headers,\n [key]: String(value),\n }), {} as Record);\n\n if (isStringWithValue(token)) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n if (isStringWithValue(username) && isStringWithValue(password)) {\n const credentials = base64(`${username}:${password}`);\n headers['Authorization'] = `Basic ${credentials}`;\n }\n\n if (options.body !== undefined) {\n if (options.mediaType) {\n headers['Content-Type'] = options.mediaType;\n } else if (isBlob(options.body)) {\n headers['Content-Type'] = options.body.type || 'application/octet-stream';\n } else if (isString(options.body)) {\n headers['Content-Type'] = 'text/plain';\n } else if (!isFormData(options.body)) {\n headers['Content-Type'] = 'application/json';\n }\n }\n\n return new Headers(headers);\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getRequestBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getRequestBody.js deleted file mode 100644 index 1378625cb..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getRequestBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getRequestBody = (options: ApiRequestOptions): unknown => {\n if (options.body !== undefined) {\n if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) {\n return JSON.stringify(options.body);\n } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {\n return options.body;\n } else {\n return JSON.stringify(options.body);\n }\n }\n return undefined;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseBody.js deleted file mode 100644 index 7b90b1b61..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getResponseBody = async (response: Response): Promise => {\n if (response.status !== 204) {\n try {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/'];\n if (contentType.includes('application/json') || contentType.includes('+json')) {\n return await response.json();\n } else if (binaryTypes.some(type => contentType.includes(type))) {\n return await response.blob();\n } else if (contentType.includes('multipart/form-data')) {\n return await response.formData();\n } else if (contentType.includes('text/')) {\n return await response.text();\n }\n }\n } catch (error) {\n console.error(error);\n }\n }\n return undefined;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseHeader.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseHeader.js deleted file mode 100644 index 46f79e225..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/getResponseHeader.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => {\n if (responseHeader) {\n const content = response.headers.get(responseHeader);\n if (isString(content)) {\n return content;\n }\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/request.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/request.js deleted file mode 100644 index 1957da010..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/request.js +++ /dev/null @@ -1,321 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return "import fetch, { FormData, Headers } from 'node-fetch';\nimport type { RequestInit, Response } from 'node-fetch';\n\n"; - }, - 3: function (container, depth0, helpers, partials, data) { - return 'ApiResult'; - }, - 5: function (container, depth0, helpers, partials, data) { - return 'T'; - }, - 7: function (container, depth0, helpers, partials, data) { - return 'result.body'; - }, - 9: function (container, depth0, helpers, partials, data) { - return 'result'; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/node', - { - name: 'equals', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 1, column: 0 }, end: { line: 5, column: 11 } }, - }, - )) != null - ? stack1 - : '') + - "import { ApiError } from './ApiError';\nimport type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { ApiResult } from './ApiResult';\nimport { CancelablePromise } from './CancelablePromise';\nimport type { OnCancel } from './CancelablePromise';\nimport type { OpenAPIConfig } from './OpenAPI';\n\n" + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isString'), - depth0, - { - name: 'functions/isString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isStringWithValue'), - depth0, - { - name: 'functions/isStringWithValue', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isBlob'), - depth0, - { - name: 'functions/isBlob', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isFormData'), - depth0, - { - name: 'functions/isFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/base64'), - depth0, - { - name: 'functions/base64', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getQueryString'), - depth0, - { - name: 'functions/getQueryString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getUrl'), - depth0, - { - name: 'functions/getUrl', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getFormData'), - depth0, - { - name: 'functions/getFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/resolve'), - depth0, - { - name: 'functions/resolve', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'fetch/getHeaders'), - depth0, - { - name: 'fetch/getHeaders', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'fetch/getRequestBody'), - depth0, - { - name: 'fetch/getRequestBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'fetch/sendRequest'), - depth0, - { - name: 'fetch/sendRequest', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'fetch/getResponseHeader'), - depth0, - { - name: 'fetch/getResponseHeader', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'fetch/getResponseBody'), - depth0, - { - name: 'fetch/getResponseBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/catchErrorCodes'), - depth0, - { - name: 'functions/catchErrorCodes', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n/**\n * Request method\n * @param config The OpenAPI configuration object\n * @param options The request options from the service\n * @returns CancelablePromise<' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'response', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(3, data, 0), - inverse: container.program(5, data, 0), - data: data, - loc: { - start: { line: 62, column: 30 }, - end: { line: 62, column: 108 }, - }, - }, - )) != null - ? stack1 - : '') + - '>\n * @throws ApiError\n */\nexport const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise<' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'response', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(3, data, 0), - inverse: container.program(5, data, 0), - data: data, - loc: { - start: { line: 65, column: 100 }, - end: { line: 65, column: 178 }, - }, - }, - )) != null - ? stack1 - : '') + - '> => {\n return new CancelablePromise(async (resolve, reject, onCancel) => {\n try {\n const url = getUrl(config, options);\n const formData = getFormData(options);\n const body = getRequestBody(options);\n const headers = await getHeaders(config, options);\n\n if (!onCancel.isCancelled) {\n let response = await sendRequest(config, options, url, body, formData, headers, onCancel);\n\n for (const fn of config.interceptors.response._fns) {\n response = await fn(response);\n }\n\n const responseBody = await getResponseBody(response);\n const responseHeader = getResponseHeader(response, options.responseHeader);\n\n let transformedBody = responseBody;\n if (options.responseTransformer && response.ok) {\n transformedBody = await options.responseTransformer(responseBody)\n }\n\n const result: ApiResult = {\n url,\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n body: responseHeader ?? transformedBody,\n };\n\n catchErrorCodes(options, result);\n\n resolve(' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'body', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(7, data, 0), - inverse: container.program(9, data, 0), - data: data, - loc: { - start: { line: 98, column: 12 }, - end: { line: 98, column: 90 }, - }, - }, - )) != null - ? stack1 - : '') + - ');\n }\n } catch (error) {\n reject(error);\n }\n });\n};' - ); - }, - usePartial: true, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/sendRequest.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/sendRequest.js deleted file mode 100644 index 0b0087c7b..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/fetch/sendRequest.js +++ /dev/null @@ -1,47 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return ' if (config.WITH_CREDENTIALS) {\n request.credentials = config.CREDENTIALS;\n }\n'; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - 'export const sendRequest = async (\n config: OpenAPIConfig,\n options: ApiRequestOptions,\n url: string,\n body: any,\n formData: FormData | undefined,\n headers: Headers,\n onCancel: OnCancel\n): Promise => {\n const controller = new AbortController();\n\n let request: RequestInit = {\n headers,\n body: body ?? formData,\n method: options.method,\n signal: controller.signal,\n };\n\n' + - ((stack1 = lookupProperty(helpers, 'equals').call( - depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/fetch', - { - name: 'equals', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.noop, - data: data, - loc: { - start: { line: 19, column: 1 }, - end: { line: 23, column: 12 }, - }, - }, - )) != null - ? stack1 - : '') + - '\n for (const fn of config.interceptors.request._fns) {\n request = await fn(request);\n }\n\n onCancel(() => controller.abort());\n\n return await fetch(url, request);\n};' - ); - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/base64.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/base64.js deleted file mode 100644 index b8fa64c80..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/base64.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const base64 = (str: string): string => {\n try {\n return btoa(str);\n } catch (err) {\n // @ts-ignore\n return Buffer.from(str).toString('base64');\n }\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/catchErrorCodes.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/catchErrorCodes.js deleted file mode 100644 index 91272e89e..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/catchErrorCodes.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => {\n const errors: Record = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 407: 'Proxy Authentication Required',\n 408: 'Request Timeout',\n 409: 'Conflict',\n 410: 'Gone',\n 411: 'Length Required',\n 412: 'Precondition Failed',\n 413: 'Payload Too Large',\n 414: 'URI Too Long',\n 415: 'Unsupported Media Type',\n 416: 'Range Not Satisfiable',\n 417: 'Expectation Failed',\n 418: 'Im a teapot',\n 421: 'Misdirected Request',\n 422: 'Unprocessable Content',\n 423: 'Locked',\n 424: 'Failed Dependency',\n 425: 'Too Early',\n 426: 'Upgrade Required',\n 428: 'Precondition Required',\n 429: 'Too Many Requests',\n 431: 'Request Header Fields Too Large',\n 451: 'Unavailable For Legal Reasons',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n 505: 'HTTP Version Not Supported',\n 506: 'Variant Also Negotiates',\n 507: 'Insufficient Storage',\n 508: 'Loop Detected',\n 510: 'Not Extended',\n 511: 'Network Authentication Required',\n ...options.errors,\n }\n\n const error = errors[result.status];\n if (error) {\n throw new ApiError(options, result, error);\n }\n\n if (!result.ok) {\n const errorStatus = result.status ?? 'unknown';\n const errorStatusText = result.statusText ?? 'unknown';\n const errorBody = (() => {\n try {\n return JSON.stringify(result.body, null, 2);\n } catch (e) {\n return undefined;\n }\n })();\n\n throw new ApiError(options, result,\n `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`\n );\n }\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getFormData.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getFormData.js deleted file mode 100644 index aadad3cc5..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getFormData.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getFormData = (options: ApiRequestOptions): FormData | undefined => {\n if (options.formData) {\n const formData = new FormData();\n\n const process = (key: string, value: unknown) => {\n if (isString(value) || isBlob(value)) {\n formData.append(key, value);\n } else {\n formData.append(key, JSON.stringify(value));\n }\n };\n\n Object.entries(options.formData)\n .filter(([, value]) => value !== undefined && value !== null)\n .forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach(v => process(key, v));\n } else {\n process(key, value);\n }\n });\n\n return formData;\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getQueryString.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getQueryString.js deleted file mode 100644 index f9c6ca47b..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getQueryString.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getQueryString = (params: Record): string => {\n const qs: string[] = [];\n\n const append = (key: string, value: unknown) => {\n qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n };\n\n const encodePair = (key: string, value: unknown) => {\n if (value === undefined || value === null) {\n return;\n }\n\n if (value instanceof Date) {\n append(key, value.toISOString());\n } else if (Array.isArray(value)) {\n value.forEach(v => encodePair(key, v));\n } else if (typeof value === 'object') {\n Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v));\n } else {\n append(key, value);\n }\n };\n\n Object.entries(params).forEach(([key, value]) => encodePair(key, value));\n\n return qs.length ? `?${qs.join('&')}` : '';\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getUrl.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getUrl.js deleted file mode 100644 index 6229a3a36..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/getUrl.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {\n const encoder = config.ENCODE_PATH || encodeURI;\n\n const path = options.url\n .replace('{api-version}', config.VERSION)\n .replace(/{(.*?)}/g, (substring: string, group: string) => {\n if (options.path?.hasOwnProperty(group)) {\n return encoder(String(options.path[group]));\n }\n return substring;\n });\n\n const url = config.BASE + path;\n return options.query ? url + getQueryString(options.query) : url;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isBlob.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isBlob.js deleted file mode 100644 index a2e49389a..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isBlob.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const isBlob = (value: any): value is Blob => {\n return value instanceof Blob;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isFormData.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isFormData.js deleted file mode 100644 index 9d0880a49..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isFormData.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const isFormData = (value: unknown): value is FormData => {\n return value instanceof FormData;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isString.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isString.js deleted file mode 100644 index 54f1fd264..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isString.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const isString = (value: unknown): value is string => {\n return typeof value === 'string';\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isStringWithValue.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isStringWithValue.js deleted file mode 100644 index 693b6f883..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isStringWithValue.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const isStringWithValue = (value: unknown): value is string => {\n return isString(value) && value !== '';\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isSuccess.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isSuccess.js deleted file mode 100644 index b51b66827..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/isSuccess.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const isSuccess = (status: number): boolean => {\n return status >= 200 && status < 300;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/resolve.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/resolve.js deleted file mode 100644 index 79457a4a7..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/functions/resolve.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "type Resolver = (options: ApiRequestOptions) => Promise;\n\nexport const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => {\n if (typeof resolver === 'function') {\n return (resolver as Resolver)(options);\n }\n return resolver;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/request.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/request.js deleted file mode 100644 index f536aca4a..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/request.js +++ /dev/null @@ -1,225 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return (stack1 = container.invokePartial( - lookupProperty(partials, 'angular/request'), - depth0, - { - name: 'angular/request', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : ''; - }, - 3: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return (stack1 = container.invokePartial( - lookupProperty(partials, 'axios/request'), - depth0, - { - name: 'axios/request', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : ''; - }, - 5: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return (stack1 = container.invokePartial( - lookupProperty(partials, 'fetch/request'), - depth0, - { - name: 'fetch/request', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : ''; - }, - 7: function (container, depth0, helpers, partials, data) { - var stack1, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return (stack1 = container.invokePartial( - lookupProperty(partials, 'xhr/request'), - depth0, - { - name: 'xhr/request', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : ''; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/angular', - { - name: 'equals', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 87 } }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/axios', - { - name: 'equals', - hash: {}, - fn: container.program(3, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 2, column: 0 }, end: { line: 2, column: 83 } }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/fetch', - { - name: 'equals', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 3, column: 0 }, end: { line: 3, column: 83 } }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/node', - { - name: 'equals', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 4, column: 0 }, end: { line: 4, column: 82 } }, - }, - )) != null - ? stack1 - : '') + - ((stack1 = lookupProperty(helpers, 'equals').call( - alias1, - lookupProperty( - lookupProperty( - lookupProperty(lookupProperty(data, 'root'), '$config'), - 'client', - ), - 'name', - ), - 'legacy/xhr', - { - name: 'equals', - hash: {}, - fn: container.program(7, data, 0), - inverse: container.noop, - data: data, - loc: { start: { line: 5, column: 0 }, end: { line: 5, column: 79 } }, - }, - )) != null - ? stack1 - : '') - ); - }, - usePartial: true, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getHeaders.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getHeaders.js deleted file mode 100644 index ba30baa44..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getHeaders.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => {\n const [token, username, password, additionalHeaders] = await Promise.all([\n // @ts-ignore\n resolve(options, config.TOKEN),\n // @ts-ignore\n resolve(options, config.USERNAME),\n // @ts-ignore\n resolve(options, config.PASSWORD),\n // @ts-ignore\n resolve(options, config.HEADERS),\n ]);\n\n const headers = Object.entries({\n Accept: 'application/json',\n ...additionalHeaders,\n ...options.headers,\n })\n .filter(([, value]) => value !== undefined && value !== null)\n .reduce((headers, [key, value]) => ({\n ...headers,\n [key]: String(value),\n }), {} as Record);\n\n if (isStringWithValue(token)) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n if (isStringWithValue(username) && isStringWithValue(password)) {\n const credentials = base64(`${username}:${password}`);\n headers['Authorization'] = `Basic ${credentials}`;\n }\n\n if (options.body !== undefined) {\n if (options.mediaType) {\n headers['Content-Type'] = options.mediaType;\n } else if (isBlob(options.body)) {\n headers['Content-Type'] = options.body.type || 'application/octet-stream';\n } else if (isString(options.body)) {\n headers['Content-Type'] = 'text/plain';\n } else if (!isFormData(options.body)) {\n headers['Content-Type'] = 'application/json';\n }\n }\n\n return new Headers(headers);\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getRequestBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getRequestBody.js deleted file mode 100644 index 1378625cb..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getRequestBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getRequestBody = (options: ApiRequestOptions): unknown => {\n if (options.body !== undefined) {\n if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) {\n return JSON.stringify(options.body);\n } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {\n return options.body;\n } else {\n return JSON.stringify(options.body);\n }\n }\n return undefined;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseBody.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseBody.js deleted file mode 100644 index 8229393a7..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseBody.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const getResponseBody = (xhr: XMLHttpRequest): unknown => {\n if (xhr.status !== 204) {\n try {\n const contentType = xhr.getResponseHeader('Content-Type');\n if (contentType) {\n if (contentType.includes('application/json') || contentType.includes('+json')) {\n return JSON.parse(xhr.responseText);\n } else {\n return xhr.responseText;\n }\n }\n } catch (error) {\n console.error(error);\n }\n }\n return undefined;\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseHeader.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseHeader.js deleted file mode 100644 index 560ee1ef8..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/getResponseHeader.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return 'export const getResponseHeader = (xhr: XMLHttpRequest, responseHeader?: string): string | undefined => {\n if (responseHeader) {\n const content = xhr.getResponseHeader(responseHeader);\n if (isString(content)) {\n return content;\n }\n }\n return undefined;\n};'; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/request.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/request.js deleted file mode 100644 index 857471311..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/request.js +++ /dev/null @@ -1,311 +0,0 @@ -export default { - 1: function (container, depth0, helpers, partials, data) { - return 'ApiResult'; - }, - 3: function (container, depth0, helpers, partials, data) { - return 'T'; - }, - 5: function (container, depth0, helpers, partials, data) { - return 'result.body'; - }, - 7: function (container, depth0, helpers, partials, data) { - return 'result'; - }, - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - var stack1, - alias1 = depth0 != null ? depth0 : container.nullContext || {}, - lookupProperty = - container.lookupProperty || - function (parent, propertyName) { - if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { - return parent[propertyName]; - } - return undefined; - }; - - return ( - "import { ApiError } from './ApiError';\nimport type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { ApiResult } from './ApiResult';\nimport { CancelablePromise } from './CancelablePromise';\nimport type { OnCancel } from './CancelablePromise';\nimport type { OpenAPIConfig } from './OpenAPI';\n\n" + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isString'), - depth0, - { - name: 'functions/isString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isStringWithValue'), - depth0, - { - name: 'functions/isStringWithValue', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isBlob'), - depth0, - { - name: 'functions/isBlob', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isFormData'), - depth0, - { - name: 'functions/isFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/isSuccess'), - depth0, - { - name: 'functions/isSuccess', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/base64'), - depth0, - { - name: 'functions/base64', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getQueryString'), - depth0, - { - name: 'functions/getQueryString', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getUrl'), - depth0, - { - name: 'functions/getUrl', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/getFormData'), - depth0, - { - name: 'functions/getFormData', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/resolve'), - depth0, - { - name: 'functions/resolve', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'fetch/getHeaders'), - depth0, - { - name: 'fetch/getHeaders', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'xhr/getRequestBody'), - depth0, - { - name: 'xhr/getRequestBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'xhr/sendRequest'), - depth0, - { - name: 'xhr/sendRequest', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'xhr/getResponseHeader'), - depth0, - { - name: 'xhr/getResponseHeader', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'xhr/getResponseBody'), - depth0, - { - name: 'xhr/getResponseBody', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n' + - ((stack1 = container.invokePartial( - lookupProperty(partials, 'functions/catchErrorCodes'), - depth0, - { - name: 'functions/catchErrorCodes', - data: data, - helpers: helpers, - partials: partials, - decorators: container.decorators, - }, - )) != null - ? stack1 - : '') + - '\n\n/**\n * Request method\n * @param config The OpenAPI configuration object\n * @param options The request options from the service\n * @returns CancelablePromise<' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'response', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.program(3, data, 0), - data: data, - loc: { - start: { line: 60, column: 30 }, - end: { line: 60, column: 108 }, - }, - }, - )) != null - ? stack1 - : '') + - '>\n * @throws ApiError\n */\nexport const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise<' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'response', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(1, data, 0), - inverse: container.program(3, data, 0), - data: data, - loc: { - start: { line: 63, column: 100 }, - end: { line: 63, column: 178 }, - }, - }, - )) != null - ? stack1 - : '') + - '> => {\n return new CancelablePromise(async (resolve, reject, onCancel) => {\n try {\n const url = getUrl(config, options);\n const formData = getFormData(options);\n const body = getRequestBody(options);\n const headers = await getHeaders(config, options);\n\n if (!onCancel.isCancelled) {\n let response = await sendRequest(config, options, url, body, formData, headers, onCancel);\n\n for (const fn of config.interceptors.response._fns) {\n response = await fn(response);\n }\n\n const responseBody = getResponseBody(response);\n const responseHeader = getResponseHeader(response, options.responseHeader);\n\n let transformedBody = responseBody;\n if (options.responseTransformer && isSuccess(response.status)) {\n transformedBody = await options.responseTransformer(responseBody)\n }\n\n const result: ApiResult = {\n url,\n ok: isSuccess(response.status),\n status: response.status,\n statusText: response.statusText,\n body: responseHeader ?? transformedBody,\n };\n\n catchErrorCodes(options, result);\n\n resolve(' + - ((stack1 = lookupProperty(helpers, 'ifServicesResponse').call( - alias1, - 'body', - { - name: 'ifServicesResponse', - hash: {}, - fn: container.program(5, data, 0), - inverse: container.program(7, data, 0), - data: data, - loc: { - start: { line: 96, column: 12 }, - end: { line: 96, column: 90 }, - }, - }, - )) != null - ? stack1 - : '') + - ');\n }\n } catch (error) {\n reject(error);\n }\n });\n};' - ); - }, - usePartial: true, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/sendRequest.js b/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/sendRequest.js deleted file mode 100644 index 41c79a585..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/compiled/core/xhr/sendRequest.js +++ /dev/null @@ -1,7 +0,0 @@ -export default { - compiler: [8, '>= 4.3.0'], - main: function (container, depth0, helpers, partials, data) { - return "export const sendRequest = async (\n config: OpenAPIConfig,\n options: ApiRequestOptions,\n url: string,\n body: any,\n formData: FormData | undefined,\n headers: Headers,\n onCancel: OnCancel\n): Promise => {\n let xhr = new XMLHttpRequest();\n xhr.open(options.method, url, true);\n xhr.withCredentials = config.WITH_CREDENTIALS;\n\n headers.forEach((value, key) => {\n xhr.setRequestHeader(key, value);\n });\n\n return new Promise(async (resolve, reject) => {\n xhr.onload = () => resolve(xhr);\n xhr.onabort = () => reject(new Error('Request aborted'));\n xhr.onerror = () => reject(new Error('Network error'));\n\n for (const fn of config.interceptors.request._fns) {\n xhr = await fn(xhr);\n }\n\n xhr.send(body ?? formData);\n\n onCancel(() => xhr.abort());\n });\n};"; - }, - useData: true, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/handlebars.cjs b/packages/openapi-ts/src/legacy/handlebars/handlebars.cjs deleted file mode 100644 index d5501d54d..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/handlebars.cjs +++ /dev/null @@ -1,72 +0,0 @@ -const Handlebars = require('handlebars'); -const fs = require('node:fs'); -const path = require('node:path'); - -const getFilesRecursively = (folderPath) => { - let fileList = []; - - const files = fs.readdirSync(folderPath); - - files.forEach((file) => { - const fullPath = path.join(folderPath, file); - - if (fs.statSync(fullPath).isDirectory()) { - fileList = fileList.concat(getFilesRecursively(fullPath)); - } else { - fileList.push(fullPath); - } - }); - - return fileList; -}; - -const templatePaths = getFilesRecursively( - path.resolve('src', 'legacy', 'handlebars', 'templates'), -); - -const compiledDirPath = path.resolve('src', 'legacy', 'handlebars', 'compiled'); - -if (fs.existsSync(compiledDirPath)) { - fs.rmdirSync(compiledDirPath, { - recursive: true, - }); -} - -templatePaths.forEach((templatePath) => { - const template = fs.readFileSync(templatePath, 'utf8').toString().trim(); - - const compiled = Handlebars.precompile(template, { - knownHelpers: { - camelCase: true, - equals: true, - ifServicesResponse: true, - ifdef: true, - notEquals: true, - transformServiceName: true, - }, - knownHelpersOnly: true, - noEscape: true, - preventIndent: true, - strict: true, - }); - - const parts = templatePath.split(path.sep); - const fileName = parts[parts.length - 1]; - const fileNameParts = fileName.split('.'); - const fileNameBase = fileNameParts - .slice(0, fileNameParts.length - 1) - .join('.'); - const compiledPath = path.resolve( - compiledDirPath, - ...parts.slice(parts.lastIndexOf('templates') + 1, parts.length - 1), - `${fileNameBase}.js`, - ); - - const compiledDir = path.dirname(compiledPath); - - if (!fs.existsSync(compiledDir)) { - fs.mkdirSync(compiledDir, { recursive: true }); - } - - fs.writeFileSync(compiledPath, `export default ${compiled};`); -}); diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/client.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/client.hbs deleted file mode 100644 index 6c38dc2f9..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/client.hbs +++ /dev/null @@ -1,87 +0,0 @@ -{{#equals @root.$config.client.name 'legacy/angular'}} -import { NgModule} from '@angular/core'; -import { HttpClientModule } from '@angular/common/http'; - -import { AngularHttpRequest } from './core/AngularHttpRequest'; -import { BaseHttpRequest } from './core/BaseHttpRequest'; -import type { OpenAPIConfig } from './core/OpenAPI'; -import { OpenAPI } from './core/OpenAPI'; -import { Interceptors } from './core/OpenAPI'; -{{else}} -import type { BaseHttpRequest } from './core/BaseHttpRequest'; -import type { OpenAPIConfig } from './core/OpenAPI'; -import { Interceptors } from './core/OpenAPI'; -import { {{{httpRequest}}} } from './core/{{{httpRequest}}}'; -{{/equals}} - -{{#if services}} -{{#each services}} -import { {{{transformServiceName name}}} } from './sdk.gen'; -{{/each}} -{{/if}} - -{{#equals @root.$config.client.name 'legacy/angular'}} -@NgModule({ - imports: [HttpClientModule], - providers: [ - { - provide: OpenAPI, - useValue: { - BASE: OpenAPI?.BASE ?? '{{{server}}}', - VERSION: OpenAPI?.VERSION ?? '{{{version}}}', - WITH_CREDENTIALS: OpenAPI?.WITH_CREDENTIALS ?? false, - CREDENTIALS: OpenAPI?.CREDENTIALS ?? 'include', - TOKEN: OpenAPI?.TOKEN, - USERNAME: OpenAPI?.USERNAME, - PASSWORD: OpenAPI?.PASSWORD, - HEADERS: OpenAPI?.HEADERS, - ENCODE_PATH: OpenAPI?.ENCODE_PATH, - interceptors: { - response: OpenAPI?.interceptors?.response ?? new Interceptors(), - }, - } as OpenAPIConfig, - }, - { - provide: BaseHttpRequest, - useClass: AngularHttpRequest, - }, - {{#each services}} - {{{transformServiceName name}}}, - {{/each}} - ] -}) -export class {{{@root.$config.name}}} {} -{{else}} -type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest; - -export class {{{@root.$config.name}}} { - - {{#each services}} - public readonly {{{camelCase name}}}: {{{transformServiceName name}}}; - {{/each}} - - public readonly request: BaseHttpRequest; - - constructor(config?: Partial, HttpRequest: HttpRequestConstructor = {{{httpRequest}}}) { - this.request = new HttpRequest({ - BASE: config?.BASE ?? '{{{server}}}', - VERSION: config?.VERSION ?? '{{{version}}}', - WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false, - CREDENTIALS: config?.CREDENTIALS ?? 'include', - TOKEN: config?.TOKEN, - USERNAME: config?.USERNAME, - PASSWORD: config?.PASSWORD, - HEADERS: config?.HEADERS, - ENCODE_PATH: config?.ENCODE_PATH, - interceptors: { - request: config?.interceptors?.request ?? new Interceptors(), - response: config?.interceptors?.response ?? new Interceptors(), - }, - }); - - {{#each services}} - this.{{{camelCase name}}} = new {{{transformServiceName name}}}(this.request); - {{/each}} - } -} -{{/equals}} diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiError.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiError.hbs deleted file mode 100644 index 9cf094969..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiError.hbs +++ /dev/null @@ -1,21 +0,0 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; - - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiRequestOptions.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiRequestOptions.hbs deleted file mode 100644 index 65a21f789..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiRequestOptions.hbs +++ /dev/null @@ -1,21 +0,0 @@ -export type ApiRequestOptions = { - readonly body?: any; - readonly cookies?: Record; - readonly errors?: Record; - readonly formData?: Record | any[] | Blob | File; - readonly headers?: Record; - readonly mediaType?: string; - readonly method: - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT'; - readonly path?: Record; - readonly query?: Record; - readonly responseHeader?: string; - readonly responseTransformer?: (data: unknown) => Promise; - readonly url: string; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiResult.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiResult.hbs deleted file mode 100644 index 84b9f9da7..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/ApiResult.hbs +++ /dev/null @@ -1,7 +0,0 @@ -export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/BaseHttpRequest.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/BaseHttpRequest.hbs deleted file mode 100644 index 71dbcc886..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/BaseHttpRequest.hbs +++ /dev/null @@ -1,29 +0,0 @@ -{{#equals @root.$config.client.name 'legacy/angular'}} -import type { HttpClient } from '@angular/common/http'; -import type { Observable } from 'rxjs'; - -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { OpenAPIConfig } from './OpenAPI'; -{{else}} -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; -{{/equals}} - -export abstract class BaseHttpRequest { - - {{#equals @root.$config.client.name 'legacy/angular'}} - constructor( - public readonly config: OpenAPIConfig, - public readonly http: HttpClient, - ) {} - {{else}} - constructor(public readonly config: OpenAPIConfig) {} - {{/equals}} - - {{#equals @root.$config.client.name 'legacy/angular'}} - public abstract request(options: ApiRequestOptions): Observable; - {{else}} - public abstract request(options: ApiRequestOptions): CancelablePromise; - {{/equals}} -} diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/CancelablePromise.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/CancelablePromise.hbs deleted file mode 100644 index 5c10c4ed6..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/CancelablePromise.hbs +++ /dev/null @@ -1,126 +0,0 @@ -export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag](): string { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/HttpRequest.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/HttpRequest.hbs deleted file mode 100644 index f962ea697..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/HttpRequest.hbs +++ /dev/null @@ -1,59 +0,0 @@ -{{#equals @root.$config.client.name 'legacy/angular'}} -import { Inject, Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import type { Observable } from 'rxjs'; - -import type { ApiRequestOptions } from './ApiRequestOptions'; -import { BaseHttpRequest } from './BaseHttpRequest'; -import type { OpenAPIConfig } from './OpenAPI'; -import { OpenAPI } from './OpenAPI'; -import { request as __request } from './request'; -{{else}} -import type { ApiRequestOptions } from './ApiRequestOptions'; -import { BaseHttpRequest } from './BaseHttpRequest'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; -import { request as __request } from './request'; -{{/equals}} - -{{#equals @root.$config.client.name 'legacy/angular'}} -@Injectable() -{{/equals}} -export class {{httpRequest}} extends BaseHttpRequest { - - {{#equals @root.$config.client.name 'legacy/angular'}} - constructor( - @Inject(OpenAPI) - config: OpenAPIConfig, - http: HttpClient, - ) { - super(config, http); - } - {{else}} - constructor(config: OpenAPIConfig) { - super(config); - } - {{/equals}} - - {{#equals @root.$config.client.name 'legacy/angular'}} - /** - * Request method - * @param options The request options from the service - * @returns Observable - * @throws ApiError - */ - public override request(options: ApiRequestOptions): Observable { - return __request(this.config, this.http, options); - } - {{else}} - /** - * Request method - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ - public override request(options: ApiRequestOptions): CancelablePromise { - return __request(this.config, options); - } - {{/equals}} -} diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/OpenAPI.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/OpenAPI.hbs deleted file mode 100644 index b9864929d..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/OpenAPI.hbs +++ /dev/null @@ -1,84 +0,0 @@ -{{#equals @root.$config.client.name 'legacy/angular'}} -import type { HttpResponse } from '@angular/common/http'; -{{/equals}} -{{#equals @root.$config.client.name 'legacy/axios'}} -import type { AxiosRequestConfig, AxiosResponse } from 'axios'; -{{/equals}} -{{#equals @root.$config.client.name 'legacy/node'}} -import type { RequestInit, Response } from 'node-fetch'; -{{/equals}} -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Headers = Record; -type Middleware = (value: T) => T | Promise; -type Resolver = (options: ApiRequestOptions) => Promise; - -export class Interceptors { - _fns: Middleware[]; - - constructor() { - this._fns = []; - } - - eject(fn: Middleware): void { - const index = this._fns.indexOf(fn); - if (index !== -1) { - this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; - } - } - - use(fn: Middleware): void { - this._fns = [...this._fns, fn]; - } -} - -export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - {{#equals @root.$config.client.name 'legacy/angular'}} - response: Interceptors>; - {{/equals}} - {{#equals @root.$config.client.name 'legacy/axios'}} - request: Interceptors; - response: Interceptors; - {{/equals}} - {{#equals @root.$config.client.name 'legacy/fetch'}} - request: Interceptors; - response: Interceptors; - {{/equals}} - {{#equals @root.$config.client.name 'legacy/node'}} - request: Interceptors; - response: Interceptors; - {{/equals}} - {{#equals @root.$config.client.name 'legacy/xhr'}} - request: Interceptors; - response: Interceptors; - {{/equals}} - }; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: '{{{server}}}', - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '{{{version}}}', - WITH_CREDENTIALS: false, - interceptors: { - {{#notEquals @root.$config.client.name 'legacy/angular'}} - request: new Interceptors(), - {{/notEquals}} - response: new Interceptors(), - }, -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getHeaders.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getHeaders.hbs deleted file mode 100644 index 25ef917bf..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getHeaders.hbs +++ /dev/null @@ -1,48 +0,0 @@ -export const getHeaders = (config: OpenAPIConfig, options: ApiRequestOptions): Observable => { - return forkJoin({ - // @ts-ignore - token: resolve(options, config.TOKEN), - // @ts-ignore - username: resolve(options, config.USERNAME), - // @ts-ignore - password: resolve(options, config.PASSWORD), - // @ts-ignore - additionalHeaders: resolve(options, config.HEADERS), - }).pipe( - map(({ token, username, password, additionalHeaders }) => { - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new HttpHeaders(headers); - }), - ); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getRequestBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getRequestBody.hbs deleted file mode 100644 index 2bb961454..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getRequestBody.hbs +++ /dev/null @@ -1,12 +0,0 @@ -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseBody.hbs deleted file mode 100644 index 73653784c..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseBody.hbs +++ /dev/null @@ -1,6 +0,0 @@ -export const getResponseBody = (response: HttpResponse): T | undefined => { - if (response.status !== 204 && response.body !== null) { - return response.body; - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseHeader.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseHeader.hbs deleted file mode 100644 index fcb7ba830..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -export const getResponseHeader = (response: HttpResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const value = response.headers.get(responseHeader); - if (isString(value)) { - return value; - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/request.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/request.hbs deleted file mode 100644 index ff9727aa5..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/request.hbs +++ /dev/null @@ -1,114 +0,0 @@ -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import type { HttpResponse, HttpErrorResponse } from '@angular/common/http'; -import { forkJoin, of, throwError } from 'rxjs'; -import { catchError, map, switchMap } from 'rxjs/operators'; -import type { Observable } from 'rxjs'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>angular/getHeaders}} - - -{{>angular/getRequestBody}} - - -{{>angular/sendRequest}} - - -{{>angular/getResponseHeader}} - - -{{>angular/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param http The Angular HTTP client - * @param options The request options from the service - * @returns Observable - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, http: HttpClient, options: ApiRequestOptions): Observable => { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - - return getHeaders(config, options).pipe( - switchMap(headers => { - return sendRequest(config, options, http, url, body, formData, headers); - }), - switchMap(async response => { - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - return { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - } as ApiResult; - }), - catchError((error: HttpErrorResponse) => { - if (!error.status) { - return throwError(() => error); - } - return of({ - url, - ok: error.ok, - status: error.status, - statusText: error.statusText, - body: error.error ?? error.statusText, - } as ApiResult); - }), - map(result => { - catchErrorCodes(options, result); - return result.body as T; - }), - catchError((error: ApiError) => { - return throwError(() => error); - }), - ); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/sendRequest.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/sendRequest.hbs deleted file mode 100644 index d765a4341..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/angular/sendRequest.hbs +++ /dev/null @@ -1,16 +0,0 @@ -export const sendRequest = ( - config: OpenAPIConfig, - options: ApiRequestOptions, - http: HttpClient, - url: string, - body: unknown, - formData: FormData | undefined, - headers: HttpHeaders -): Observable> => { - return http.request(options.method, url, { - headers, - body: body ?? formData, - withCredentials: config.WITH_CREDENTIALS, - observe: 'response', - }); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getHeaders.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getHeaders.hbs deleted file mode 100644 index d5e5f0076..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getHeaders.hbs +++ /dev/null @@ -1,50 +0,0 @@ -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise> => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } else if (options.formData !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } - } - - return headers; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getRequestBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getRequestBody.hbs deleted file mode 100644 index 1699e7b68..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getRequestBody.hbs +++ /dev/null @@ -1,6 +0,0 @@ -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body) { - return options.body; - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseBody.hbs deleted file mode 100644 index 5878045d0..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseBody.hbs +++ /dev/null @@ -1,6 +0,0 @@ -export const getResponseBody = (response: AxiosResponse): unknown => { - if (response.status !== 204) { - return response.data; - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseHeader.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseHeader.hbs deleted file mode 100644 index f191da9f3..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -export const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers[responseHeader]; - if (isString(content)) { - return content; - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/request.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/request.hbs deleted file mode 100644 index ef3d6978d..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/request.hbs +++ /dev/null @@ -1,106 +0,0 @@ -import axios from 'axios'; -import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/isSuccess}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>axios/getHeaders}} - - -{{>axios/getRequestBody}} - - -{{>axios/sendRequest}} - - -{{>axios/getResponseHeader}} - - -{{>axios/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @param axiosClient The axios client instance to use - * @returns CancelablePromise<{{#ifServicesResponse 'response'}}ApiResult{{else}}T{{/ifServicesResponse}}> - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise<{{#ifServicesResponse 'response'}}ApiResult{{else}}T{{/ifServicesResponse}}> => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && isSuccess(response.status)) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve({{#ifServicesResponse 'body'}}result.body{{else}}result{{/ifServicesResponse}}); - } - } catch (error) { - reject(error); - } - }); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/sendRequest.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/sendRequest.hbs deleted file mode 100644 index 4c8046289..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/axios/sendRequest.hbs +++ /dev/null @@ -1,37 +0,0 @@ -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: unknown, - formData: FormData | undefined, - headers: Record, - onCancel: OnCancel, - axiosClient: AxiosInstance -): Promise> => { - const controller = new AbortController(); - - let requestConfig: AxiosRequestConfig = { - data: body ?? formData, - headers, - method: options.method, - signal: controller.signal, - url, - withCredentials: config.WITH_CREDENTIALS, - }; - - onCancel(() => controller.abort()); - - for (const fn of config.interceptors.request._fns) { - requestConfig = await fn(requestConfig); - } - - try { - return await axiosClient.request(requestConfig); - } catch (error) { - const axiosError = error as AxiosError; - if (axiosError.response) { - return axiosError.response; - } - throw error; - } -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getHeaders.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getHeaders.hbs deleted file mode 100644 index 5ad8e9cb5..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getHeaders.hbs +++ /dev/null @@ -1,46 +0,0 @@ -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getRequestBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getRequestBody.hbs deleted file mode 100644 index b3f7a4b1c..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getRequestBody.hbs +++ /dev/null @@ -1,12 +0,0 @@ -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseBody.hbs deleted file mode 100644 index 9d631ad37..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseBody.hbs +++ /dev/null @@ -1,22 +0,0 @@ -export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseHeader.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseHeader.hbs deleted file mode 100644 index cc415c0a7..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/request.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/request.hbs deleted file mode 100644 index ef6089387..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/request.hbs +++ /dev/null @@ -1,104 +0,0 @@ -{{#equals @root.$config.client.name 'legacy/node'}} -import fetch, { FormData, Headers } from 'node-fetch'; -import type { RequestInit, Response } from 'node-fetch'; - -{{/equals}} -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>fetch/getHeaders}} - - -{{>fetch/getRequestBody}} - - -{{>fetch/sendRequest}} - - -{{>fetch/getResponseHeader}} - - -{{>fetch/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise<{{#ifServicesResponse 'response'}}ApiResult{{else}}T{{/ifServicesResponse}}> - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise<{{#ifServicesResponse 'response'}}ApiResult{{else}}T{{/ifServicesResponse}}> => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && response.ok) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve({{#ifServicesResponse 'body'}}result.body{{else}}result{{/ifServicesResponse}}); - } - } catch (error) { - reject(error); - } - }); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/sendRequest.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/sendRequest.hbs deleted file mode 100644 index eb6fcc60a..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/fetch/sendRequest.hbs +++ /dev/null @@ -1,32 +0,0 @@ -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - {{#equals @root.$config.client.name 'legacy/fetch'}} - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - {{/equals}} - - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/base64.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/base64.hbs deleted file mode 100644 index 5b7e43aed..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/base64.hbs +++ /dev/null @@ -1,8 +0,0 @@ -export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/catchErrorCodes.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/catchErrorCodes.hbs deleted file mode 100644 index f686bc096..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/catchErrorCodes.hbs +++ /dev/null @@ -1,68 +0,0 @@ - - -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getFormData.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getFormData.hbs deleted file mode 100644 index fce141194..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getFormData.hbs +++ /dev/null @@ -1,26 +0,0 @@ -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getQueryString.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getQueryString.hbs deleted file mode 100644 index 4faca0674..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getQueryString.hbs +++ /dev/null @@ -1,27 +0,0 @@ -export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getUrl.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getUrl.hbs deleted file mode 100644 index ec617ac18..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/getUrl.hbs +++ /dev/null @@ -1,15 +0,0 @@ -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isBlob.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isBlob.hbs deleted file mode 100644 index 83dd5b892..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isBlob.hbs +++ /dev/null @@ -1,3 +0,0 @@ -export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isFormData.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isFormData.hbs deleted file mode 100644 index 3c8649575..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isFormData.hbs +++ /dev/null @@ -1,3 +0,0 @@ -export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isString.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isString.hbs deleted file mode 100644 index 1b70a8a7f..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isString.hbs +++ /dev/null @@ -1,3 +0,0 @@ -export const isString = (value: unknown): value is string => { - return typeof value === 'string'; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isStringWithValue.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isStringWithValue.hbs deleted file mode 100644 index 6e69d331c..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isStringWithValue.hbs +++ /dev/null @@ -1,3 +0,0 @@ -export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isSuccess.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isSuccess.hbs deleted file mode 100644 index 5749d56e4..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/isSuccess.hbs +++ /dev/null @@ -1,3 +0,0 @@ -export const isSuccess = (status: number): boolean => { - return status >= 200 && status < 300; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/resolve.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/resolve.hbs deleted file mode 100644 index d38f28121..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/functions/resolve.hbs +++ /dev/null @@ -1,8 +0,0 @@ -type Resolver = (options: ApiRequestOptions) => Promise; - -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/request.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/request.hbs deleted file mode 100644 index 84ca4fa42..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/request.hbs +++ /dev/null @@ -1,5 +0,0 @@ -{{~#equals @root.$config.client.name 'legacy/angular'}}{{>angular/request}}{{/equals~}} -{{~#equals @root.$config.client.name 'legacy/axios'}}{{>axios/request}}{{/equals~}} -{{~#equals @root.$config.client.name 'legacy/fetch'}}{{>fetch/request}}{{/equals~}} -{{~#equals @root.$config.client.name 'legacy/node'}}{{>fetch/request}}{{/equals~}} -{{~#equals @root.$config.client.name 'legacy/xhr'}}{{>xhr/request}}{{/equals~}} diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getHeaders.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getHeaders.hbs deleted file mode 100644 index 5ad8e9cb5..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getHeaders.hbs +++ /dev/null @@ -1,46 +0,0 @@ -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - // @ts-ignore - resolve(options, config.TOKEN), - // @ts-ignore - resolve(options, config.USERNAME), - // @ts-ignore - resolve(options, config.PASSWORD), - // @ts-ignore - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getRequestBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getRequestBody.hbs deleted file mode 100644 index b3f7a4b1c..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getRequestBody.hbs +++ /dev/null @@ -1,12 +0,0 @@ -export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseBody.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseBody.hbs deleted file mode 100644 index 0bd9d354e..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseBody.hbs +++ /dev/null @@ -1,17 +0,0 @@ -export const getResponseBody = (xhr: XMLHttpRequest): unknown => { - if (xhr.status !== 204) { - try { - const contentType = xhr.getResponseHeader('Content-Type'); - if (contentType) { - if (contentType.includes('application/json') || contentType.includes('+json')) { - return JSON.parse(xhr.responseText); - } else { - return xhr.responseText; - } - } - } catch (error) { - console.error(error); - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseHeader.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseHeader.hbs deleted file mode 100644 index 2ebc80e7a..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -export const getResponseHeader = (xhr: XMLHttpRequest, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = xhr.getResponseHeader(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/request.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/request.hbs deleted file mode 100644 index cc9a3f785..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/request.hbs +++ /dev/null @@ -1,102 +0,0 @@ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/isSuccess}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>fetch/getHeaders}} - - -{{>xhr/getRequestBody}} - - -{{>xhr/sendRequest}} - - -{{>xhr/getResponseHeader}} - - -{{>xhr/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise<{{#ifServicesResponse 'response'}}ApiResult{{else}}T{{/ifServicesResponse}}> - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise<{{#ifServicesResponse 'response'}}ApiResult{{else}}T{{/ifServicesResponse}}> => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - let transformedBody = responseBody; - if (options.responseTransformer && isSuccess(response.status)) { - transformedBody = await options.responseTransformer(responseBody) - } - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? transformedBody, - }; - - catchErrorCodes(options, result); - - resolve({{#ifServicesResponse 'body'}}result.body{{else}}result{{/ifServicesResponse}}); - } - } catch (error) { - reject(error); - } - }); -}; diff --git a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/sendRequest.hbs b/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/sendRequest.hbs deleted file mode 100644 index ca92799f5..000000000 --- a/packages/openapi-ts/src/legacy/handlebars/templates/core/xhr/sendRequest.hbs +++ /dev/null @@ -1,31 +0,0 @@ -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - let xhr = new XMLHttpRequest(); - xhr.open(options.method, url, true); - xhr.withCredentials = config.WITH_CREDENTIALS; - - headers.forEach((value, key) => { - xhr.setRequestHeader(key, value); - }); - - return new Promise(async (resolve, reject) => { - xhr.onload = () => resolve(xhr); - xhr.onabort = () => reject(new Error('Request aborted')); - xhr.onerror = () => reject(new Error('Network error')); - - for (const fn of config.interceptors.request._fns) { - xhr = await fn(xhr); - } - - xhr.send(body ?? formData); - - onCancel(() => xhr.abort()); - }); -}; diff --git a/packages/openapi-ts/src/openApi/__tests__/index.test.ts b/packages/openapi-ts/src/openApi/__tests__/index.test.ts index 8ed46431f..9629b2b9d 100644 --- a/packages/openapi-ts/src/openApi/__tests__/index.test.ts +++ b/packages/openapi-ts/src/openApi/__tests__/index.test.ts @@ -4,11 +4,9 @@ import type { OpenApiV3_0_X } from '~/openApi/3.0.x'; import { parseV3_0_X } from '~/openApi/3.0.x'; import type { OpenApiV3_1_X } from '~/openApi/3.1.x'; import { parseV3_1_X } from '~/openApi/3.1.x'; -import * as parseV2 from '~/openApi/v2'; -import * as parseV3 from '~/openApi/v3'; import type { Config } from '../../types/config'; -import { type OpenApi, parseLegacy, parseOpenApiSpec } from '..'; +import { parseOpenApiSpec } from '..'; vi.mock('../3.0.x', () => ({ parseV3_0_X: vi.fn(), @@ -27,86 +25,10 @@ vi.mock('../../utils/config', () => { }; return { getConfig: () => config, - isLegacyClient: vi.fn().mockReturnValue(true), }; }); -describe('parse', () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('uses v2 parser', () => { - const spy = vi.spyOn(parseV2, 'parse'); - - const spec: OpenApi = { - info: { - title: 'dummy', - version: '1.0', - }, - paths: {}, - swagger: '2', - }; - parseLegacy({ openApi: spec }); - expect(spy).toHaveBeenCalledWith(spec); - - const spec2: OpenApi = { - info: { - title: 'dummy', - version: '1.0', - }, - paths: {}, - swagger: '2.0', - }; - parseLegacy({ openApi: spec2 }); - expect(spy).toHaveBeenCalledWith(spec2); - }); - - it('uses v3 parser', () => { - const spy = vi.spyOn(parseV3, 'parse'); - - const spec: OpenApi = { - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3', - paths: {}, - }; - parseLegacy({ openApi: spec }); - expect(spy).toHaveBeenCalledWith(spec); - - const spec2: OpenApi = { - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3.0', - paths: {}, - }; - parseLegacy({ openApi: spec2 }); - expect(spy).toHaveBeenCalledWith(spec2); - - const spec3: OpenApi = { - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3.1.0', - paths: {}, - }; - parseLegacy({ openApi: spec3 }); - expect(spy).toHaveBeenCalledWith(spec3); - }); - - it('throws on unknown version', () => { - expect(() => parseLegacy({ openApi: { foo: 'bar' } })).toThrow( - `Unsupported OpenAPI specification: ${JSON.stringify({ foo: 'bar' }, null, 2)}`, - ); - }); -}); - -describe('experimentalParser', () => { +describe('OpenAPI parser', () => { afterEach(() => { vi.restoreAllMocks(); }); diff --git a/packages/openapi-ts/src/openApi/common/interfaces/Dictionary.ts b/packages/openapi-ts/src/openApi/common/interfaces/Dictionary.ts deleted file mode 100644 index 829f225db..000000000 --- a/packages/openapi-ts/src/openApi/common/interfaces/Dictionary.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface Dictionary { - [key: string]: T; -} diff --git a/packages/openapi-ts/src/openApi/common/interfaces/OpenApi.ts b/packages/openapi-ts/src/openApi/common/interfaces/OpenApi.ts deleted file mode 100644 index 656e638d4..000000000 --- a/packages/openapi-ts/src/openApi/common/interfaces/OpenApi.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { OpenApi as OpenApiV2 } from '~/openApi/v2/interfaces/OpenApi'; -import type { OpenApi as OpenApiV3 } from '~/openApi/v3/interfaces/OpenApi'; - -export type OpenApi = OpenApiV2 | OpenApiV3; diff --git a/packages/openapi-ts/src/openApi/common/interfaces/Type.ts b/packages/openapi-ts/src/openApi/common/interfaces/Type.ts deleted file mode 100644 index 1feeb5dd6..000000000 --- a/packages/openapi-ts/src/openApi/common/interfaces/Type.ts +++ /dev/null @@ -1,8 +0,0 @@ -export interface Type { - $refs: string[]; - base: string; - imports: string[]; - isNullable: boolean; - template: string | null; - type: string; -} diff --git a/packages/openapi-ts/src/openApi/common/interfaces/WithEnumExtension.ts b/packages/openapi-ts/src/openApi/common/interfaces/WithEnumExtension.ts deleted file mode 100644 index a714e025d..000000000 --- a/packages/openapi-ts/src/openApi/common/interfaces/WithEnumExtension.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface WithEnumExtension { - 'x-enum-descriptions'?: ReadonlyArray; - 'x-enum-varnames'?: ReadonlyArray; - // NSwag uses x-enumNames for custom enum names - 'x-enumNames'?: ReadonlyArray; -} diff --git a/packages/openapi-ts/src/openApi/common/interfaces/client.ts b/packages/openapi-ts/src/openApi/common/interfaces/client.ts deleted file mode 100644 index b11f7a3c2..000000000 --- a/packages/openapi-ts/src/openApi/common/interfaces/client.ts +++ /dev/null @@ -1,171 +0,0 @@ -import type { OpenApiParameter } from '~/openApi/v3/interfaces/OpenApiParameter'; - -import type { Config } from '../../../types/config'; - -export interface ModelComposition - extends Pick { - export: Extract; -} - -export interface Enum { - customDescription?: string; - customName?: string; - description?: string; - value: string | number; -} - -export interface OperationParameter extends Model { - in: 'body' | 'cookie' | 'formData' | 'header' | 'path' | 'query'; - mediaType: string | null; - prop: string; -} - -export interface OperationParameters extends Pick { - parameters: OperationParameter[]; - parametersBody: OperationParameter | null; - parametersCookie: OperationParameter[]; - parametersForm: OperationParameter[]; - parametersHeader: OperationParameter[]; - parametersPath: OperationParameter[]; - parametersQuery: OperationParameter[]; -} - -export interface OperationResponse extends Model { - code: number | 'default' | '1XX' | '2XX' | '3XX' | '4XX' | '5XX'; - in: 'header' | 'response'; - responseTypes: Array<'error' | 'success'>; -} - -export type Method = - | 'CONNECT' - | 'DELETE' - | 'GET' - | 'HEAD' - | 'OPTIONS' - | 'PATCH' - | 'POST' - | 'PUT' - | 'TRACE'; - -export interface Operation extends OperationParameters { - deprecated: boolean; - description: string | null; - /** - * The operationId from OpenAPI specification. - */ - id: string | null; - method: Method; - name: string; - path: string; - responseHeader: string | null; - /** - * All operation responses defined in OpenAPI specification. - * Sorted by status code. - */ - responses: OperationResponse[]; - summary: string | null; - tags: string[] | null; -} - -export interface Schema { - default?: unknown; - exclusiveMaximum?: boolean; - exclusiveMinimum?: boolean; - format?: - | 'binary' - | 'boolean' - | 'byte' - | 'date-time' - | 'date' - | 'double' - | 'float' - | 'int32' - | 'int64' - | 'password' - | 'string'; - isDefinition: boolean; - isNullable: boolean; - isReadOnly: boolean; - isRequired: boolean; - maxItems?: number; - maxLength?: number; - maxProperties?: number; - maximum?: number; - minItems?: number; - minLength?: number; - minProperties?: number; - minimum?: number; - multipleOf?: number; - pattern?: string; - uniqueItems?: boolean; -} - -export interface ModelMeta { - /** - * Ref to the type in OpenAPI specification. - */ - $ref: string; - /** - * Name passed to the initial `getModel()` call. - */ - name: string; -} - -export interface Model extends Schema { - /** - * **Experimental.** Contains list of original refs so they can be used - * to access the schema from anywhere instead of relying on string name. - * This allows us to do things like detect type of ref. - */ - $refs: string[]; - base: string; - deprecated?: boolean; - description: string | null; - enum: Enum[]; - enums: Model[]; - export: - | 'all-of' - | 'any-of' - | 'array' - | 'const' - | 'dictionary' - | 'enum' - | 'generic' - | 'interface' - | 'one-of' - | 'reference'; - imports: string[]; - in: - | OperationParameter['in'] - | OpenApiParameter['in'] - | OperationResponse['in'] - | ''; - link: Model | Model[] | null; - meta?: ModelMeta; - /** - * @deprecated use `meta.name` instead - */ - name: string; - properties: Model[]; - template: string | null; - type: string; -} - -export interface Client { - /** - * Configuration for parsing and generating the output. This - * is a mix of user-provided and default values. - */ - config: Config; - models: Model[]; - operations: Operation[]; - server: string; - /** - * Map of generated types where type names are keys. This is used to track - * uniquely generated types as we may want to deduplicate if there are - * multiple definitions with the same name but different value, or if we - * want to transform names. - */ - types: Record; - version: string; -} diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/getPattern.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/getPattern.test.ts deleted file mode 100644 index 0116fb07a..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/getPattern.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { getPattern } from '../getPattern'; - -describe('getPattern', () => { - it.each([ - { expected: undefined, pattern: undefined }, - { expected: '', pattern: '' }, - { expected: '^[a-zA-Z]', pattern: '^[a-zA-Z]' }, - { expected: '^\\\\w+$', pattern: '^\\w+$' }, - { - expected: '^\\\\d{3}-\\\\d{2}-\\\\d{4}$', - pattern: '^\\d{3}-\\d{2}-\\d{4}$', - }, - { expected: '\\\\', pattern: '\\' }, - { expected: '\\\\/', pattern: '\\/' }, - { expected: '\\\\/\\\\/', pattern: '\\/\\/' }, - { expected: "\\'", pattern: "'" }, - ])('getPattern($pattern) -> $expected', ({ expected, pattern }) => { - expect(getPattern(pattern)).toEqual(expected); - }); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/getRef.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/getRef.test.ts deleted file mode 100644 index 413d03f68..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/getRef.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { getRef } from '../getRef'; - -describe('getRef (v2)', () => { - it('should produce correct result', () => { - expect( - getRef( - { - basePath: '/api', - definitions: { - Example: { - description: 'This is an Example model ', - type: 'integer', - }, - }, - host: 'localhost:8080', - info: { - title: 'dummy', - version: '1.0', - }, - paths: {}, - schemes: ['http', 'https'], - swagger: '2.0', - }, - { - $ref: '#/definitions/Example', - }, - ), - ).toEqual({ - description: 'This is an Example model ', - type: 'integer', - }); - }); -}); - -describe('getRef (v3)', () => { - it('should produce correct result', () => { - expect( - getRef( - { - components: { - schemas: { - Example: { - description: 'This is an Example model ', - type: 'integer', - }, - }, - }, - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3.0', - paths: {}, - servers: [ - { - url: 'https://localhost:8080/api', - }, - ], - }, - { - $ref: '#/components/schemas/Example', - }, - ), - ).toEqual({ - description: 'This is an Example model ', - type: 'integer', - }); - }); - - it('should produce correct result for encoded ref path', () => { - expect( - getRef( - { - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3.0', - paths: { - '/api/user/{id}': { - description: 'This is an Example path', - }, - }, - }, - { - $ref: '#/paths/~1api~1user~1%7Bid%7D', - }, - ), - ).toEqual({ - description: 'This is an Example path', - }); - }); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/operation.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/operation.test.ts deleted file mode 100644 index ea2b43f0c..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/operation.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { parseResponseStatusCode } from '../operation'; - -describe('parseResponseStatusCode', () => { - it.each([ - { expected: null, input: '' }, - { expected: 'default', input: 'default' }, - { expected: 200, input: '200' }, - { expected: 300, input: '300' }, - { expected: 400, input: '400' }, - { expected: '4XX', input: '4XX' }, - { expected: null, input: 'abc' }, - { expected: null, input: '-100' }, - ])('parseResponseStatusCode($input) -> $expected', ({ expected, input }) => { - expect(parseResponseStatusCode(input)).toBe(expected); - }); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/sanitize.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/sanitize.test.ts index 4be6c3598..6d656b407 100644 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/sanitize.test.ts +++ b/packages/openapi-ts/src/openApi/common/parser/__tests__/sanitize.test.ts @@ -1,25 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { - ensureValidTypeScriptJavaScriptIdentifier, - sanitizeNamespaceIdentifier, - sanitizeOperationParameterName, -} from '../sanitize'; - -describe('sanitizeOperationParameterName', () => { - it.each([ - { expected: 'abc', input: 'abc' }, - { expected: 'æbc', input: 'æbc' }, - { expected: 'æb-c', input: 'æb.c' }, - { expected: 'æb-c', input: '1æb.c' }, - { expected: 'unknownArray', input: 'unknown[]' }, - ])( - 'sanitizeOperationParameterName($input) -> $expected', - ({ expected, input }) => { - expect(sanitizeOperationParameterName(input)).toEqual(expected); - }, - ); -}); +import { sanitizeNamespaceIdentifier } from '../sanitize'; describe('sanitizeNamespaceIdentifier', () => { it.each([ @@ -35,20 +16,3 @@ describe('sanitizeNamespaceIdentifier', () => { }, ); }); - -describe('ensureValidTypeScriptJavaScriptIdentifier', () => { - it.each([ - { expected: 'abc', input: 'abc' }, - { expected: 'æbc', input: 'æbc' }, - { expected: 'æb_c', input: 'æb.c' }, - { expected: '_1æb_c', input: '1æb.c' }, - { expected: '_400', input: '400' }, - ])( - 'ensureValidTypeScriptJavaScriptIdentifier($input) -> $expected', - ({ expected, input }) => { - expect(ensureValidTypeScriptJavaScriptIdentifier(input)).toEqual( - expected, - ); - }, - ); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/service.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/service.test.ts deleted file mode 100644 index 2037d7e7b..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/service.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { getServiceVersion } from '../service'; - -describe('getServiceVersion', () => { - it.each([ - { expected: '1.0', input: '1.0' }, - { expected: '1.2', input: 'v1.2' }, - { expected: '2.4', input: 'V2.4' }, - ])('should get $expected when version is $input', ({ expected, input }) => { - expect(getServiceVersion(input)).toEqual(expected); - }); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/sort.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/sort.test.ts deleted file mode 100644 index 0fe94d472..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/sort.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { toSortedByRequired } from '../sort'; - -describe('sort', () => { - it.each([ - { - expected: [ - { id: 'test2', isRequired: true }, - { id: 'test3', isRequired: true }, - { id: 'test', isRequired: false }, - ], - input: [ - { id: 'test', isRequired: false }, - { id: 'test2', isRequired: true }, - { id: 'test3', isRequired: true }, - ], - }, - { - expected: [ - { id: 'test', isRequired: false }, - { id: 'test2', isRequired: false }, - { default: 'something', id: 'test3', isRequired: true }, - ], - input: [ - { id: 'test', isRequired: false }, - { id: 'test2', isRequired: false }, - { default: 'something', id: 'test3', isRequired: true }, - ], - }, - ])( - 'should sort $input by required to produce $expected', - ({ expected, input }) => { - expect(toSortedByRequired(input)).toEqual(expected); - }, - ); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/stripNamespace.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/stripNamespace.test.ts deleted file mode 100644 index 382b5e9e7..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/stripNamespace.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { stripNamespace } from '../stripNamespace'; - -describe('stripNamespace', () => { - it.each([ - { expected: 'Item', input: '#/definitions/Item' }, - { expected: 'Item', input: '#/parameters/Item' }, - { expected: 'Item', input: '#/responses/Item' }, - { expected: 'Item', input: '#/securityDefinitions/Item' }, - { expected: 'Item', input: '#/components/schemas/Item' }, - { expected: 'Item', input: '#/components/responses/Item' }, - { expected: 'Item', input: '#/components/parameters/Item' }, - { expected: 'Item', input: '#/components/examples/Item' }, - { expected: 'Item', input: '#/components/requestBodies/Item' }, - { expected: 'Item', input: '#/components/headers/Item' }, - { expected: 'Item', input: '#/components/securitySchemes/Item' }, - { expected: 'Item', input: '#/components/links/Item' }, - { expected: 'Item', input: '#/components/callbacks/Item' }, - ])('stripNamespace($input) -> $expected', ({ expected, input }) => { - expect(stripNamespace(input)).toEqual(expected); - }); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/__tests__/type.test.ts b/packages/openapi-ts/src/openApi/common/parser/__tests__/type.test.ts deleted file mode 100644 index 9e66203f2..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/__tests__/type.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import type { Config } from '../../../../types/config'; -import { getMappedType, getType } from '../type'; - -vi.mock('../../../../utils/config', () => { - const config: Partial = { - plugins: { - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - }, - }; - return { - getConfig: () => config, - isLegacyClient: vi.fn().mockReturnValue(true), - }; -}); - -describe('getMappedType', () => { - it.each([ - { expected: 'binary', type: 'file' }, - { expected: 'boolean', type: 'boolean' }, - { expected: 'null', type: 'null' }, - { expected: 'number', type: 'byte' }, - { expected: 'number', type: 'double' }, - { expected: 'number', type: 'float' }, - { expected: 'number', type: 'int' }, - { expected: 'number', type: 'integer' }, - { expected: 'number', type: 'long' }, - { expected: 'number', type: 'number' }, - { expected: 'number', type: 'short' }, - { expected: 'string', type: 'char' }, - { expected: 'string', type: 'date-time' }, - { expected: 'string', type: 'date' }, - { expected: 'string', type: 'password' }, - { expected: 'string', type: 'string' }, - { expected: 'unknown', type: 'any' }, - { expected: 'unknown', type: 'object' }, - { expected: 'unknown', type: 'unknown' }, - { expected: 'unknown[]', type: 'array' }, - { expected: 'void', type: 'void' }, - { expected: undefined, type: '' }, - ])('should map type $type to $expected', ({ expected, type }) => { - expect(getMappedType(type)).toEqual(expected); - }); -}); - -describe('getType', () => { - it('should convert int', () => { - const type = getType({ type: 'int' }); - expect(type.type).toEqual('number'); - expect(type.base).toEqual('number'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual([]); - expect(type.isNullable).toEqual(false); - }); - - it('should convert string', () => { - const type = getType({ type: 'string' }); - expect(type.type).toEqual('string'); - expect(type.base).toEqual('string'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual([]); - expect(type.isNullable).toEqual(false); - }); - - it('should convert string array', () => { - const type = getType({ type: 'array[string]' }); - expect(type.type).toEqual('string[]'); - expect(type.base).toEqual('string'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual([]); - expect(type.isNullable).toEqual(false); - }); - - it('should convert template with primary', () => { - const type = getType({ type: '#/components/schemas/Link[string]' }); - expect(type.type).toEqual('Link'); - expect(type.base).toEqual('Link'); - expect(type.template).toEqual('string'); - expect(type.imports).toEqual(['Link']); - expect(type.isNullable).toEqual(false); - }); - - it('should convert template with model', () => { - const type = getType({ type: '#/components/schemas/Link[Model]' }); - expect(type.type).toEqual('Link'); - expect(type.base).toEqual('Link'); - expect(type.template).toEqual('Model'); - expect(type.imports).toEqual(['Link', 'Model']); - expect(type.isNullable).toEqual(false); - }); - - it('should have double imports', () => { - const type = getType({ type: '#/components/schemas/Link[Link]' }); - expect(type.type).toEqual('Link'); - expect(type.base).toEqual('Link'); - expect(type.template).toEqual('Link'); - expect(type.imports).toEqual(['Link', 'Link']); - expect(type.isNullable).toEqual(false); - }); - - it('should support dot', () => { - const type = getType({ type: '#/components/schemas/model.000' }); - expect(type.type).toEqual('model_000'); - expect(type.base).toEqual('model_000'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual(['model_000']); - expect(type.isNullable).toEqual(false); - }); - - it('should support dashes', () => { - const type = getType({ type: '#/components/schemas/some_special-schema' }); - expect(type.type).toEqual('some_special_schema'); - expect(type.base).toEqual('some_special_schema'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual(['some_special_schema']); - expect(type.isNullable).toEqual(false); - }); - - it('should support dollar sign', () => { - const type = getType({ type: '#/components/schemas/$some+special+schema' }); - expect(type.type).toEqual('$some_special_schema'); - expect(type.base).toEqual('$some_special_schema'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual(['$some_special_schema']); - expect(type.isNullable).toEqual(false); - }); - - it('should support multiple base types', () => { - const type = getType({ type: ['string', 'int'] }); - expect(type.type).toEqual('string | number'); - expect(type.base).toEqual('string | number'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual([]); - expect(type.isNullable).toEqual(false); - }); - - it('should support multiple nullable types', () => { - const type = getType({ type: ['string', 'null'] }); - expect(type.type).toEqual('string'); - expect(type.base).toEqual('string'); - expect(type.template).toEqual(null); - expect(type.imports).toEqual([]); - expect(type.isNullable).toEqual(true); - }); -}); diff --git a/packages/openapi-ts/src/openApi/common/parser/getDefault.ts b/packages/openapi-ts/src/openApi/common/parser/getDefault.ts deleted file mode 100644 index 551f5f953..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/getDefault.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { OpenApiParameter } from '~/openApi/v2/interfaces/OpenApiParameter'; -import type { OpenApiSchema } from '~/openApi/v3/interfaces/OpenApiSchema'; -import { getDefinitionTypes } from '~/openApi/v3/parser/inferType'; - -import type { Model } from '../../common/interfaces/client'; -import type { OperationParameter } from '../interfaces/client'; - -export const getDefault = ( - definition: OpenApiSchema | OpenApiParameter, - model?: Model | OperationParameter, -): unknown | undefined => { - if (definition.default === undefined || definition.default === null) { - return definition.default; - } - - const definitionTypes = getDefinitionTypes(definition); - - const type = - definitionTypes.find((type) => type !== 'null') || - typeof definition.default; - - switch (type) { - case 'int': - case 'integer': - case 'number': - if ( - model?.export === 'enum' && - model.enum?.[definition.default as number] - ) { - const { value } = model.enum[definition.default as number]!; - return value; - } - return definition.default; - case 'array': - case 'boolean': - case 'object': - case 'string': - return definition.default; - default: - return; - } -}; diff --git a/packages/openapi-ts/src/openApi/common/parser/getEnums.ts b/packages/openapi-ts/src/openApi/common/parser/getEnums.ts deleted file mode 100644 index 81767d450..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/getEnums.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { unique } from '~/utils/unique'; - -import type { Enum } from '../interfaces/client'; -import type { WithEnumExtension } from '../interfaces/WithEnumExtension'; - -export const getEnums = ( - definition: WithEnumExtension, - values?: ReadonlyArray, -): Enum[] => { - if (!Array.isArray(values)) { - return []; - } - - const descriptions = (definition['x-enum-descriptions'] ?? []).filter( - (value) => typeof value === 'string', - ); - const names = ( - definition['x-enum-varnames'] ?? - definition['x-enumNames'] ?? - [] - ).filter((value) => typeof value === 'string'); - - return values - .filter(unique) - .filter((value) => typeof value === 'number' || typeof value === 'string') - .map((value, index) => ({ - customDescription: descriptions[index], - customName: names[index], - description: undefined, - value, - })); -}; diff --git a/packages/openapi-ts/src/openApi/common/parser/getPattern.ts b/packages/openapi-ts/src/openApi/common/parser/getPattern.ts deleted file mode 100644 index 3cdc85320..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/getPattern.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * The spec generates a pattern like this '^\d{3}-\d{2}-\d{4}$' - * However, to use it in HTML or inside new RegExp() we need to - * escape the pattern to become: '^\\d{3}-\\d{2}-\\d{4}$' in order - * to make it a valid regexp string. - * - * Also, escape single quote characters, because the output uses single quotes for strings - * - * @param pattern - */ -export const getPattern = (pattern?: string): string | undefined => - pattern?.replace(/\\/g, '\\\\').replace(/'/g, "\\'"); diff --git a/packages/openapi-ts/src/openApi/common/parser/getRef.ts b/packages/openapi-ts/src/openApi/common/parser/getRef.ts deleted file mode 100644 index 98cec868c..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/getRef.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { OpenApiReference as OpenApiReferenceV2 } from '~/openApi/v2/interfaces/OpenApiReference'; -import type { OpenApiReference as OpenApiReferenceV3 } from '~/openApi/v3/interfaces/OpenApiReference'; - -import type { OpenApi } from '../interfaces/OpenApi'; - -const ESCAPED_REF_SLASH = /~1/g; -const ESCAPED_REF_TILDE = /~0/g; - -export function getRef( - openApi: OpenApi, - item: T & (OpenApiReferenceV2 | OpenApiReferenceV3), -): T { - if (item.$ref) { - // Fetch the paths to the definitions, this converts: - // "#/components/schemas/Form" to ["components", "schemas", "Form"] - const paths = item.$ref.replace(/^#/g, '').split('/').filter(Boolean); - - // Try to find the reference by walking down the path, - // if we cannot find it, then we throw an error. - let result = openApi; - paths.forEach((path) => { - const decodedPath = decodeURIComponent( - path.replace(ESCAPED_REF_SLASH, '/').replace(ESCAPED_REF_TILDE, '~'), - ); - if (result.hasOwnProperty(decodedPath)) { - // @ts-expect-error - result = result[decodedPath]; - } else { - throw new Error(`Could not find reference: "${item.$ref}"`); - } - }); - return result as T; - } - return item as T; -} diff --git a/packages/openapi-ts/src/openApi/common/parser/operation.ts b/packages/openapi-ts/src/openApi/common/parser/operation.ts deleted file mode 100644 index c4319a8c2..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/operation.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { getConfig, isLegacyClient } from '~/utils/config'; -import { stringCase } from '~/utils/stringCase'; -import { transformTypeKeyName } from '~/utils/type'; - -import type { Config } from '../../../types/config'; -import type { - OperationParameter, - OperationResponse, -} from '../interfaces/client'; -import { sanitizeNamespaceIdentifier } from './sanitize'; - -export const getOperationResponseHeader = ( - operationResponses: OperationResponse[], -): string | null => { - const header = operationResponses.find( - (operationResponses) => operationResponses.in === 'header', - ); - if (header) { - return header.name; - } - return null; -}; - -/** - * Does this operation have at least one required parameter? - * @returns boolean - */ -export const isOperationParameterRequired = ( - parameters: OperationParameter[], -) => { - const isRequired = parameters.some((parameter) => parameter.isRequired); - return isRequired; -}; - -/** - * Attempts to parse response status code from string into number. - * @param value string status code from OpenAPI definition - * @returns Parsed status code or null if invalid value - */ -export const parseResponseStatusCode = ( - value: string, -): OperationResponse['code'] | null => { - if (value === 'default') { - return 'default'; - } - - if (value === '1XX') { - return '1XX'; - } - - if (value === '2XX') { - return '2XX'; - } - - if (value === '3XX') { - return '3XX'; - } - - if (value === '4XX') { - return '4XX'; - } - - if (value === '5XX') { - return '5XX'; - } - - if (/\d{3}/g.test(value)) { - const code = Number.parseInt(value, 10); - if (code >= 100 && code < 600) { - return code; - } - } - - return null; -}; - -export const sorterByResponseStatusCode = ( - a: OperationResponse, - b: OperationResponse, -) => { - if (a.code > b.code) { - return 1; - } - - if (a.code < b.code) { - return -1; - } - - return 0; -}; - -const isErrorStatusCode = (code: OperationResponse['code']) => - code === '3XX' || - code === '4XX' || - code === '5XX' || - (typeof code === 'number' && code >= 300); - -const isSuccessStatusCode = (code: OperationResponse['code']) => - code === '2XX' || (typeof code === 'number' && code >= 200 && code < 300); - -/** - * Detects whether default response is meant to be used - * for error or success response. - */ -const inferDefaultResponseTypes = ( - response: OperationResponse, - responses: OperationResponse[], -) => { - let types: Array<'error' | 'success'> = []; - - const addResponseType = (type: (typeof types)[number]) => { - if (!types.includes(type)) { - types = [...types, type]; - } - }; - - const hasSuccessResponse = responses.some(({ code }) => - isSuccessStatusCode(code), - ); - if (!hasSuccessResponse) { - addResponseType('success'); - } - - const description = (response.description ?? '').toLocaleLowerCase(); - const $refs = response.$refs.join('|').toLocaleLowerCase(); - - // must be in lowercase - const errorKeywords = ['error', 'problem']; - const successKeywords = ['success']; - - if ( - successKeywords.some( - (keyword) => description.includes(keyword) || $refs.includes(keyword), - ) - ) { - addResponseType('success'); - } - - if ( - errorKeywords.some( - (keyword) => description.includes(keyword) || $refs.includes(keyword), - ) - ) { - addResponseType('error'); - } - - if (!types.length) { - addResponseType('error'); - } - - return types; -}; - -export const operationFilterFn = ({ - config, - operationKey, -}: { - config: Config; - operationKey: string; -}): boolean => { - const regexp = config.plugins['@hey-api/sdk']?.config.filter - ? new RegExp(config.plugins['@hey-api/sdk']?.config.filter) - : undefined; - return !regexp || regexp.test(operationKey); -}; - -/** - * Convert the input value to a correct operation (method) class name. - * This will use the operation ID - if available - and otherwise fallback - * on a generated name from the URL - */ -export const operationNameFn = ({ - config, - method, - operationId, - path, -}: { - config: Config; - method: string; - operationId: string | undefined; - path: string; -}): string => { - if (config.plugins['@hey-api/sdk']?.config.operationId && operationId) { - return stringCase({ - case: 'camelCase', - value: sanitizeNamespaceIdentifier(operationId), - }); - } - - let urlWithoutPlaceholders = path; - - // legacy clients ignore the "api-version" param since we do not want to - // add it as the first/default parameter for each of the service calls - if (isLegacyClient(config)) { - urlWithoutPlaceholders = urlWithoutPlaceholders.replace( - /[^/]*?{api-version}.*?\//g, - '', - ); - } - - urlWithoutPlaceholders = urlWithoutPlaceholders - .replace(/{(.*?)}/g, 'by-$1') - // replace slashes with hyphens for camelcase method at the end - .replace(/[/:+]/g, '-'); - - return stringCase({ - case: 'camelCase', - value: `${method}-${urlWithoutPlaceholders}`, - }); -}; - -export const operationParameterFilterFn = ( - parameter: OperationParameter, -): boolean => { - const config = getConfig(); - - // legacy clients ignore the "api-version" param since we do not want to - // add it as the first/default parameter for each of the service calls - return !isLegacyClient(config) || parameter.prop !== 'api-version'; -}; - -export const operationParameterNameFn = ( - parameter: Omit, -): string => { - const config = getConfig(); - - return !isLegacyClient(config) - ? parameter.prop - : transformTypeKeyName(parameter.prop); -}; - -export const tagResponseTypes = (responses: OperationResponse[]) => - responses.map((response) => { - const { code } = response; - if (code === 'default') { - response.responseTypes = inferDefaultResponseTypes(response, responses); - } else if (isSuccessStatusCode(code)) { - response.responseTypes = ['success']; - } else if (isErrorStatusCode(code)) { - response.responseTypes = ['error']; - } - return response; - }); diff --git a/packages/openapi-ts/src/openApi/common/parser/sanitize.ts b/packages/openapi-ts/src/openApi/common/parser/sanitize.ts index 27fa71955..dba46d2a8 100644 --- a/packages/openapi-ts/src/openApi/common/parser/sanitize.ts +++ b/packages/openapi-ts/src/openApi/common/parser/sanitize.ts @@ -1,14 +1,3 @@ -import { illegalStartCharactersRegExp } from '~/utils/regexp'; - -export const ensureValidTypeScriptJavaScriptIdentifier = (name: string) => { - const replaced = name.replace(/[^$\u200c\u200d\p{ID_Continue}]/gu, '_'); - illegalStartCharactersRegExp.lastIndex = 0; - const startsWithIllegalCharacter = - illegalStartCharactersRegExp.test(replaced); - const valid = startsWithIllegalCharacter ? `_${replaced}` : replaced; - return valid; -}; - /** * Sanitizes namespace identifiers so they are valid TypeScript identifiers of a certain form. * @@ -28,8 +17,3 @@ export const sanitizeNamespaceIdentifier = (name: string) => .replace(/^[^\p{ID_Start}]+/u, '') .replace(/[^$\u200c\u200d\p{ID_Continue}]/gu, '-') .replace(/[$+]/g, '-'); - -export const sanitizeOperationParameterName = (name: string) => { - const withoutBrackets = name.replace('[]', 'Array'); - return sanitizeNamespaceIdentifier(withoutBrackets); -}; diff --git a/packages/openapi-ts/src/openApi/common/parser/service.ts b/packages/openapi-ts/src/openApi/common/parser/service.ts deleted file mode 100644 index 0351896f8..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/service.ts +++ /dev/null @@ -1,20 +0,0 @@ -export const allowedServiceMethods = [ - 'connect', - 'delete', - 'get', - 'head', - 'options', - 'patch', - 'post', - 'put', - 'trace', -] as const; - -/** - * Convert the service version to 'normal' version. - * This basically removes any "v" prefix from the version string. - * @param version - */ -export function getServiceVersion(version = '1.0'): string { - return String(version).replace(/^v/gi, ''); -} diff --git a/packages/openapi-ts/src/openApi/common/parser/sort.ts b/packages/openapi-ts/src/openApi/common/parser/sort.ts deleted file mode 100644 index b3ecd112b..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/sort.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Sort list of values and ensure that required parameters are first so that we do not generate - * invalid types. Optional parameters cannot be positioned after required ones. - */ -export function toSortedByRequired< - T extends { default?: unknown; isRequired: boolean }, ->(values: T[]): T[] { - return values.sort((a, b) => { - const aNeedsValue = a.isRequired && a.default === undefined; - const bNeedsValue = b.isRequired && b.default === undefined; - if (aNeedsValue && !bNeedsValue) return -1; - if (bNeedsValue && !aNeedsValue) return 1; - return 0; - }); -} diff --git a/packages/openapi-ts/src/openApi/common/parser/stripNamespace.ts b/packages/openapi-ts/src/openApi/common/parser/stripNamespace.ts deleted file mode 100644 index 7ae032282..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/stripNamespace.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Strip (OpenAPI) namespaces from values. - * @param value - */ -export const stripNamespace = (value: string): string => - value - .trim() - .replace(/^#\/definitions\//, '') - .replace(/^#\/parameters\//, '') - .replace(/^#\/responses\//, '') - .replace(/^#\/securityDefinitions\//, '') - .replace(/^#\/components\/schemas\//, '') - .replace(/^#\/components\/responses\//, '') - .replace(/^#\/components\/parameters\//, '') - .replace(/^#\/components\/examples\//, '') - .replace(/^#\/components\/requestBodies\//, '') - .replace(/^#\/components\/headers\//, '') - .replace(/^#\/components\/securitySchemes\//, '') - .replace(/^#\/components\/links\//, '') - .replace(/^#\/components\/callbacks\//, ''); diff --git a/packages/openapi-ts/src/openApi/common/parser/type.ts b/packages/openapi-ts/src/openApi/common/parser/type.ts deleted file mode 100644 index bd8bde457..000000000 --- a/packages/openapi-ts/src/openApi/common/parser/type.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { isDefinitionTypeNullable } from '~/openApi/v3/parser/inferType'; -import { refParametersPartial } from '~/utils/const'; -import { transformTypeName } from '~/utils/transform'; - -import type { Type } from '../interfaces/Type'; -import { ensureValidTypeScriptJavaScriptIdentifier } from './sanitize'; -import { stripNamespace } from './stripNamespace'; - -/** - * Get mapped type for given type to basic Typescript/Javascript type. - */ -export const getMappedType = ( - type: string, - format?: string, -): string | undefined => { - if (format === 'binary') { - return 'binary'; - } - switch (type) { - case 'any': - case 'object': - case 'unknown': - return 'unknown'; - case 'array': - return 'unknown[]'; - case 'boolean': - return 'boolean'; - case 'byte': - case 'double': - case 'float': - case 'int': - case 'integer': - case 'long': - case 'number': - case 'short': - return 'number'; - case 'char': - case 'date': - case 'date-time': - case 'password': - case 'string': - return 'string'; - case 'file': - return 'binary'; - case 'null': - return 'null'; - case 'void': - return 'void'; - default: - return; - } -}; - -/** - * Matches characters inside square brackets, including the brackets. Does not - * match if the opening bracket is preceded by "`1" which is a syntax for generics - * from C#. - * - * Hello[World] -> matches [World] - * Hello`1[World] -> no match - * string[] -> matches [] - */ -export const hasSquareBracketsRegExp = /(? { - const result: Type = { - $refs: [], - base: 'unknown', - imports: [], - isNullable: false, - template: null, - type: 'unknown', - }; - - // Special case for JSON Schema spec (december 2020, page 17), - // that allows type to be an array of primitive types... - if (Array.isArray(type)) { - const joinedType = type - .filter((value) => value !== 'null') - .map((value) => getMappedType(value, format)) - .filter(Boolean) - .join(' | '); - result.type = joinedType; - result.base = joinedType; - result.isNullable = isDefinitionTypeNullable({ type }); - return result; - } - - const mapped = getMappedType(type, format); - if (mapped) { - result.type = mapped; - result.base = mapped; - return result; - } - - const typeWithoutNamespace = decodeURIComponent(stripNamespace(type)); - - hasSquareBracketsRegExp.lastIndex = 0; - if (hasSquareBracketsRegExp.test(typeWithoutNamespace)) { - const matches = typeWithoutNamespace.match(/(.*?)\[(.*)\]$/); - if (matches?.length) { - const match1 = getType({ - debug, - type: ensureValidTypeScriptJavaScriptIdentifier(matches[1]!), - }); - const match2 = getType({ - debug, - type: ensureValidTypeScriptJavaScriptIdentifier(matches[2]!), - }); - - if (match1.type === 'unknown[]') { - result.type = `${match2.type}[]`; - result.base = `${match2.type}`; - match1.$refs = []; - match1.imports = []; - } else if (match2.type) { - result.type = `${match1.type}<${match2.type}>`; - result.base = match1.type; - result.template = match2.type; - } else { - result.type = match1.type; - result.base = match1.type; - result.template = match1.type; - } - - result.$refs = [...result.$refs, ...match1.$refs, ...match2.$refs]; - result.imports = [ - ...result.imports, - ...match1.imports, - ...match2.imports, - ]; - return result; - } - } - - if (typeWithoutNamespace) { - let encodedType = transformTypeName( - ensureValidTypeScriptJavaScriptIdentifier(typeWithoutNamespace), - ); - if (type.startsWith(refParametersPartial)) { - // prefix parameter names to avoid conflicts, assuming people are mostly - // interested in importing schema types and don't care about this naming - encodedType = `Parameter${encodedType}`; - } - result.type = encodedType; - result.base = encodedType; - if (type.startsWith('#')) { - result.$refs = [...result.$refs, decodeURIComponent(type)]; - } - result.imports = [...result.imports, encodedType]; - return result; - } - - return result; -}; diff --git a/packages/openapi-ts/src/openApi/index.ts b/packages/openapi-ts/src/openApi/index.ts index 500657745..2ccd20c97 100644 --- a/packages/openapi-ts/src/openApi/index.ts +++ b/packages/openapi-ts/src/openApi/index.ts @@ -3,60 +3,10 @@ import { Context } from '~/ir/context'; import { parseV2_0_X } from '~/openApi/2.0.x'; import { parseV3_0_X } from '~/openApi/3.0.x'; import { parseV3_1_X } from '~/openApi/3.1.x'; -import type { Client } from '~/openApi/common/interfaces/client'; -import type { OpenApi as LegacyOpenApi } from '~/openApi/common/interfaces/OpenApi'; import type { OpenApi } from '~/openApi/types'; -import { parse as parseV2 } from '~/openApi/v2'; -import { parse as parseV3 } from '~/openApi/v3'; import type { Config } from '~/types/config'; import type { Logger } from '~/utils/logger'; -export type { - Client, - Enum, - Method, - Model, - ModelMeta, - Operation, - OperationParameter, - OperationResponse, -} from './common/interfaces/client'; -export type { OpenApi } from './common/interfaces/OpenApi'; -export { isOperationParameterRequired } from './common/parser/operation'; -export { - ensureValidTypeScriptJavaScriptIdentifier, - sanitizeNamespaceIdentifier, - sanitizeOperationParameterName, -} from './common/parser/sanitize'; -export { getType } from './common/parser/type'; -export type { OpenApiSchema as OpenApiV2Schema } from './v2/interfaces/OpenApiSchema'; -export type { OpenApiSchema as OpenApiV3Schema } from './v3/interfaces/OpenApiSchema'; - -/** - * Parse the OpenAPI specification to a Client model that contains - * all the models, services and schema's we should output. - * @param openApi The OpenAPI spec that we have loaded from disk. - */ -export function parseLegacy({ - openApi, -}: { - openApi: unknown; -}): Omit { - const spec = openApi as LegacyOpenApi; - - if ('openapi' in spec) { - return parseV3(spec); - } - - if ('swagger' in spec) { - return parseV2(spec); - } - - throw new Error( - `Unsupported OpenAPI specification: ${JSON.stringify(spec, null, 2)}`, - ); -} - /** * @internal * Parse the resolved OpenAPI specification. This will populate and return @@ -72,7 +22,7 @@ export const parseOpenApiSpec = ({ dependencies: Record; logger: Logger; spec: unknown; -}): Context | undefined => { +}): Context => { const context = new Context({ config, dependencies, diff --git a/packages/openapi-ts/src/openApi/v2/index.ts b/packages/openapi-ts/src/openApi/v2/index.ts deleted file mode 100644 index eca7c2948..000000000 --- a/packages/openapi-ts/src/openApi/v2/index.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { Client } from '~/openApi/common/interfaces/client'; -import { getServiceVersion } from '~/openApi/common/parser/service'; - -import type { OpenApi } from './interfaces/OpenApi'; -import { getModels } from './parser/getModels'; -import { getOperations } from './parser/getOperations'; -import { getServer } from './parser/getServer'; - -/** - * Parse the OpenAPI specification to a Client model that contains - * all the models, operations and schema's we should output. - * @param openApi The OpenAPI spec that we have loaded from disk. - */ -export const parse = (openApi: OpenApi): Omit => { - const version = getServiceVersion(openApi.info.version); - const server = getServer(openApi); - const { models, types } = getModels(openApi); - const operations = getOperations({ openApi, types }); - - return { - models, - operations, - server, - types, - version, - }; -}; diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/Extensions/WithNullableExtension.ts b/packages/openapi-ts/src/openApi/v2/interfaces/Extensions/WithNullableExtension.ts deleted file mode 100644 index 4912b2c21..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/Extensions/WithNullableExtension.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface WithNullableExtension { - 'x-nullable'?: boolean; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/Model.ts b/packages/openapi-ts/src/openApi/v2/interfaces/Model.ts deleted file mode 100644 index c442b81a6..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/Model.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Model, ModelMeta } from '~/openApi/common/interfaces/client'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from './OpenApi'; -import type { OpenApiSchema } from './OpenApiSchema'; - -export type GetModelFn = ( - args: Pick & { - definition: OpenApiSchema; - isDefinition?: boolean; - meta?: ModelMeta; - openApi: OpenApi; - }, -) => Model; diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApi.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApi.ts deleted file mode 100644 index 5d641a917..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApi.ts +++ /dev/null @@ -1,32 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; -import type { OpenApiInfo } from './OpenApiInfo'; -import type { OpenApiParameter } from './OpenApiParameter'; -import type { OpenApiPath } from './OpenApiPath'; -import type { OpenApiResponse } from './OpenApiResponse'; -import type { OpenApiSchema } from './OpenApiSchema'; -import type { OpenApiSecurityRequirement } from './OpenApiSecurityRequirement'; -import type { OpenApiSecurityScheme } from './OpenApiSecurityScheme'; -import type { OpenApiTag } from './OpenApiTag'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md - */ -export interface OpenApi { - basePath?: string; - consumes?: string[]; - definitions?: Dictionary; - externalDocs?: OpenApiExternalDocs; - host?: string; - info: OpenApiInfo; - parameters?: Dictionary; - paths: Dictionary; - produces?: string[]; - responses?: Dictionary; - schemes?: string[]; - security?: OpenApiSecurityRequirement[]; - securityDefinitions?: Dictionary; - swagger: string; - tags?: OpenApiTag[]; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiContact.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiContact.ts deleted file mode 100644 index fd3b0ba88..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiContact.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#contact-object - */ -export interface OpenApiContact { - email?: string; - name?: string; - url?: string; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExample.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExample.ts deleted file mode 100644 index 992d12a60..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExample.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#example-object - */ -export interface OpenApiExample { - [mimetype: string]: unknown; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExternalDocs.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExternalDocs.ts deleted file mode 100644 index 2e88cc48e..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiExternalDocs.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#external-documentation-object - */ -export interface OpenApiExternalDocs { - description?: string; - url: string; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiHeader.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiHeader.ts deleted file mode 100644 index cc595e0df..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiHeader.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiItems } from './OpenApiItems'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#header-object - */ -export interface OpenApiHeader { - collectionFormat?: 'csv' | 'ssv' | 'tsv' | 'pipes'; - default?: unknown; - description?: string; - enum?: (string | number)[]; - exclusiveMaximum?: boolean; - exclusiveMinimum?: boolean; - format?: - | 'int32' - | 'int64' - | 'float' - | 'double' - | 'string' - | 'boolean' - | 'byte' - | 'binary' - | 'date' - | 'date-time' - | 'password'; - items?: Dictionary; - maxItems?: number; - maxLength?: number; - maximum?: number; - minItems?: number; - minLength?: number; - minimum?: number; - multipleOf?: number; - pattern?: string; - type: 'string' | 'number' | 'integer' | 'boolean' | 'array'; - uniqueItems?: boolean; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiInfo.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiInfo.ts deleted file mode 100644 index 955b6704d..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiInfo.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { OpenApiContact } from './OpenApiContact'; -import type { OpenApiLicense } from './OpenApiLicense'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#info-object - */ -export interface OpenApiInfo { - contact?: OpenApiContact; - description?: string; - license?: OpenApiLicense; - termsOfService?: string; - title: string; - version: string; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiItems.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiItems.ts deleted file mode 100644 index 6e0025752..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiItems.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { WithEnumExtension } from '~/openApi/common/interfaces/WithEnumExtension'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#items-object) - */ -export interface OpenApiItems extends WithEnumExtension { - collectionFormat?: 'csv' | 'ssv' | 'tsv' | 'pipes'; - default?: unknown; - enum?: (string | number)[]; - exclusiveMaximum?: number; - exclusiveMinimum?: number; - format?: - | 'int32' - | 'int64' - | 'float' - | 'double' - | 'string' - | 'boolean' - | 'byte' - | 'binary' - | 'date' - | 'date-time' - | 'password'; - items?: OpenApiItems; - maxItems?: number; - maxLength?: number; - maximum?: number; - minItems?: number; - minLength?: number; - minimum?: number; - multipleOf?: number; - pattern?: string; - type?: string; - uniqueItems?: boolean; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiLicense.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiLicense.ts deleted file mode 100644 index 580d89e46..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiLicense.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#license-object - */ -export interface OpenApiLicense { - name: string; - url?: string; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiOperation.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiOperation.ts deleted file mode 100644 index 27932a7fe..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiOperation.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; -import type { OpenApiParameter } from './OpenApiParameter'; -import type { OpenApiResponses } from './OpenApiResponses'; -import type { OpenApiSecurityRequirement } from './OpenApiSecurityRequirement'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#operation-object - */ -export interface OpenApiOperation { - consumes?: string[]; - deprecated?: boolean; - description?: string; - externalDocs?: OpenApiExternalDocs; - operationId?: string; - parameters?: OpenApiParameter[]; - produces?: string[]; - responses: OpenApiResponses; - schemes?: ('http' | 'https' | 'ws' | 'wss')[]; - security?: OpenApiSecurityRequirement[]; - summary?: string; - tags?: string[]; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiParameter.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiParameter.ts deleted file mode 100644 index 223151007..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiParameter.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { WithEnumExtension } from '~/openApi/common/interfaces/WithEnumExtension'; - -import type { WithNullableExtension } from './Extensions/WithNullableExtension'; -import type { OpenApiItems } from './OpenApiItems'; -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiSchema } from './OpenApiSchema'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#parameter-object - */ -export interface OpenApiParameter - extends OpenApiReference, - WithEnumExtension, - WithNullableExtension { - allowEmptyValue?: boolean; - collectionFormat?: 'csv' | 'ssv' | 'tsv' | 'pipes' | 'multi'; - default?: unknown; - description?: string; - enum?: (string | number)[]; - exclusiveMaximum?: boolean; - exclusiveMinimum?: boolean; - format?: - | 'int32' - | 'int64' - | 'float' - | 'double' - | 'string' - | 'boolean' - | 'byte' - | 'binary' - | 'date' - | 'date-time' - | 'password'; - in: 'path' | 'query' | 'header' | 'formData' | 'body'; - items?: OpenApiItems; - maxItems?: number; - maxLength?: number; - maximum?: number; - minItems?: number; - minLength?: number; - minimum?: number; - multipleOf?: number; - name: string; - pattern?: string; - required?: boolean; - schema?: OpenApiSchema; - type?: string; - uniqueItems?: boolean; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiPath.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiPath.ts deleted file mode 100644 index c342a87ae..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiPath.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { OpenApiOperation } from './OpenApiOperation'; -import type { OpenApiParameter } from './OpenApiParameter'; -import type { OpenApiReference } from './OpenApiReference'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-item-object - */ -export interface OpenApiPath extends OpenApiReference { - connect?: OpenApiOperation; - delete?: OpenApiOperation; - get?: OpenApiOperation; - head?: OpenApiOperation; - options?: OpenApiOperation; - parameters?: OpenApiParameter[]; - patch?: OpenApiOperation; - post?: OpenApiOperation; - put?: OpenApiOperation; - trace?: OpenApiOperation; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiReference.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiReference.ts deleted file mode 100644 index 6916176ea..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiReference.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#reference-object - */ -export interface OpenApiReference { - $ref?: string; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponse.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponse.ts deleted file mode 100644 index 26c372d80..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponse.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiExample } from './OpenApiExample'; -import type { OpenApiHeader } from './OpenApiHeader'; -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiSchema } from './OpenApiSchema'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#response-object - */ -export interface OpenApiResponse extends OpenApiReference { - description: string; - examples?: OpenApiExample; - headers?: Dictionary; - schema?: OpenApiSchema & OpenApiReference; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponses.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponses.ts deleted file mode 100644 index 4d5b84243..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiResponses.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { OpenApiResponse } from './OpenApiResponse'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#responses-object - */ -interface Response { - [httpcode: string]: OpenApiResponse; -} - -export type OpenApiResponses = Response & { - default?: OpenApiResponse; -}; diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSchema.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSchema.ts deleted file mode 100644 index 65ff39f37..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSchema.ts +++ /dev/null @@ -1,56 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; -import type { WithEnumExtension } from '~/openApi/common/interfaces/WithEnumExtension'; - -import type { WithNullableExtension } from './Extensions/WithNullableExtension'; -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiXml } from './OpenApiXml'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#schema-object - */ -export interface OpenApiSchema - extends OpenApiReference, - WithEnumExtension, - WithNullableExtension { - additionalProperties?: boolean | OpenApiSchema; - allOf?: OpenApiSchema[]; - default?: unknown; - description?: string; - discriminator?: string; - enum?: (string | number)[]; - example?: unknown; - exclusiveMaximum?: boolean; - exclusiveMinimum?: boolean; - externalDocs?: OpenApiExternalDocs; - format?: - | 'int32' - | 'int64' - | 'float' - | 'double' - | 'string' - | 'boolean' - | 'byte' - | 'binary' - | 'date' - | 'date-time' - | 'password'; - items?: OpenApiSchema; - maxItems?: number; - maxLength?: number; - maxProperties?: number; - maximum?: number; - minItems?: number; - minLength?: number; - minProperties?: number; - minimum?: number; - multipleOf?: number; - pattern?: string; - properties?: Dictionary; - readOnly?: boolean; - required?: string[]; - title?: string; - type?: string; - uniqueItems?: boolean; - xml?: OpenApiXml; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityRequirement.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityRequirement.ts deleted file mode 100644 index 24d2e678b..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityRequirement.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#security-requirement-object - */ -export interface OpenApiSecurityRequirement { - [key: string]: string; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityScheme.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityScheme.ts deleted file mode 100644 index 2a096b0f6..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiSecurityScheme.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#security-scheme-object - */ -export interface OpenApiSecurityScheme { - authorizationUrl?: string; - description?: string; - flow?: 'implicit' | 'password' | 'application' | 'accessCode'; - in?: 'query' | 'header'; - name?: string; - scopes: Dictionary; - tokenUrl?: string; - type: 'basic' | 'apiKey' | 'oauth2'; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiTag.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiTag.ts deleted file mode 100644 index d1beb5ca6..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiTag.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#tag-object - */ -export interface OpenApiTag { - description?: string; - externalDocs?: OpenApiExternalDocs; - name: string; -} diff --git a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiXml.ts b/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiXml.ts deleted file mode 100644 index 4aab655df..000000000 --- a/packages/openapi-ts/src/openApi/v2/interfaces/OpenApiXml.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#xml-object - */ -export interface OpenApiXml { - attribute?: boolean; - name?: string; - namespace?: string; - prefix?: string; - wrapped?: boolean; -} diff --git a/packages/openapi-ts/src/openApi/v2/parser/__tests__/getServer.test.ts b/packages/openapi-ts/src/openApi/v2/parser/__tests__/getServer.test.ts deleted file mode 100644 index 926f51ccd..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/__tests__/getServer.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { getServer } from '../getServer'; - -describe('getServer', () => { - it('should produce correct result', () => { - expect( - getServer({ - basePath: '/api', - host: 'localhost:8080', - info: { - title: 'dummy', - version: '1.0', - }, - paths: {}, - schemes: ['http', 'https'], - swagger: '2.0', - }), - ).toEqual('http://localhost:8080/api'); - }); -}); diff --git a/packages/openapi-ts/src/openApi/v2/parser/getModel.ts b/packages/openapi-ts/src/openApi/v2/parser/getModel.ts deleted file mode 100644 index 449810818..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getModel.ts +++ /dev/null @@ -1,190 +0,0 @@ -import type { Model, ModelMeta } from '~/openApi/common/interfaces/client'; -import { getEnums } from '~/openApi/common/parser/getEnums'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getType } from '~/openApi/common/parser/type'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { getModelComposition } from './getModelComposition'; -import { getModelProperties } from './getModelProperties'; - -export const getModel = ({ - definition, - isDefinition = false, - meta, - openApi, - types, -}: Pick & { - definition: OpenApiSchema; - isDefinition?: boolean; - meta?: ModelMeta; - openApi: OpenApi; -}): Model => { - const model: Model = { - $refs: [], - base: 'unknown', - description: definition.description || null, - enum: [], - enums: [], - exclusiveMaximum: definition.exclusiveMaximum, - exclusiveMinimum: definition.exclusiveMinimum, - export: 'interface', - format: definition.format, - imports: [], - in: '', - isDefinition, - isNullable: definition['x-nullable'] === true, - isReadOnly: definition.readOnly === true, - isRequired: false, - link: null, - maxItems: definition.maxItems, - maxLength: definition.maxLength, - maxProperties: definition.maxProperties, - maximum: definition.maximum, - meta, - minItems: definition.minItems, - minLength: definition.minLength, - minProperties: definition.minProperties, - minimum: definition.minimum, - multipleOf: definition.multipleOf, - name: meta?.name ?? '', - pattern: getPattern(definition.pattern), - properties: [], - template: null, - type: 'unknown', - uniqueItems: definition.uniqueItems, - }; - - if (definition.$ref) { - const definitionRef = getType({ type: definition.$ref }); - model.export = 'reference'; - model.type = definitionRef.type; - model.base = definitionRef.base; - model.template = definitionRef.template; - model.imports.push(...definitionRef.imports); - return model; - } - - if (definition.enum && definition.type !== 'boolean') { - const enums = getEnums(definition, definition.enum); - if (enums.length) { - model.base = 'string'; - model.enum = [...model.enum, ...enums]; - model.export = 'enum'; - model.type = 'string'; - return model; - } - } - - if (definition.type === 'array' && definition.items) { - if (definition.items.$ref) { - const arrayItems = getType({ type: definition.items.$ref }); - model.export = 'array'; - model.type = arrayItems.type; - model.base = arrayItems.base; - model.template = arrayItems.template; - model.imports.push(...arrayItems.imports); - return model; - } else { - const arrayItems = getModel({ - definition: definition.items, - openApi, - types, - }); - model.export = 'array'; - model.type = arrayItems.type; - model.base = arrayItems.base; - model.template = arrayItems.template; - model.link = arrayItems; - model.imports.push(...arrayItems.imports); - return model; - } - } - - if ( - definition.type === 'object' && - typeof definition.additionalProperties === 'object' - ) { - if (definition.additionalProperties.$ref) { - const additionalProperties = getType({ - type: definition.additionalProperties.$ref, - }); - model.export = 'dictionary'; - model.type = additionalProperties.type; - model.base = additionalProperties.base; - model.template = additionalProperties.template; - model.imports.push(...additionalProperties.imports); - return model; - } else { - const additionalProperties = getModel({ - definition: definition.additionalProperties, - openApi, - types, - }); - model.export = 'dictionary'; - model.type = additionalProperties.type; - model.base = additionalProperties.base; - model.template = additionalProperties.template; - model.link = additionalProperties; - model.imports.push(...additionalProperties.imports); - return model; - } - } - - if (definition.allOf?.length) { - const composition = getModelComposition({ - definition, - definitions: definition.allOf, - getModel, - openApi, - type: 'all-of', - types, - }); - model.export = composition.export; - model.imports.push(...composition.imports); - model.properties.push(...composition.properties); - model.enums = [...model.enums, ...composition.enums]; - return model; - } - - if (definition.type === 'object') { - model.export = 'interface'; - model.type = 'unknown'; - model.base = 'unknown'; - - if (definition.properties) { - const modelProperties = getModelProperties({ - definition, - getModel, - openApi, - types, - }); - modelProperties.forEach((modelProperty) => { - model.imports.push(...modelProperty.imports); - model.enums = [...model.enums, ...modelProperty.enums]; - model.properties.push(modelProperty); - if (modelProperty.export === 'enum') { - model.enums = [...model.enums, modelProperty]; - } - }); - } - return model; - } - - // If the schema has a type than it can be a basic or generic type. - if (definition.type) { - const definitionType = getType({ - format: definition.format, - type: definition.type, - }); - model.export = 'generic'; - model.type = definitionType.type; - model.base = definitionType.base; - model.template = definitionType.template; - model.imports.push(...definitionType.imports); - return model; - } - - return model; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getModelComposition.ts b/packages/openapi-ts/src/openApi/v2/parser/getModelComposition.ts deleted file mode 100644 index d131b1e79..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getModelComposition.ts +++ /dev/null @@ -1,108 +0,0 @@ -import type { - Model, - ModelComposition, -} from '~/openApi/common/interfaces/client'; - -import type { Client } from '../../../types/client'; -import type { GetModelFn } from '../interfaces/Model'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { getModelProperties } from './getModelProperties'; -import { getRequiredPropertiesFromComposition } from './getRequiredPropertiesFromComposition'; - -export const getModelComposition = ({ - definition, - definitions, - getModel, - openApi, - type, - types, -}: { - definition: OpenApiSchema; - definitions: OpenApiSchema[]; - getModel: GetModelFn; - openApi: OpenApi; - type: 'one-of' | 'any-of' | 'all-of'; - types: Client['types']; -}): ModelComposition => { - const composition: ModelComposition = { - $refs: [], - enums: [], - export: type, - imports: [], - properties: [], - }; - - const properties: Model[] = []; - - definitions - .map((definition) => getModel({ definition, openApi, types })) - .filter((model) => { - const hasProperties = model.properties.length; - const hasEnums = model.enums.length; - const isObject = model.type === 'unknown'; - const isEmpty = isObject && !hasProperties && !hasEnums; - return !isEmpty; - }) - .forEach((model) => { - composition.imports.push(...model.imports); - composition.enums.push(...model.enums); - composition.properties.push(model); - }); - - if (definition.required && type === 'all-of') { - const requiredProperties = getRequiredPropertiesFromComposition({ - definitions, - getModel, - openApi, - required: definition.required, - types, - }); - requiredProperties.forEach((requiredProperty) => { - composition.imports.push(...requiredProperty.imports); - composition.enums.push(...requiredProperty.enums); - }); - properties.push(...requiredProperties); - } - - if (definition.properties) { - const modelProperties = getModelProperties({ - definition, - getModel, - openApi, - types, - }); - modelProperties.forEach((modelProperty) => { - composition.imports.push(...modelProperty.imports); - composition.enums.push(...modelProperty.enums); - if (modelProperty.export === 'enum') { - composition.enums.push(modelProperty); - } - }); - properties.push(...modelProperties); - } - - if (properties.length) { - composition.properties.push({ - $refs: [], - base: 'unknown', - description: '', - enum: [], - enums: [], - export: 'interface', - imports: [], - in: '', - isDefinition: false, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: 'properties', - properties, - template: null, - type: 'unknown', - }); - } - - return composition; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getModelProperties.ts b/packages/openapi-ts/src/openApi/v2/parser/getModelProperties.ts deleted file mode 100644 index d3a51c7f5..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getModelProperties.ts +++ /dev/null @@ -1,104 +0,0 @@ -import type { Model } from '~/openApi/common/interfaces/client'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getType } from '~/openApi/common/parser/type'; -import { escapeName } from '~/utils/escape'; - -import type { Client } from '../../../types/client'; -import type { GetModelFn } from '../interfaces/Model'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; - -export const getModelProperties = ({ - definition, - getModel, - openApi, - types, -}: { - definition: OpenApiSchema; - getModel: GetModelFn; - openApi: OpenApi; - types: Client['types']; -}): Model[] => { - const models: Model[] = []; - - Object.entries(definition.properties ?? {}).forEach( - ([propertyName, property]) => { - const propertyRequired = Boolean( - definition.required?.includes(propertyName), - ); - if (property.$ref) { - const model = getType({ type: property.$ref }); - models.push({ - $refs: [], - base: model.base, - description: property.description || null, - enum: [], - enums: [], - exclusiveMaximum: property.exclusiveMaximum, - exclusiveMinimum: property.exclusiveMinimum, - export: 'reference', - format: property.format, - imports: model.imports, - in: '', - isDefinition: false, - isNullable: property['x-nullable'] === true, - isReadOnly: property.readOnly === true, - isRequired: propertyRequired, - link: null, - maxItems: property.maxItems, - maxLength: property.maxLength, - maxProperties: property.maxProperties, - maximum: property.maximum, - minItems: property.minItems, - minLength: property.minLength, - minProperties: property.minProperties, - minimum: property.minimum, - multipleOf: property.multipleOf, - name: escapeName(propertyName), - pattern: getPattern(property.pattern), - properties: [], - template: model.template, - type: model.type, - uniqueItems: property.uniqueItems, - }); - } else { - const model = getModel({ definition: property, openApi, types }); - models.push({ - $refs: [], - base: model.base, - description: property.description || null, - enum: model.enum, - enums: model.enums, - exclusiveMaximum: property.exclusiveMaximum, - exclusiveMinimum: property.exclusiveMinimum, - export: model.export, - format: property.format, - imports: model.imports, - in: '', - isDefinition: false, - isNullable: property['x-nullable'] === true, - isReadOnly: property.readOnly === true, - isRequired: propertyRequired, - link: model.link, - maxItems: property.maxItems, - maxLength: property.maxLength, - maxProperties: property.maxProperties, - maximum: property.maximum, - minItems: property.minItems, - minLength: property.minLength, - minProperties: property.minProperties, - minimum: property.minimum, - multipleOf: property.multipleOf, - name: escapeName(propertyName), - pattern: getPattern(property.pattern), - properties: model.properties, - template: model.template, - type: model.type, - uniqueItems: property.uniqueItems, - }); - } - }, - ); - - return models; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getModels.ts b/packages/openapi-ts/src/openApi/v2/parser/getModels.ts deleted file mode 100644 index 7a87247aa..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getModels.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { getType } from '~/openApi/common/parser/type'; -import { reservedJavaScriptKeywordsRegExp } from '~/utils/regexp'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import { getModel } from './getModel'; - -export const getModels = ( - openApi: OpenApi, -): Pick => { - const types: Client['types'] = {}; - let models: Client['models'] = []; - - Object.entries(openApi.definitions ?? {}).forEach( - ([definitionName, definition]) => { - const definitionType = getType({ type: definitionName }); - const name = definitionType.base.replace( - reservedJavaScriptKeywordsRegExp, - '_$1', - ); - const meta = { - $ref: `#/definitions/${definitionName}`, - name, - }; - types[name] = meta; - const model = getModel({ - definition, - isDefinition: true, - meta, - openApi, - types, - }); - models = [...models, model]; - }, - ); - - return { - models, - types, - }; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getOperationParameter.ts b/packages/openapi-ts/src/openApi/v2/parser/getOperationParameter.ts deleted file mode 100644 index 1016e3ea3..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getOperationParameter.ts +++ /dev/null @@ -1,186 +0,0 @@ -import type { OperationParameter } from '~/openApi/common/interfaces/client'; -import { getDefault } from '~/openApi/common/parser/getDefault'; -import { getEnums } from '~/openApi/common/parser/getEnums'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { operationParameterNameFn } from '~/openApi/common/parser/operation'; -import { getType } from '~/openApi/common/parser/type'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiParameter } from '../interfaces/OpenApiParameter'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { getModel } from './getModel'; - -export const getOperationParameter = ({ - openApi, - parameter, - types, -}: { - openApi: OpenApi; - parameter: OpenApiParameter; - types: Client['types']; -}): OperationParameter => { - const operationParameterWithoutName: Omit = { - $refs: [], - base: 'unknown', - description: parameter.description || null, - enum: [], - enums: [], - exclusiveMaximum: parameter.exclusiveMaximum, - exclusiveMinimum: parameter.exclusiveMinimum, - export: 'interface', - format: parameter.format, - imports: [], - in: parameter.in, - isDefinition: false, - isNullable: parameter['x-nullable'] === true, - isReadOnly: false, - isRequired: parameter.required === true, - link: null, - maxItems: parameter.maxItems, - maxLength: parameter.maxLength, - maximum: parameter.maximum, - mediaType: null, - minItems: parameter.minItems, - minLength: parameter.minLength, - minimum: parameter.minimum, - multipleOf: parameter.multipleOf, - pattern: getPattern(parameter.pattern), - prop: parameter.name, - properties: [], - template: null, - type: 'unknown', - uniqueItems: parameter.uniqueItems, - }; - let operationParameter = { - ...operationParameterWithoutName, - name: operationParameterNameFn(operationParameterWithoutName), - }; - - if (parameter.$ref) { - const model = getType({ type: parameter.$ref }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - export: 'reference', - imports: [...operationParameter.imports, ...model.imports], - template: model.template, - type: model.type, - }; - operationParameter.default = getDefault(parameter, operationParameter); - return operationParameter; - } - - if (parameter.enum) { - const model = getEnums(parameter, parameter.enum); - if (model.length) { - operationParameter = { - ...operationParameter, - base: 'string', - enum: [...operationParameter.enum, ...model], - export: 'enum', - type: 'string', - }; - operationParameter.default = getDefault(parameter, operationParameter); - return operationParameter; - } - } - - if (parameter.type === 'array' && parameter.items) { - const model = getType({ - format: parameter.items.format, - type: parameter.items.type, - }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - export: 'array', - imports: [...operationParameter.imports, ...model.imports], - template: model.template, - type: model.type, - }; - operationParameter.default = getDefault(parameter, operationParameter); - return operationParameter; - } - - if (parameter.type === 'object' && parameter.items) { - const model = getType({ - format: parameter.items.format, - type: parameter.items.type, - }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - export: 'dictionary', - imports: [...operationParameter.imports, ...model.imports], - template: model.template, - type: model.type, - }; - operationParameter.default = getDefault(parameter, operationParameter); - return operationParameter; - } - - let schema = parameter.schema; - if (schema) { - if (schema.$ref?.startsWith('#/parameters/')) { - schema = getRef(openApi, schema); - } - - if (schema.$ref) { - const model = getType({ type: schema.$ref }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - export: 'reference', - imports: [...operationParameter.imports, ...model.imports], - template: model.template, - type: model.type, - }; - operationParameter.default = getDefault(parameter, operationParameter); - return operationParameter; - } - - const model = getModel({ definition: schema, openApi, types }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - enum: [...operationParameter.enum, ...model.enum], - enums: [...operationParameter.enums, ...model.enums], - export: model.export, - imports: [...operationParameter.imports, ...model.imports], - link: model.link, - properties: [...operationParameter.properties, ...model.properties], - template: model.template, - type: model.type, - }; - operationParameter.default = getDefault(parameter, operationParameter); - return operationParameter; - } - - // If the parameter has a type than it can be a basic or generic type. - if (parameter.type) { - const model = getType({ - format: parameter.format, - type: parameter.type, - }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - export: 'generic', - imports: [...operationParameter.imports, ...model.imports], - template: model.template, - type: model.type, - }; - operationParameter.default = getDefault(parameter, operationParameter); - return operationParameter; - } - - return operationParameter; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getOperationParameters.ts b/packages/openapi-ts/src/openApi/v2/parser/getOperationParameters.ts deleted file mode 100644 index 392832370..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getOperationParameters.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type { OperationParameters } from '~/openApi/common/interfaces/client'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { operationParameterFilterFn } from '~/openApi/common/parser/operation'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiParameter } from '../interfaces/OpenApiParameter'; -import { getOperationParameter } from './getOperationParameter'; - -const allowedIn = ['body', 'formData', 'header', 'path', 'query'] as const; - -export const getOperationParameters = ({ - openApi, - parameters, - types, -}: { - openApi: OpenApi; - parameters: OpenApiParameter[]; - types: Client['types']; -}): OperationParameters => { - const operationParameters: OperationParameters = { - $refs: [], - imports: [], - parameters: [], - parametersBody: null, - parametersCookie: [], // not used in v2 - parametersForm: [], - parametersHeader: [], - parametersPath: [], - parametersQuery: [], - }; - - parameters.forEach((parameterOrReference) => { - const parameterDef = getRef( - openApi, - parameterOrReference, - ); - const parameter = getOperationParameter({ - openApi, - parameter: parameterDef, - types, - }); - - const skip = !operationParameterFilterFn(parameter); - if (!allowedIn.includes(parameterDef.in) || skip) { - return; - } - - switch (parameterDef.in) { - case 'body': - operationParameters.parametersBody = parameter; - break; - case 'formData': - operationParameters.parametersForm = [ - ...operationParameters.parametersForm, - parameter, - ]; - break; - case 'header': - operationParameters.parametersHeader = [ - ...operationParameters.parametersHeader, - parameter, - ]; - break; - case 'path': - operationParameters.parametersPath = [ - ...operationParameters.parametersPath, - parameter, - ]; - break; - case 'query': - operationParameters.parametersQuery = [ - ...operationParameters.parametersQuery, - parameter, - ]; - break; - } - - operationParameters.$refs = [ - ...operationParameters.$refs, - ...parameter.$refs, - ]; - operationParameters.imports = [ - ...operationParameters.imports, - ...parameter.imports, - ]; - operationParameters.parameters = [ - ...operationParameters.parameters, - parameter, - ]; - }); - - return operationParameters; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getOperationResponse.ts b/packages/openapi-ts/src/openApi/v2/parser/getOperationResponse.ts deleted file mode 100644 index 9068c93b3..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getOperationResponse.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type { OperationResponse } from '~/openApi/common/interfaces/client'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { getType } from '~/openApi/common/parser/type'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiResponse } from '../interfaces/OpenApiResponse'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { getModel } from './getModel'; - -export const getOperationResponse = ({ - code, - openApi, - response, - types, -}: { - code: OperationResponse['code']; - openApi: OpenApi; - response: OpenApiResponse; - types: Client['types']; -}): OperationResponse => { - const operationResponse: OperationResponse = { - $refs: [], - base: code !== 204 ? 'unknown' : 'void', - code, - description: response.description || null, - enum: [], - enums: [], - export: 'generic', - imports: [], - in: 'response', - isDefinition: false, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: '', - properties: [], - responseTypes: [], - template: null, - type: code !== 204 ? 'unknown' : 'void', - }; - - let schema = response.schema; - if (schema) { - if (schema.$ref?.startsWith('#/responses/')) { - schema = getRef(openApi, schema); - } - - if (schema.$ref) { - const model = getType({ type: schema.$ref }); - operationResponse.export = 'reference'; - operationResponse.type = model.type; - operationResponse.base = model.base; - operationResponse.template = model.template; - operationResponse.imports = [ - ...operationResponse.imports, - ...model.imports, - ]; - return operationResponse; - } - - const model = getModel({ definition: schema, openApi, types }); - operationResponse.export = model.export; - operationResponse.type = model.type; - operationResponse.base = model.base; - operationResponse.template = model.template; - operationResponse.link = model.link; - operationResponse.isReadOnly = model.isReadOnly; - operationResponse.isRequired = model.isRequired; - operationResponse.isNullable = model.isNullable; - operationResponse.format = model.format; - operationResponse.maximum = model.maximum; - operationResponse.exclusiveMaximum = model.exclusiveMaximum; - operationResponse.minimum = model.minimum; - operationResponse.exclusiveMinimum = model.exclusiveMinimum; - operationResponse.multipleOf = model.multipleOf; - operationResponse.maxLength = model.maxLength; - operationResponse.minLength = model.minLength; - operationResponse.maxItems = model.maxItems; - operationResponse.minItems = model.minItems; - operationResponse.uniqueItems = model.uniqueItems; - operationResponse.maxProperties = model.maxProperties; - operationResponse.minProperties = model.minProperties; - operationResponse.pattern = getPattern(model.pattern); - operationResponse.imports = [ - ...operationResponse.imports, - ...model.imports, - ]; - operationResponse.enum = [...operationResponse.enum, ...model.enum]; - operationResponse.enums = [...operationResponse.enums, ...model.enums]; - operationResponse.properties = [ - ...operationResponse.properties, - ...model.properties, - ]; - return operationResponse; - } - - // We support basic properties from response headers, since both - // fetch and XHR client just support string types. - if (response.headers) { - for (const name in response.headers) { - operationResponse.in = 'header'; - operationResponse.name = name; - operationResponse.type = 'string'; - operationResponse.base = 'string'; - return operationResponse; - } - } - - return operationResponse; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getOperationResponses.ts b/packages/openapi-ts/src/openApi/v2/parser/getOperationResponses.ts deleted file mode 100644 index 3ebf13843..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getOperationResponses.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { OperationResponse } from '~/openApi/common/interfaces/client'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { - parseResponseStatusCode, - sorterByResponseStatusCode, - tagResponseTypes, -} from '~/openApi/common/parser/operation'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiResponse } from '../interfaces/OpenApiResponse'; -import type { OpenApiResponses } from '../interfaces/OpenApiResponses'; -import { getOperationResponse } from './getOperationResponse'; - -export const getOperationResponses = ({ - openApi, - responses, - types, -}: { - openApi: OpenApi; - responses: OpenApiResponses; - types: Client['types']; -}): OperationResponse[] => { - let operationResponses: OperationResponse[] = []; - - Object.entries(responses).forEach(([responseCode, responseOrReference]) => { - const code = parseResponseStatusCode(responseCode); - if (!code) { - return; - } - - const response = getRef(openApi, responseOrReference); - const operationResponse = getOperationResponse({ - code, - openApi, - response, - types, - }); - operationResponses = [...operationResponses, operationResponse]; - }); - - operationResponses = tagResponseTypes(operationResponses); - - return operationResponses.sort(sorterByResponseStatusCode); -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getOperations.ts b/packages/openapi-ts/src/openApi/v2/parser/getOperations.ts deleted file mode 100644 index fe297f310..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getOperations.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { createOperationKey } from '~/ir/operation'; -import type { Client, Operation } from '~/openApi/common/interfaces/client'; -import { operationFilterFn } from '~/openApi/common/parser/operation'; -import { allowedServiceMethods } from '~/openApi/common/parser/service'; -import { getConfig } from '~/utils/config'; - -import type { OpenApi } from '../interfaces/OpenApi'; -import { getOperationParameters } from './getOperationParameters'; -import { getOperation } from './operation'; - -export const getOperations = ({ - openApi, - types, -}: { - openApi: OpenApi; - types: Client['types']; -}): Operation[] => { - const operationIds = new Map(); - const operations: Operation[] = []; - - const config = getConfig(); - - for (const path in openApi.paths) { - const pathItem = openApi.paths[path]!; - const pathParameters = getOperationParameters({ - openApi, - parameters: pathItem.parameters ?? [], - types, - }); - - for (const name in pathItem) { - const method = name as Lowercase; - - const operationKey = createOperationKey({ - method, - path, - }); - - if (allowedServiceMethods.includes(method)) { - const op = pathItem[method]!; - - if (op.operationId) { - if (operationIds.has(op.operationId)) { - if (config.logs.level !== 'silent') { - console.warn( - `❗️ Duplicate operationId: ${op.operationId} in ${operationKey}. Please ensure your operation IDs are unique. This behavior is not supported and will likely lead to unexpected results.`, - ); - } - } else { - operationIds.set(op.operationId, operationKey); - } - } - - if ( - operationFilterFn({ - config, - operationKey, - }) - ) { - const operation = getOperation({ - method, - op, - openApi, - pathParams: pathParameters, - types, - url: path, - }); - operations.push(operation); - } - } - } - } - - return operations; -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/getRequiredPropertiesFromComposition.ts b/packages/openapi-ts/src/openApi/v2/parser/getRequiredPropertiesFromComposition.ts deleted file mode 100644 index b67368619..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getRequiredPropertiesFromComposition.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { Model } from '~/openApi/common/interfaces/client'; -import { getRef } from '~/openApi/common/parser/getRef'; - -import type { Client } from '../../../types/client'; -import type { GetModelFn } from '../interfaces/Model'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; - -export const getRequiredPropertiesFromComposition = ({ - definitions, - getModel, - openApi, - required, - types, -}: { - definitions: OpenApiSchema[]; - getModel: GetModelFn; - openApi: OpenApi; - required: string[]; - types: Client['types']; -}): Model[] => - definitions - .reduce((properties, definition) => { - if (definition.$ref) { - const schema = getRef(openApi, definition); - return [ - ...properties, - ...getModel({ definition: schema, openApi, types }).properties, - ]; - } - return [ - ...properties, - ...getModel({ definition, openApi, types }).properties, - ]; - }, [] as Model[]) - .filter( - (property) => !property.isRequired && required.includes(property.name), - ) - .map((property) => ({ - ...property, - isRequired: true, - })); diff --git a/packages/openapi-ts/src/openApi/v2/parser/getServer.ts b/packages/openapi-ts/src/openApi/v2/parser/getServer.ts deleted file mode 100644 index e148543e8..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/getServer.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { OpenApi } from '../interfaces/OpenApi'; - -/** - * Get the base server url. - * @param openApi - */ -export const getServer = (openApi: OpenApi): string => { - const scheme = openApi.schemes?.[0] || 'http'; - const host = openApi.host; - const basePath = openApi.basePath || ''; - const url = host ? `${scheme}://${host}${basePath}` : basePath; - return url.replace(/\/$/g, ''); -}; diff --git a/packages/openapi-ts/src/openApi/v2/parser/operation.ts b/packages/openapi-ts/src/openApi/v2/parser/operation.ts deleted file mode 100644 index 9a34b1f27..000000000 --- a/packages/openapi-ts/src/openApi/v2/parser/operation.ts +++ /dev/null @@ -1,116 +0,0 @@ -import type { - Operation, - OperationParameters, -} from '~/openApi/common/interfaces/client'; -import { - getOperationResponseHeader, - operationNameFn, -} from '~/openApi/common/parser/operation'; -import { toSortedByRequired } from '~/openApi/common/parser/sort'; -import { getConfig } from '~/utils/config'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiOperation } from '../interfaces/OpenApiOperation'; -import { getOperationParameters } from './getOperationParameters'; -import { getOperationResponses } from './getOperationResponses'; - -export const getOperation = ({ - method, - op, - openApi, - pathParams, - types, - url, -}: { - method: Lowercase; - op: OpenApiOperation; - openApi: OpenApi; - pathParams: OperationParameters; - types: Client['types']; - url: string; -}): Operation => { - const operationWithoutName: Omit = { - $refs: [], - deprecated: op.deprecated === true, - description: op.description || null, - id: op.operationId || null, - imports: [], - method: method.toUpperCase() as Operation['method'], - parameters: [...pathParams.parameters], - parametersBody: pathParams.parametersBody, - parametersCookie: [...pathParams.parametersCookie], - parametersForm: [...pathParams.parametersForm], - parametersHeader: [...pathParams.parametersHeader], - parametersPath: [...pathParams.parametersPath], - parametersQuery: [...pathParams.parametersQuery], - path: url, - responseHeader: null, - responses: [], - summary: op.summary || null, - tags: op.tags || null, - }; - const operation = { - ...operationWithoutName, - name: operationNameFn({ - config: getConfig(), - method: operationWithoutName.method, - operationId: op.operationId, - path: operationWithoutName.path, - }), - }; - - if (op.parameters) { - const parameters = getOperationParameters({ - openApi, - parameters: op.parameters, - types, - }); - operation.$refs = [...operation.$refs, ...parameters.$refs]; - operation.imports = [...operation.imports, ...parameters.imports]; - operation.parameters = [...operation.parameters, ...parameters.parameters]; - operation.parametersBody = parameters.parametersBody; - operation.parametersCookie = [ - ...operation.parametersCookie, - ...parameters.parametersCookie, - ]; - operation.parametersForm = [ - ...operation.parametersForm, - ...parameters.parametersForm, - ]; - operation.parametersHeader = [ - ...operation.parametersHeader, - ...parameters.parametersHeader, - ]; - operation.parametersPath = [ - ...operation.parametersPath, - ...parameters.parametersPath, - ]; - operation.parametersQuery = [ - ...operation.parametersQuery, - ...parameters.parametersQuery, - ]; - } - - if (op.responses) { - operation.responses = getOperationResponses({ - openApi, - responses: op.responses, - types, - }); - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - - operation.responseHeader = getOperationResponseHeader(successResponses); - - successResponses.forEach((response) => { - operation.$refs = [...operation.$refs, ...response.$refs]; - operation.imports = [...operation.imports, ...response.imports]; - }); - } - - operation.parameters = toSortedByRequired(operation.parameters); - - return operation; -}; diff --git a/packages/openapi-ts/src/openApi/v3/index.ts b/packages/openapi-ts/src/openApi/v3/index.ts deleted file mode 100644 index eca7c2948..000000000 --- a/packages/openapi-ts/src/openApi/v3/index.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { Client } from '~/openApi/common/interfaces/client'; -import { getServiceVersion } from '~/openApi/common/parser/service'; - -import type { OpenApi } from './interfaces/OpenApi'; -import { getModels } from './parser/getModels'; -import { getOperations } from './parser/getOperations'; -import { getServer } from './parser/getServer'; - -/** - * Parse the OpenAPI specification to a Client model that contains - * all the models, operations and schema's we should output. - * @param openApi The OpenAPI spec that we have loaded from disk. - */ -export const parse = (openApi: OpenApi): Omit => { - const version = getServiceVersion(openApi.info.version); - const server = getServer(openApi); - const { models, types } = getModels(openApi); - const operations = getOperations({ openApi, types }); - - return { - models, - operations, - server, - types, - version, - }; -}; diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/Model.ts b/packages/openapi-ts/src/openApi/v3/interfaces/Model.ts deleted file mode 100644 index 731d6f25c..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/Model.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { Model, ModelMeta } from '~/openApi/common/interfaces/client'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from './OpenApi'; -import type { OpenApiSchema } from './OpenApiSchema'; - -export type GetModelFn = ( - args: Pick & { - debug?: boolean; - definition: OpenApiSchema; - /** - * Pass through initial model values - */ - initialValues?: Partial; - isDefinition?: boolean; - meta?: ModelMeta; - openApi: OpenApi; - parentDefinition?: OpenApiSchema | null; - }, -) => Model; diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApi.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApi.ts deleted file mode 100644 index 3a80db46d..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApi.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { OpenApiComponents } from './OpenApiComponents'; -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; -import type { OpenApiInfo } from './OpenApiInfo'; -import type { OpenApiPaths } from './OpenApiPaths'; -import type { OpenApiSecurityRequirement } from './OpenApiSecurityRequirement'; -import type { OpenApiServer } from './OpenApiServer'; -import type { OpenApiTag } from './OpenApiTag'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md - */ -export interface OpenApi { - components?: OpenApiComponents; - externalDocs?: OpenApiExternalDocs; - info: OpenApiInfo; - openapi: string; - paths: OpenApiPaths; - security?: OpenApiSecurityRequirement[]; - servers?: OpenApiServer[]; - tags?: OpenApiTag[]; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiCallback.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiCallback.ts deleted file mode 100644 index 4a7b4c21c..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiCallback.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { OpenApiPath } from './OpenApiPath'; -import type { OpenApiReference } from './OpenApiReference'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object - */ -interface Callback { - [key: string]: OpenApiPath; -} - -export type OpenApiCallback = OpenApiReference & Callback; diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiComponents.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiComponents.ts deleted file mode 100644 index 883acb493..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiComponents.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiCallback } from './OpenApiCallback'; -import type { OpenApiExample } from './OpenApiExample'; -import type { OpenApiHeader } from './OpenApiHeader'; -import type { OpenApiLink } from './OpenApiLink'; -import type { OpenApiParameter } from './OpenApiParameter'; -import type { OpenApiRequestBody } from './OpenApiRequestBody'; -import type { OpenApiResponses } from './OpenApiResponses'; -import type { OpenApiSchema } from './OpenApiSchema'; -import type { OpenApiSecurityScheme } from './OpenApiSecurityScheme'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#components-object - */ -export interface OpenApiComponents { - callbacks?: Dictionary; - examples?: Dictionary; - headers?: Dictionary; - links?: Dictionary; - parameters?: Dictionary; - requestBodies?: Dictionary; - responses?: Dictionary; - schemas?: Dictionary; - securitySchemes?: Dictionary; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiContact.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiContact.ts deleted file mode 100644 index 6ffc35693..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiContact.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#contact-object - */ -export interface OpenApiContact { - email?: string; - name?: string; - url?: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiDiscriminator.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiDiscriminator.ts deleted file mode 100644 index bb33b72b7..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiDiscriminator.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#discriminator-object - */ -export interface OpenApiDiscriminator { - mapping?: Dictionary; - propertyName: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiEncoding.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiEncoding.ts deleted file mode 100644 index 620eedbee..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiEncoding.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiHeader } from './OpenApiHeader'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encoding-object - */ -export interface OpenApiEncoding { - allowReserved?: boolean; - contentType?: string; - explode?: boolean; - headers?: Dictionary; - style?: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExample.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExample.ts deleted file mode 100644 index 8531e3fad..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExample.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { OpenApiReference } from './OpenApiReference'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object - */ -export interface OpenApiExample extends OpenApiReference { - description?: string; - externalValue?: string; - summary?: string; - value?: unknown; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExternalDocs.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExternalDocs.ts deleted file mode 100644 index 8b435c828..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiExternalDocs.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#external-documentation-object - */ -export interface OpenApiExternalDocs { - description?: string; - url: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiHeader.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiHeader.ts deleted file mode 100644 index e32ba419d..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiHeader.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiExample } from './OpenApiExample'; -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiSchema } from './OpenApiSchema'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#header-object - */ -export interface OpenApiHeader extends OpenApiReference { - allowEmptyValue?: boolean; - allowReserved?: boolean; - deprecated?: boolean; - description?: string; - example?: unknown; - examples?: Dictionary; - explode?: boolean; - required?: boolean; - schema?: OpenApiSchema; - style?: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiInfo.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiInfo.ts deleted file mode 100644 index a92ddd370..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiInfo.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { OpenApiContact } from './OpenApiContact'; -import type { OpenApiLicense } from './OpenApiLicense'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#info-object - */ -export interface OpenApiInfo { - contact?: OpenApiContact; - description?: string; - license?: OpenApiLicense; - termsOfService?: string; - title: string; - version: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLicense.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLicense.ts deleted file mode 100644 index e85de83bf..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLicense.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#license-object - */ -export interface OpenApiLicense { - name: string; - url?: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLink.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLink.ts deleted file mode 100644 index 6b36c907e..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiLink.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiServer } from './OpenApiServer'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object - */ -export interface OpenApiLink extends OpenApiReference { - description?: string; - operationId?: string; - operationRef?: string; - parameters?: Dictionary; - requestBody?: unknown; - server?: OpenApiServer; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiMediaType.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiMediaType.ts deleted file mode 100644 index 01d115809..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiMediaType.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiEncoding } from './OpenApiEncoding'; -import type { OpenApiExample } from './OpenApiExample'; -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiSchema } from './OpenApiSchema'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object - */ -export interface OpenApiMediaType extends OpenApiReference { - encoding?: Dictionary; - example?: unknown; - examples?: Dictionary; - schema?: OpenApiSchema; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlow.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlow.ts deleted file mode 100644 index 5ef94cc65..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlow.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oauth-flow-object - */ -export interface OpenApiOAuthFlow { - authorizationUrl: string; - refreshUrl?: string; - scopes: Dictionary; - tokenUrl: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlows.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlows.ts deleted file mode 100644 index 443150468..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOAuthFlows.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { OpenApiOAuthFlow } from './OpenApiOAuthFlow'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oauth-flows-object - */ -export interface OpenApiOAuthFlows { - authorizationCode?: OpenApiOAuthFlow; - clientCredentials?: OpenApiOAuthFlow; - implicit?: OpenApiOAuthFlow; - password?: OpenApiOAuthFlow; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOperation.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOperation.ts deleted file mode 100644 index f4bcc9bd9..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiOperation.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiCallback } from './OpenApiCallback'; -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; -import type { OpenApiParameter } from './OpenApiParameter'; -import type { OpenApiRequestBody } from './OpenApiRequestBody'; -import type { OpenApiResponses } from './OpenApiResponses'; -import type { OpenApiSecurityRequirement } from './OpenApiSecurityRequirement'; -import type { OpenApiServer } from './OpenApiServer'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object - */ -export interface OpenApiOperation { - callbacks?: Dictionary; - deprecated?: boolean; - description?: string; - externalDocs?: OpenApiExternalDocs; - operationId?: string; - parameters?: OpenApiParameter[]; - requestBody?: OpenApiRequestBody; - responses: OpenApiResponses; - security?: OpenApiSecurityRequirement[]; - servers?: OpenApiServer[]; - summary?: string; - tags?: string[]; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiParameter.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiParameter.ts deleted file mode 100644 index 3bf7ec4ac..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiParameter.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiExample } from './OpenApiExample'; -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiSchema } from './OpenApiSchema'; - -/** - * add only one type for now as that's needed to resolve the reported issue, - * more types should be added though - * {@link https://github.com/hey-api/openapi-ts/issues/612} - */ -type MediaType = 'application/json'; - -/** - * encoding interface should be added, not adding it for now as it's not needed - * to resolve the issue reported - * {@link https://github.com/hey-api/openapi-ts/issues/612} - */ -interface MediaTypeObject { - example?: unknown; - examples?: Dictionary; - schema: OpenApiSchema; - // encoding? -} - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object - */ -export interface OpenApiParameter extends OpenApiReference { - allowEmptyValue?: boolean; - allowReserved?: boolean; - content?: Record; - deprecated?: boolean; - description?: string; - example?: unknown; - examples?: Dictionary; - explode?: boolean; - in: 'cookie' | 'formData' | 'header' | 'path' | 'query'; - name: string; - nullable?: boolean; - required?: boolean; - schema?: OpenApiSchema; - style?: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPath.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPath.ts deleted file mode 100644 index dc0cf6d09..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPath.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { OpenApiOperation } from './OpenApiOperation'; -import type { OpenApiParameter } from './OpenApiParameter'; -import type { OpenApiServer } from './OpenApiServer'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object - */ -export interface OpenApiPath { - connect?: OpenApiOperation; - delete?: OpenApiOperation; - description?: string; - get?: OpenApiOperation; - head?: OpenApiOperation; - options?: OpenApiOperation; - parameters?: OpenApiParameter[]; - patch?: OpenApiOperation; - post?: OpenApiOperation; - put?: OpenApiOperation; - servers?: OpenApiServer[]; - summary?: string; - trace?: OpenApiOperation; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPaths.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPaths.ts deleted file mode 100644 index da108892a..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiPaths.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { OpenApiPath } from './OpenApiPath'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#paths-object - */ -export interface OpenApiPaths { - [path: string]: OpenApiPath; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiReference.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiReference.ts deleted file mode 100644 index 514ba953c..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiReference.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#reference-object - */ -export interface OpenApiReference { - $ref?: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiRequestBody.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiRequestBody.ts deleted file mode 100644 index a001a7a8a..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiRequestBody.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiMediaType } from './OpenApiMediaType'; -import type { OpenApiReference } from './OpenApiReference'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#request-body-object - */ -export interface OpenApiRequestBody extends OpenApiReference { - content: Dictionary; - description?: string; - nullable?: boolean; - required?: boolean; - 'x-body-name'?: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponse.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponse.ts deleted file mode 100644 index 83fe0c65b..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponse.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiHeader } from './OpenApiHeader'; -import type { OpenApiLink } from './OpenApiLink'; -import type { OpenApiMediaType } from './OpenApiMediaType'; -import type { OpenApiReference } from './OpenApiReference'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#response-object - */ -export interface OpenApiResponse extends OpenApiReference { - content?: Dictionary; - description: string; - headers?: Dictionary; - links?: Dictionary; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponses.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponses.ts deleted file mode 100644 index af664f5a0..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiResponses.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiResponse } from './OpenApiResponse'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#responses-object - */ -interface Response { - [httpcode: string]: OpenApiResponse; -} - -export type OpenApiResponses = OpenApiReference & - Response & { - default: OpenApiResponse; - }; diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSchema.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSchema.ts deleted file mode 100644 index f8c66cc96..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSchema.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; -import type { WithEnumExtension } from '~/openApi/common/interfaces/WithEnumExtension'; - -import type { OpenApiDiscriminator } from './OpenApiDiscriminator'; -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; -import type { OpenApiReference } from './OpenApiReference'; -import type { OpenApiXml } from './OpenApiXml'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object - */ -export interface OpenApiSchema extends OpenApiReference, WithEnumExtension { - additionalProperties?: boolean | OpenApiSchema; - allOf?: OpenApiSchema[]; - anyOf?: OpenApiSchema[]; - const?: string | number | boolean | null; - default?: unknown; - deprecated?: boolean; - description?: string; - discriminator?: OpenApiDiscriminator; - enum?: (string | number)[]; - example?: unknown; - exclusiveMaximum?: boolean; - exclusiveMinimum?: boolean; - externalDocs?: OpenApiExternalDocs; - format?: - | 'binary' - | 'boolean' - | 'byte' - | 'date-time' - | 'date' - | 'double' - | 'float' - | 'int32' - | 'int64' - | 'password' - | 'string'; - items?: OpenApiSchema; - maxItems?: number; - maxLength?: number; - maxProperties?: number; - maximum?: number; - minItems?: number; - minLength?: number; - minProperties?: number; - minimum?: number; - multipleOf?: number; - not?: OpenApiSchema[]; - nullable?: boolean; - oneOf?: OpenApiSchema[]; - pattern?: string; - prefixItems?: OpenApiSchema[]; - properties?: Dictionary; - readOnly?: boolean; - required?: string[]; - title?: string; - type?: string | string[]; - uniqueItems?: boolean; - writeOnly?: boolean; - xml?: OpenApiXml; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityRequirement.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityRequirement.ts deleted file mode 100644 index 9c62f7695..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityRequirement.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-requirement-object - */ -export interface OpenApiSecurityRequirement { - [name: string]: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityScheme.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityScheme.ts deleted file mode 100644 index d1fd3ac57..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiSecurityScheme.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { OpenApiOAuthFlows } from './OpenApiOAuthFlows'; -import type { OpenApiReference } from './OpenApiReference'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-scheme-object - */ -export interface OpenApiSecurityScheme extends OpenApiReference { - bearerFormat?: string; - description?: string; - flows?: OpenApiOAuthFlows; - in?: 'query' | 'header' | 'cookie'; - name?: string; - openIdConnectUrl?: string; - scheme?: string; - type: 'apiKey' | 'http' | 'oauth2' | 'openIdConnect'; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServer.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServer.ts deleted file mode 100644 index d09ccaf6c..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServer.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApiServerVariable } from './OpenApiServerVariable'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-object - */ -export interface OpenApiServer { - description?: string; - url: string; - variables?: Dictionary; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServerVariable.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServerVariable.ts deleted file mode 100644 index 1477f8fe1..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiServerVariable.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { WithEnumExtension } from '~/openApi/common/interfaces/WithEnumExtension'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-variable-object - */ -export interface OpenApiServerVariable extends WithEnumExtension { - default: string; - description?: string; - enum?: (string | number)[]; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiTag.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiTag.ts deleted file mode 100644 index 3d6b15af2..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiTag.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { OpenApiExternalDocs } from './OpenApiExternalDocs'; - -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#tag-object - */ -export interface OpenApiTag { - description?: string; - externalDocs?: OpenApiExternalDocs; - name: string; -} diff --git a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiXml.ts b/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiXml.ts deleted file mode 100644 index 84e168712..000000000 --- a/packages/openapi-ts/src/openApi/v3/interfaces/OpenApiXml.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * {@link} https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xml-object - */ -export interface OpenApiXml { - attribute?: boolean; - name?: string; - namespace?: string; - prefix?: string; - wrapped?: boolean; -} diff --git a/packages/openapi-ts/src/openApi/v3/parser/__tests__/getModel.test.ts b/packages/openapi-ts/src/openApi/v3/parser/__tests__/getModel.test.ts deleted file mode 100644 index e58e7eec8..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/__tests__/getModel.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import { getType } from '~/openApi/common/parser/type'; - -import type { Config } from '../../../../types/config'; -import { reservedJavaScriptKeywordsRegExp } from '../../../../utils/regexp'; -import { getModel } from '../getModel'; - -vi.mock('../../../../utils/config', () => { - const config: Partial = { - plugins: { - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - }, - }; - return { - getConfig: () => config, - }; -}); - -const openApi = { - components: { - schemas: { - CompositionWithAny: { - description: - "This is a model with one property with a 'any of' relationship where the options are not $ref", - properties: { - propA: { - anyOf: [ - { - $ref: '#/components/schemas/Enum1', - }, - { - $ref: '#/components/schemas/ConstValue', - }, - { - type: 'null', - }, - ], - }, - }, - type: 'object', - }, - CompositionWithAnyOfAndNull: { - description: - "This is a model with one property with a 'any of' relationship where the options are not $ref", - properties: { - propA: { - anyOf: [ - { - items: { - anyOf: [ - { - $ref: '#/components/schemas/Enum1', - }, - { - $ref: '#/components/schemas/ConstValue', - }, - ], - }, - type: 'array', - }, - { - type: 'null', - }, - ], - }, - }, - type: 'object', - }, - ConstValue: { - const: 'ConstValue', - type: 'string', - }, - Enum1: { - enum: ['Bird', 'Dog'], - type: 'string', - }, - }, - }, - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3.0', - paths: {}, - servers: [ - { - url: 'https://localhost:8080/api', - }, - ], -}; - -describe('getModel', () => { - it('Parses any of', () => { - const definition = openApi.components.schemas.CompositionWithAnyOfAndNull; - const definitionType = getType({ type: 'CompositionWithAnyOfAndNull' }); - const model = getModel({ - definition, - isDefinition: true, - meta: { - $ref: '', - name: definitionType.base.replace( - reservedJavaScriptKeywordsRegExp, - '_$1', - ), - }, - openApi, - types: {}, - }); - expect(model.properties[0]!.properties.length).toBe(2); - }); - - it('Parses any of 2', () => { - const definition = openApi.components.schemas.CompositionWithAny; - const definitionType = getType({ type: 'CompositionWithAny' }); - const model = getModel({ - definition, - isDefinition: true, - meta: { - $ref: '', - name: definitionType.base.replace( - reservedJavaScriptKeywordsRegExp, - '_$1', - ), - }, - openApi, - types: {}, - }); - expect(model.properties[0]!.properties.length).toBe(3); - }); -}); diff --git a/packages/openapi-ts/src/openApi/v3/parser/__tests__/getServer.test.ts b/packages/openapi-ts/src/openApi/v3/parser/__tests__/getServer.test.ts deleted file mode 100644 index 41cf40726..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/__tests__/getServer.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { getServer } from '../getServer'; - -describe('getServer', () => { - it('should produce correct result', () => { - expect( - getServer({ - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3.0', - paths: {}, - servers: [ - { - url: 'https://localhost:8080/api', - }, - ], - }), - ).toEqual('https://localhost:8080/api'); - }); - - it('should produce correct result with variables', () => { - expect( - getServer({ - info: { - title: 'dummy', - version: '1.0', - }, - openapi: '3.0', - paths: {}, - servers: [ - { - url: '{scheme}://localhost:{port}/api', - variables: { - port: { - default: '8080', - }, - scheme: { - default: 'https', - }, - }, - }, - ], - }), - ).toEqual('https://localhost:8080/api'); - }); -}); diff --git a/packages/openapi-ts/src/openApi/v3/parser/discriminator.ts b/packages/openapi-ts/src/openApi/v3/parser/discriminator.ts deleted file mode 100644 index ea3834aec..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/discriminator.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { Model } from '~/openApi/common/interfaces/client'; -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; -import { stripNamespace } from '~/openApi/common/parser/stripNamespace'; - -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiDiscriminator } from '../interfaces/OpenApiDiscriminator'; - -const inverseDictionary = (map: Dictionary): Dictionary => { - const m2: Dictionary = {}; - for (const name in map) { - m2[map[name]!] = name; - } - return m2; -}; - -export const findOneOfParentDiscriminator = ( - openApi: OpenApi, - parent?: Model, -): OpenApiDiscriminator | undefined => { - if (openApi.components && parent) { - for (const definitionName in openApi.components.schemas) { - if (openApi.components.schemas.hasOwnProperty(definitionName)) { - const schema = openApi.components.schemas[definitionName]!; - if ( - schema.discriminator && - schema.oneOf?.length && - schema.oneOf.some( - (definition) => - definition.$ref && stripNamespace(definition.$ref) == parent.name, - ) - ) { - return schema.discriminator; - } - } - } - } - return; -}; - -export const mapPropertyValue = ( - discriminator: OpenApiDiscriminator, - parent: Model, -): string => { - if (discriminator.mapping) { - const mapping = inverseDictionary(discriminator.mapping); - const key = Object.keys(mapping).find( - (item) => stripNamespace(item) == parent.name, - ); - if (key && mapping[key]) { - return mapping[key]; - } - } - return parent.name; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getContent.ts b/packages/openapi-ts/src/openApi/v3/parser/getContent.ts deleted file mode 100644 index 26cbd7f59..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getContent.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { Dictionary } from '~/openApi/common/interfaces/Dictionary'; - -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiMediaType } from '../interfaces/OpenApiMediaType'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; - -export interface Content { - mediaType: string; - schema: OpenApiSchema; -} - -const BASIC_MEDIA_TYPES = [ - 'application/json-patch+json', - 'application/json', - 'application/ld+json', - 'application/x-www-form-urlencoded', - 'multipart/batch', - 'multipart/form-data', - 'multipart/mixed', - 'multipart/related', - 'text/json', - 'text/plain', -]; - -export const getContent = ( - _openApi: OpenApi, - content: Dictionary, -): Content | undefined => { - const basicMediaTypeWithSchema = Object.keys(content) - .filter((mediaType) => { - const cleanMediaType = mediaType.split(';')[0]!.trim(); - return BASIC_MEDIA_TYPES.includes(cleanMediaType); - }) - .find((mediaType) => Boolean(content[mediaType]?.schema)); - - if (basicMediaTypeWithSchema) { - return { - mediaType: basicMediaTypeWithSchema, - schema: content[basicMediaTypeWithSchema]!.schema as OpenApiSchema, - }; - } - - const firstMediaTypeWithSchema = Object.keys(content).find((mediaType) => - Boolean(content[mediaType]?.schema), - ); - - if (firstMediaTypeWithSchema) { - return { - mediaType: firstMediaTypeWithSchema, - schema: content[firstMediaTypeWithSchema]!.schema as OpenApiSchema, - }; - } - - return; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getModel.ts b/packages/openapi-ts/src/openApi/v3/parser/getModel.ts deleted file mode 100644 index e3dd272d9..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getModel.ts +++ /dev/null @@ -1,325 +0,0 @@ -import type { Model, ModelMeta } from '~/openApi/common/interfaces/client'; -import { getDefault } from '~/openApi/common/parser/getDefault'; -import { getEnums } from '~/openApi/common/parser/getEnums'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getType } from '~/openApi/common/parser/type'; -import { enumMeta } from '~/utils/enum'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { - findModelComposition, - getModelComposition, -} from './getModelComposition'; -import { - getAdditionalPropertiesModel, - getModelProperties, -} from './getModelProperties'; -import { - getDefinitionTypes, - inferType, - isDefinitionNullable, -} from './inferType'; - -export const getModel = ({ - debug, - definition, - initialValues = {}, - isDefinition = false, - meta, - openApi, - parentDefinition = null, - types, -}: Pick & { - debug?: boolean; - definition: OpenApiSchema; - /** - * Pass through initial model values - */ - initialValues?: Partial; - isDefinition?: boolean; - meta?: ModelMeta; - openApi: OpenApi; - parentDefinition?: OpenApiSchema | null; -}): Model => { - const definitionTypes = getDefinitionTypes(definition); - const inferredType = inferType(definition, definitionTypes); - - const model: Model = { - $refs: [], - base: 'unknown', - deprecated: Boolean(definition.deprecated), - description: definition.description || null, - enum: [], - enums: [], - exclusiveMaximum: definition.exclusiveMaximum, - exclusiveMinimum: definition.exclusiveMinimum, - export: 'interface', - format: definition.format, - imports: [], - in: '', - isDefinition, - isNullable: isDefinitionNullable(definition), - isReadOnly: definition.readOnly === true, - isRequired: false, - link: null, - maxItems: definition.maxItems, - maxLength: definition.maxLength, - maxProperties: definition.maxProperties, - maximum: definition.maximum, - meta, - minItems: definition.minItems, - minLength: definition.minLength, - minProperties: definition.minProperties, - minimum: definition.minimum, - multipleOf: definition.multipleOf, - name: meta?.name ?? '', - pattern: getPattern(definition.pattern), - properties: [], - template: null, - type: 'unknown', - uniqueItems: definition.uniqueItems, - ...initialValues, - }; - - if (definition.$ref) { - const definitionRef = getType({ - debug, - type: definition.$ref, - }); - model.$refs = [...model.$refs, decodeURIComponent(definition.$ref)]; - model.base = definitionRef.base; - model.export = 'reference'; - model.imports = [...model.imports, ...definitionRef.imports]; - model.template = definitionRef.template; - model.type = definitionRef.type; - model.default = getDefault(definition, model); - return model; - } - - if (inferredType === 'enum') { - const enums = getEnums(definition, definition.enum); - if (enums.length) { - model.base = 'string'; - model.enum = [...model.enum, ...enums]; - model.export = 'enum'; - model.type = 'string'; - model.default = getDefault(definition, model); - if (!model.meta) { - model.meta = enumMeta(model); - } - return model; - } - } - - if ( - definitionTypes.includes('array') && - (definition.items || definition.prefixItems) - ) { - if (definition.prefixItems) { - const arrayItems = definition.prefixItems.map((item) => - getModel({ - definition: item, - openApi, - parentDefinition: definition, - types, - }), - ); - - model.export = 'array'; - model.$refs = [ - ...model.$refs, - ...arrayItems.reduce( - (acc, m) => [...acc, ...m.$refs], - [] as Model['$refs'], - ), - ]; - model.imports = [ - ...model.imports, - ...arrayItems.reduce( - (acc, m) => [...acc, ...m.imports], - [] as Model['imports'], - ), - ]; - model.link = arrayItems; - model.default = getDefault(definition, model); - return model; - } - - if (!definition.items) { - return model; - } - - if (definition.items.$ref) { - const arrayItems = getType({ type: definition.items.$ref }); - model.$refs = [...model.$refs, decodeURIComponent(definition.items.$ref)]; - model.base = arrayItems.base; - model.export = 'array'; - model.imports = [...model.imports, ...arrayItems.imports]; - model.template = arrayItems.template; - model.type = arrayItems.type; - model.default = getDefault(definition, model); - return model; - } - - if (definition.items.anyOf && parentDefinition && parentDefinition.type) { - const foundComposition = findModelComposition(parentDefinition); - if ( - foundComposition && - foundComposition.definitions.some( - (definition) => !getDefinitionTypes(definition).includes('array'), - ) - ) { - return getModel({ - definition: definition.items, - openApi, - parentDefinition: definition, - types, - }); - } - } - - /** - * if items are a plain array, infer any-of composition - * {@link} https://github.com/ferdikoomen/openapi-typescript-codegen/issues/2062 - */ - const arrayItemsDefinition: OpenApiSchema = Array.isArray(definition.items) - ? { - anyOf: definition.items, - } - : definition.items; - const arrayItems = getModel({ - definition: arrayItemsDefinition, - openApi, - parentDefinition: definition, - types, - }); - model.base = arrayItems.base; - model.export = 'array'; - model.$refs = [...model.$refs, ...arrayItems.$refs]; - model.imports = [...model.imports, ...arrayItems.imports]; - model.link = arrayItems; - model.template = arrayItems.template; - model.type = arrayItems.type; - model.default = getDefault(definition, model); - return model; - } - - const foundComposition = findModelComposition(definition); - if (foundComposition) { - const composition = getModelComposition({ - ...foundComposition, - debug, - definition, - getModel, - model, - openApi, - types, - }); - const result = { ...model, ...composition }; - return result; - } - - if ( - definitionTypes.includes('object') || - definition.properties || - definition.additionalProperties - ) { - if ( - definition.properties && - (Object.keys(definition.properties).length > 0 || - !definition.additionalProperties) - ) { - model.base = 'unknown'; - model.export = 'interface'; - model.type = 'unknown'; - model.default = getDefault(definition, model); - - const modelProperties = getModelProperties({ - debug, - definition, - getModel, - openApi, - parent: model, - types, - }); - modelProperties.forEach((modelProperty) => { - model.$refs = [...model.$refs, ...modelProperty.$refs]; - model.enums = [...model.enums, ...modelProperty.enums]; - model.imports = [...model.imports, ...modelProperty.imports]; - model.properties = [...model.properties, modelProperty]; - if (modelProperty.export === 'enum') { - model.enums = [...model.enums, modelProperty]; - } - }); - - if (definition.additionalProperties) { - const modelProperty = getAdditionalPropertiesModel({ - debug, - definition, - getModel, - model, - openApi, - types, - }); - model.properties = [...model.properties, modelProperty]; - } - - // objects with no explicit properties accept any key/value pair - if ( - !model.properties.length && - model.base === 'unknown' && - model.type === 'unknown' - ) { - model.export = 'dictionary'; - if (!model.name) { - model.name = '[key: string]'; - } - } - - return model; - } - - const result = getAdditionalPropertiesModel({ - debug, - definition, - getModel, - model, - openApi, - types, - }); - return result; - } - - if (definition.const !== undefined) { - const definitionConst = definition.const; - const modelConst = - typeof definitionConst === 'string' - ? `"${definitionConst}"` - : `${definitionConst}`; - model.base = modelConst; - model.export = 'const'; - model.type = modelConst; - return model; - } - - // If the schema has a type than it can be a basic or generic type. - if (definitionTypes.length) { - const definitionType = getType({ - format: definition.format, - type: definition.type, - }); - model.base = definitionType.base; - model.export = 'generic'; - model.$refs = [...model.$refs, ...definitionType.$refs]; - model.imports = [...model.imports, ...definitionType.imports]; - model.isNullable = definitionType.isNullable || model.isNullable; - model.template = definitionType.template; - model.type = definitionType.type; - model.default = getDefault(definition, model); - return model; - } - - return model; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getModelComposition.ts b/packages/openapi-ts/src/openApi/v3/parser/getModelComposition.ts deleted file mode 100644 index ca63a28a9..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getModelComposition.ts +++ /dev/null @@ -1,179 +0,0 @@ -import type { - Model, - ModelComposition, -} from '~/openApi/common/interfaces/client'; - -import type { Client } from '../../../types/client'; -import type { GetModelFn } from '../interfaces/Model'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { getModelProperties } from './getModelProperties'; -import { getRequiredPropertiesFromComposition } from './getRequiredPropertiesFromComposition'; - -type Composition = { - definitions: OpenApiSchema[]; - type: ModelComposition['export']; -}; - -export const findModelComposition = ( - definition: OpenApiSchema, -): Composition | undefined => { - const compositions: ReadonlyArray<{ - definitions: Composition['definitions'] | undefined; - type: Composition['type']; - }> = [ - { - definitions: definition.allOf, - type: 'all-of', - }, - { - definitions: definition.anyOf, - type: 'any-of', - }, - { - definitions: definition.oneOf, - type: 'one-of', - }, - ]; - return compositions.find( - (composition) => composition.definitions?.length, - ) as ReturnType; -}; - -export const getModelComposition = ({ - debug, - definition, - definitions, - getModel, - model, - openApi, - type, - types, -}: Composition & - Pick & { - debug?: boolean; - definition: OpenApiSchema; - getModel: GetModelFn; - model: Model; - openApi: OpenApi; - }): ModelComposition => { - const composition: ModelComposition = { - $refs: model.$refs, - enums: model.enums, - export: type, - imports: model.imports, - properties: model.properties, - }; - - let properties: Model[] = []; - - definitions - .map((def) => { - const modelFromDef = getModel({ - debug, - definition: def, - openApi, - parentDefinition: definition, - types, - }); - return modelFromDef; - }) - .forEach((model) => { - composition.$refs = [...composition.$refs, ...model.$refs]; - composition.imports = [...composition.imports, ...model.imports]; - composition.enums = [...composition.enums, ...model.enums]; - composition.properties = [...composition.properties, model]; - }); - - if (definition.required && type === 'all-of') { - const requiredProperties = getRequiredPropertiesFromComposition({ - debug, - definitions, - getModel, - openApi, - required: definition.required, - types, - }); - requiredProperties.forEach((requiredProperty) => { - composition.$refs = [...composition.$refs, ...requiredProperty.$refs]; - composition.imports = [ - ...composition.imports, - ...requiredProperty.imports, - ]; - composition.enums = [...composition.enums, ...requiredProperty.enums]; - }); - properties = [...properties, ...requiredProperties]; - } - - if (definition.properties) { - const modelProperties = getModelProperties({ - definition, - getModel, - openApi, - types, - }); - modelProperties.forEach((modelProperty) => { - composition.$refs = [...composition.$refs, ...modelProperty.$refs]; - composition.imports = [...composition.imports, ...modelProperty.imports]; - composition.enums = [...composition.enums, ...modelProperty.enums]; - if (modelProperty.export === 'enum') { - composition.enums = [...composition.enums, modelProperty]; - } - }); - properties = [...properties, ...modelProperties]; - } - - if (properties.length) { - const foundComposition = findModelComposition(definition); - if (foundComposition) { - const propertiesProperty: Model = { - $refs: [], - base: 'unknown', - description: '', - enum: [], - enums: [], - export: 'interface', - imports: [], - in: '', - isDefinition: false, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: 'properties', - properties, - template: null, - type: 'unknown', - }; - - if (foundComposition.type === 'one-of') { - composition.properties = [ - { - ...composition, - base: '', - description: null, - enum: [], - in: '', - isDefinition: false, - isNullable: false, - isReadOnly: false, - isRequired: true, - link: null, - name: '', - template: null, - type: '', - }, - propertiesProperty, - ]; - composition.export = 'all-of'; - } else { - composition.properties = [ - ...composition.properties, - propertiesProperty, - ]; - } - } - } - - return composition; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getModelProperties.ts b/packages/openapi-ts/src/openApi/v3/parser/getModelProperties.ts deleted file mode 100644 index 83f69aeb9..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getModelProperties.ts +++ /dev/null @@ -1,211 +0,0 @@ -import type { Model } from '~/openApi/common/interfaces/client'; -import { getDefault } from '~/openApi/common/parser/getDefault'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getType } from '~/openApi/common/parser/type'; -import { escapeName } from '~/utils/escape'; -import { unique } from '~/utils/unique'; - -import type { Client } from '../../../types/client'; -import type { GetModelFn } from '../interfaces/Model'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { - findOneOfParentDiscriminator, - mapPropertyValue, -} from './discriminator'; -import { isDefinitionNullable } from './inferType'; - -export const getAdditionalPropertiesModel = ({ - debug, - definition, - getModel, - model, - openApi, - types, -}: { - debug?: boolean; - definition: OpenApiSchema; - getModel: GetModelFn; - model: Model; - openApi: OpenApi; - types: Client['types']; -}): Model => { - const ap = - typeof definition.additionalProperties === 'object' - ? definition.additionalProperties - : {}; - const apModel = getModel({ - debug, - definition: ap, - openApi, - parentDefinition: definition, - types, - }); - - if (ap.$ref) { - const apType = getType({ type: ap.$ref }); - model.base = apType.base; - model.default = getDefault(definition, model); - model.export = 'dictionary'; - model.imports.push(...apType.imports); - model.template = apType.template; - model.type = apType.type; - return model; - } - - if ( - definition.additionalProperties && - definition.properties && - Object.keys(definition.properties).length > 0 - ) { - const additionalPropertiesType = - typeof definition.additionalProperties === 'object' && - definition.additionalProperties.type && - !Array.isArray(definition.additionalProperties.type) - ? definition.additionalProperties.type - : apModel.base; - const additionalProperties = [ - getType({ type: additionalPropertiesType }).base, - ...model.properties.map((property) => property.base), - ]; - apModel.base = additionalProperties.filter(unique).join(' | '); - apModel.default = getDefault(definition, model); - apModel.export = 'generic'; - apModel.isRequired = definition.additionalProperties === true; - apModel.name = '[key: string]'; - return apModel; - } - - model.base = apModel.base; - model.default = getDefault(definition, model); - model.export = 'dictionary'; - model.imports.push(...apModel.imports); - model.link = apModel; - model.template = apModel.template; - model.type = apModel.type; - return model; -}; - -export const getModelProperties = ({ - debug, - definition, - getModel, - openApi, - parent, - types, -}: { - debug?: boolean; - definition: OpenApiSchema; - getModel: GetModelFn; - openApi: OpenApi; - parent?: Model; - types: Client['types']; -}): Model[] => { - let models: Model[] = []; - const discriminator = findOneOfParentDiscriminator(openApi, parent); - - Object.entries(definition.properties ?? {}).forEach( - ([propertyName, property]) => { - const propertyRequired = Boolean( - definition.required?.includes(propertyName), - ); - - const propertyValues: Omit< - Model, - | '$refs' - | 'base' - | 'enum' - | 'enums' - | 'export' - | 'imports' - | 'isNullable' - | 'link' - | 'properties' - | 'template' - | 'type' - > = { - default: property.default, - deprecated: property.deprecated === true, - description: property.description || null, - exclusiveMaximum: property.exclusiveMaximum, - exclusiveMinimum: property.exclusiveMinimum, - format: - property.type === 'array' - ? (property.items?.format ?? property.format) - : property.format, - in: '', - isDefinition: false, - isReadOnly: property.readOnly === true, - isRequired: propertyRequired, - maxItems: property.maxItems, - maxLength: property.maxLength, - maxProperties: property.maxProperties, - maximum: property.maximum, - minItems: property.minItems, - minLength: property.minLength, - minProperties: property.minProperties, - minimum: property.minimum, - multipleOf: property.multipleOf, - name: escapeName(propertyName), - pattern: getPattern(property.pattern), - uniqueItems: property.uniqueItems, - }; - - if (parent && discriminator?.propertyName == propertyName) { - models = [ - ...models, - { - ...propertyValues, - $refs: [], - base: `'${mapPropertyValue(discriminator, parent)}'`, - enum: [], - enums: [], - export: 'reference', - imports: [], - isNullable: isDefinitionNullable(property), - link: null, - properties: [], - template: null, - type: 'string', - }, - ]; - return; - } - - if (property.$ref) { - const model = getType({ type: property.$ref }); - models = [ - ...models, - { - ...propertyValues, - $refs: model.$refs, - base: model.base, - enum: [], - enums: [], - export: 'reference', - imports: model.imports, - isNullable: model.isNullable || isDefinitionNullable(property), - link: null, - properties: [], - template: model.template, - type: model.type, - }, - ]; - return; - } - - const model = getModel({ - debug, - definition: property, - initialValues: propertyValues, - openApi, - parentDefinition: definition, - types, - }); - model.isNullable = model.isNullable || isDefinitionNullable(property); - models = [...models, model]; - }, - ); - - return models; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getModels.ts b/packages/openapi-ts/src/openApi/v3/parser/getModels.ts deleted file mode 100644 index 9d19db258..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getModels.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { getParametersMeta, getSchemasMeta } from '~/utils/meta'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import { getModel } from './getModel'; -import { getParameterSchema } from './parameter'; - -export const getModels = ( - openApi: OpenApi, -): Pick => { - const types: Client['types'] = {}; - let models: Client['models'] = []; - - if (!openApi.components) { - return { - models, - types, - }; - } - - Object.entries(openApi.components.schemas ?? {}).forEach( - ([definitionName, definition]) => { - const meta = getSchemasMeta(definitionName); - types[meta.name] = meta; - const model = getModel({ - definition, - isDefinition: true, - meta, - openApi, - types, - }); - models = [...models, model]; - }, - ); - - Object.entries(openApi.components.parameters ?? {}).forEach( - ([definitionName, definition]) => { - const schema = getParameterSchema(definition); - if (!schema) { - return; - } - - const meta = getParametersMeta(definitionName); - types[meta.name] = meta; - const model = getModel({ - definition: schema, - isDefinition: true, - meta, - openApi, - types, - }); - model.deprecated = definition.deprecated; - model.description = definition.description || null; - models = [...models, model]; - }, - ); - - return { - models, - types, - }; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getOperationParameter.ts b/packages/openapi-ts/src/openApi/v3/parser/getOperationParameter.ts deleted file mode 100644 index 6289c6038..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getOperationParameter.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { OperationParameter } from '~/openApi/common/interfaces/client'; -import { getDefault } from '~/openApi/common/parser/getDefault'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { operationParameterNameFn } from '~/openApi/common/parser/operation'; -import { getType } from '~/openApi/common/parser/type'; -import { refParametersPartial } from '~/utils/const'; -import { enumMeta } from '~/utils/enum'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiParameter } from '../interfaces/OpenApiParameter'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { getModel } from './getModel'; -import { isDefinitionNullable } from './inferType'; -import { getParameterSchema } from './parameter'; - -export const getOperationParameter = ({ - openApi, - parameter, - types, -}: { - openApi: OpenApi; - parameter: OpenApiParameter; - types: Client['types']; -}): OperationParameter => { - const operationParameterWithoutName: Omit = { - $refs: [], - base: 'unknown', - deprecated: parameter.deprecated === true, - description: parameter.description || null, - enum: [], - enums: [], - export: 'interface', - imports: [], - in: parameter.in, - isDefinition: false, - isNullable: isDefinitionNullable(parameter), - isReadOnly: false, - isRequired: parameter.required === true, - link: null, - mediaType: null, - prop: parameter.name, - properties: [], - template: null, - type: 'unknown', - }; - let operationParameter = { - ...operationParameterWithoutName, - name: operationParameterNameFn(operationParameterWithoutName), - }; - - if (parameter.$ref) { - const model = getType({ type: parameter.$ref }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - export: 'reference', - imports: [...operationParameter.imports, ...model.imports], - template: model.template, - type: model.type, - }; - return operationParameter; - } - - let schema = getParameterSchema(parameter); - if (schema) { - if (schema.$ref?.startsWith(refParametersPartial)) { - schema = getRef(openApi, schema); - } - - if (schema.$ref) { - const model = getType({ type: schema.$ref }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - export: 'reference', - imports: [...operationParameter.imports, ...model.imports], - template: model.template, - type: model.type, - }; - operationParameter.default = getDefault(schema); - return operationParameter; - } - - const model = getModel({ definition: schema, openApi, types }); - operationParameter = { - ...operationParameter, - $refs: [...operationParameter.$refs, ...model.$refs], - base: model.base, - enum: [...operationParameter.enum, ...model.enum], - enums: [...operationParameter.enums, ...model.enums], - exclusiveMaximum: model.exclusiveMaximum, - exclusiveMinimum: model.exclusiveMinimum, - export: model.export, - format: model.format, - imports: [...operationParameter.imports, ...model.imports], - isNullable: operationParameter.isNullable || model.isNullable, - isReadOnly: model.isReadOnly, - isRequired: operationParameter.isRequired || model.isRequired, - link: model.link, - maxItems: model.maxItems, - maxLength: model.maxLength, - maxProperties: model.maxProperties, - maximum: model.maximum, - minItems: model.minItems, - minLength: model.minLength, - minProperties: model.minProperties, - minimum: model.minimum, - multipleOf: model.multipleOf, - pattern: getPattern(model.pattern), - properties: [...operationParameter.properties, ...model.properties], - template: model.template, - type: model.type, - uniqueItems: model.uniqueItems, - }; - if ( - (operationParameter.enum.length || operationParameter.enums.length) && - !operationParameter.meta - ) { - operationParameter.meta = enumMeta(operationParameter); - } - operationParameter.default = model.default; - return operationParameter; - } - - return operationParameter; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getOperationParameters.ts b/packages/openapi-ts/src/openApi/v3/parser/getOperationParameters.ts deleted file mode 100644 index 359106552..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getOperationParameters.ts +++ /dev/null @@ -1,97 +0,0 @@ -import type { OperationParameters } from '~/openApi/common/interfaces/client'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { operationParameterFilterFn } from '~/openApi/common/parser/operation'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiParameter } from '../interfaces/OpenApiParameter'; -import { getOperationParameter } from './getOperationParameter'; - -const allowedIn = ['cookie', 'formData', 'header', 'path', 'query'] as const; - -export const getOperationParameters = ({ - openApi, - parameters, - types, -}: { - openApi: OpenApi; - parameters: OpenApiParameter[]; - types: Client['types']; -}): OperationParameters => { - const operationParameters: OperationParameters = { - $refs: [], - imports: [], - parameters: [], - parametersBody: null, - parametersCookie: [], - parametersForm: [], - parametersHeader: [], - parametersPath: [], - parametersQuery: [], // not used in v3 -> @see requestBody - }; - - parameters.forEach((parameterOrReference) => { - const parameterDef = getRef( - openApi, - parameterOrReference, - ); - const parameter = getOperationParameter({ - openApi, - parameter: parameterDef, - types, - }); - - const skip = !operationParameterFilterFn(parameter); - if (!allowedIn.includes(parameterDef.in) || skip) { - return; - } - - switch (parameterDef.in) { - case 'cookie': - operationParameters.parametersCookie = [ - ...operationParameters.parametersCookie, - parameter, - ]; - break; - case 'formData': - operationParameters.parametersForm = [ - ...operationParameters.parametersForm, - parameter, - ]; - break; - case 'header': - operationParameters.parametersHeader = [ - ...operationParameters.parametersHeader, - parameter, - ]; - break; - case 'path': - operationParameters.parametersPath = [ - ...operationParameters.parametersPath, - parameter, - ]; - break; - case 'query': - operationParameters.parametersQuery = [ - ...operationParameters.parametersQuery, - parameter, - ]; - break; - } - - operationParameters.$refs = [ - ...operationParameters.$refs, - ...parameter.$refs, - ]; - operationParameters.imports = [ - ...operationParameters.imports, - ...parameter.imports, - ]; - operationParameters.parameters = [ - ...operationParameters.parameters, - parameter, - ]; - }); - - return operationParameters; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getOperationRequestBody.ts b/packages/openapi-ts/src/openApi/v3/parser/getOperationRequestBody.ts deleted file mode 100644 index 350f28abd..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getOperationRequestBody.ts +++ /dev/null @@ -1,112 +0,0 @@ -import type { OperationParameter } from '~/openApi/common/interfaces/client'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getType } from '~/openApi/common/parser/type'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiRequestBody } from '../interfaces/OpenApiRequestBody'; -import { getContent } from './getContent'; -import { getModel } from './getModel'; - -export const getOperationRequestBody = ({ - body, - debug, - openApi, - types, -}: { - body: OpenApiRequestBody; - debug?: boolean; - openApi: OpenApi; - types: Client['types']; -}): OperationParameter => { - const name = body['x-body-name'] ?? 'requestBody'; - - const requestBody: OperationParameter = { - $refs: [], - base: 'unknown', - default: undefined, - description: body.description || null, - enum: [], - enums: [], - export: 'interface', - imports: [], - in: 'body', - isDefinition: false, - isNullable: body.nullable === true, - isReadOnly: false, - isRequired: body.required === true, - link: null, - mediaType: null, - name, - prop: name, - properties: [], - template: null, - type: 'unknown', - }; - - if (!body.content) { - return requestBody; - } - - const content = getContent(openApi, body.content); - if (!content) { - return requestBody; - } - - requestBody.mediaType = content.mediaType; - - switch (requestBody.mediaType) { - case 'application/x-www-form-urlencoded': - case 'multipart/form-data': - requestBody.in = 'formData'; - requestBody.name = 'formData'; - requestBody.prop = 'formData'; - break; - } - - if (content.schema.$ref) { - const model = getType({ type: content.schema.$ref }); - requestBody.export = 'reference'; - requestBody.type = model.type; - requestBody.base = model.base; - requestBody.template = model.template; - requestBody.$refs = [...requestBody.$refs, ...model.$refs]; - requestBody.imports = [...requestBody.imports, ...model.imports]; - return requestBody; - } - - const model = getModel({ - debug, - definition: content.schema, - openApi, - types, - }); - requestBody.$refs = [...requestBody.$refs, ...model.$refs]; - requestBody.base = model.base; - requestBody.enum = [...requestBody.enum, ...model.enum]; - requestBody.enums = [...requestBody.enums, ...model.enums]; - requestBody.exclusiveMaximum = model.exclusiveMaximum; - requestBody.exclusiveMinimum = model.exclusiveMinimum; - requestBody.export = model.export; - requestBody.format = model.format; - requestBody.imports = [...requestBody.imports, ...model.imports]; - requestBody.isNullable = requestBody.isNullable || model.isNullable; - requestBody.isReadOnly = model.isReadOnly; - requestBody.isRequired = requestBody.isRequired || model.isRequired; - requestBody.link = model.link; - requestBody.maximum = model.maximum; - requestBody.maxItems = model.maxItems; - requestBody.maxLength = model.maxLength; - requestBody.maxProperties = model.maxProperties; - requestBody.minimum = model.minimum; - requestBody.minItems = model.minItems; - requestBody.minLength = model.minLength; - requestBody.minProperties = model.minProperties; - requestBody.multipleOf = model.multipleOf; - requestBody.pattern = getPattern(model.pattern); - requestBody.properties = [...requestBody.properties, ...model.properties]; - requestBody.template = model.template; - requestBody.type = model.type; - requestBody.uniqueItems = model.uniqueItems; - return requestBody; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getOperationResponse.ts b/packages/openapi-ts/src/openApi/v3/parser/getOperationResponse.ts deleted file mode 100644 index fb022b20f..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getOperationResponse.ts +++ /dev/null @@ -1,118 +0,0 @@ -import type { OperationResponse } from '~/openApi/common/interfaces/client'; -import { getPattern } from '~/openApi/common/parser/getPattern'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { getType } from '~/openApi/common/parser/type'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiResponse } from '../interfaces/OpenApiResponse'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; -import { getContent } from './getContent'; -import { getModel } from './getModel'; - -export const getOperationResponse = ({ - code, - openApi, - response, - types, -}: { - code: OperationResponse['code']; - openApi: OpenApi; - response: OpenApiResponse; - types: Client['types']; -}): OperationResponse => { - const operationResponse: OperationResponse = { - $refs: [], - base: code !== 204 ? 'unknown' : 'void', - code, - description: response.description || null, - enum: [], - enums: [], - export: 'generic', - imports: [], - in: 'response', - isDefinition: false, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: '', - properties: [], - responseTypes: [], - template: null, - type: code !== 204 ? 'unknown' : 'void', - }; - - if (response.content) { - const content = getContent(openApi, response.content); - if (content) { - if (content.schema.$ref?.startsWith('#/components/responses/')) { - content.schema = getRef(openApi, content.schema); - } - - if (content.schema.$ref) { - const model = getType({ type: content.schema.$ref }); - operationResponse.base = model.base; - operationResponse.export = 'reference'; - operationResponse.$refs = [...operationResponse.$refs, ...model.$refs]; - operationResponse.imports = [ - ...operationResponse.imports, - ...model.imports, - ]; - operationResponse.template = model.template; - operationResponse.type = model.type; - return operationResponse; - } - - const model = getModel({ definition: content.schema, openApi, types }); - operationResponse.export = model.export; - operationResponse.type = model.type; - operationResponse.base = model.base; - operationResponse.template = model.template; - operationResponse.link = model.link; - operationResponse.isReadOnly = model.isReadOnly; - operationResponse.isRequired = model.isRequired; - operationResponse.isNullable = model.isNullable; - operationResponse.format = model.format; - operationResponse.maximum = model.maximum; - operationResponse.exclusiveMaximum = model.exclusiveMaximum; - operationResponse.minimum = model.minimum; - operationResponse.exclusiveMinimum = model.exclusiveMinimum; - operationResponse.multipleOf = model.multipleOf; - operationResponse.maxLength = model.maxLength; - operationResponse.minLength = model.minLength; - operationResponse.maxItems = model.maxItems; - operationResponse.minItems = model.minItems; - operationResponse.uniqueItems = model.uniqueItems; - operationResponse.maxProperties = model.maxProperties; - operationResponse.minProperties = model.minProperties; - operationResponse.pattern = getPattern(model.pattern); - operationResponse.$refs = [...operationResponse.$refs, ...model.$refs]; - operationResponse.imports = [ - ...operationResponse.imports, - ...model.imports, - ]; - operationResponse.enum = [...operationResponse.enum, ...model.enum]; - operationResponse.enums = [...operationResponse.enums, ...model.enums]; - operationResponse.properties = [ - ...operationResponse.properties, - ...model.properties, - ]; - return operationResponse; - } - } - - // We support basic properties from response headers, since both - // fetch and XHR client just support string types. - if (response.headers) { - for (const name in response.headers) { - operationResponse.in = 'header'; - operationResponse.name = name; - operationResponse.type = 'string'; - operationResponse.base = 'string'; - return operationResponse; - } - } - - return operationResponse; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getOperationResponses.ts b/packages/openapi-ts/src/openApi/v3/parser/getOperationResponses.ts deleted file mode 100644 index 2719459ba..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getOperationResponses.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { OperationResponse } from '~/openApi/common/interfaces/client'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { - parseResponseStatusCode, - sorterByResponseStatusCode, - tagResponseTypes, -} from '~/openApi/common/parser/operation'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiResponse } from '../interfaces/OpenApiResponse'; -import type { OpenApiResponses } from '../interfaces/OpenApiResponses'; -import { getOperationResponse } from './getOperationResponse'; - -export const getOperationResponses = ({ - openApi, - responses, - types, -}: { - debug?: boolean; - openApi: OpenApi; - responses: OpenApiResponses; - types: Client['types']; -}): OperationResponse[] => { - let operationResponses: OperationResponse[] = []; - - Object.entries(responses).forEach(([responseCode, responseOrReference]) => { - const code = parseResponseStatusCode(responseCode); - if (!code) { - return; - } - - const response = getRef(openApi, responseOrReference); - const operationResponse = getOperationResponse({ - code, - openApi, - response, - types, - }); - operationResponses = [...operationResponses, operationResponse]; - }); - - operationResponses = tagResponseTypes(operationResponses); - - return operationResponses.sort(sorterByResponseStatusCode); -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getOperations.ts b/packages/openapi-ts/src/openApi/v3/parser/getOperations.ts deleted file mode 100644 index fe297f310..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getOperations.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { createOperationKey } from '~/ir/operation'; -import type { Client, Operation } from '~/openApi/common/interfaces/client'; -import { operationFilterFn } from '~/openApi/common/parser/operation'; -import { allowedServiceMethods } from '~/openApi/common/parser/service'; -import { getConfig } from '~/utils/config'; - -import type { OpenApi } from '../interfaces/OpenApi'; -import { getOperationParameters } from './getOperationParameters'; -import { getOperation } from './operation'; - -export const getOperations = ({ - openApi, - types, -}: { - openApi: OpenApi; - types: Client['types']; -}): Operation[] => { - const operationIds = new Map(); - const operations: Operation[] = []; - - const config = getConfig(); - - for (const path in openApi.paths) { - const pathItem = openApi.paths[path]!; - const pathParameters = getOperationParameters({ - openApi, - parameters: pathItem.parameters ?? [], - types, - }); - - for (const name in pathItem) { - const method = name as Lowercase; - - const operationKey = createOperationKey({ - method, - path, - }); - - if (allowedServiceMethods.includes(method)) { - const op = pathItem[method]!; - - if (op.operationId) { - if (operationIds.has(op.operationId)) { - if (config.logs.level !== 'silent') { - console.warn( - `❗️ Duplicate operationId: ${op.operationId} in ${operationKey}. Please ensure your operation IDs are unique. This behavior is not supported and will likely lead to unexpected results.`, - ); - } - } else { - operationIds.set(op.operationId, operationKey); - } - } - - if ( - operationFilterFn({ - config, - operationKey, - }) - ) { - const operation = getOperation({ - method, - op, - openApi, - pathParams: pathParameters, - types, - url: path, - }); - operations.push(operation); - } - } - } - } - - return operations; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getRequiredPropertiesFromComposition.ts b/packages/openapi-ts/src/openApi/v3/parser/getRequiredPropertiesFromComposition.ts deleted file mode 100644 index 6f99f3288..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getRequiredPropertiesFromComposition.ts +++ /dev/null @@ -1,73 +0,0 @@ -import type { Model } from '~/openApi/common/interfaces/client'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { getType } from '~/openApi/common/parser/type'; - -import type { Client } from '../../../types/client'; -import type { GetModelFn } from '../interfaces/Model'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; - -export const getRequiredPropertiesFromComposition = ({ - debug, - definitions, - getModel, - openApi, - required, - types, -}: { - debug?: boolean; - definitions: OpenApiSchema[]; - getModel: GetModelFn; - openApi: OpenApi; - required: string[]; - types: Client['types']; -}): Model[] => { - const requiredProperties = definitions - .reduce((properties, definition) => { - if (definition.$ref) { - const type = getType({ type: definition.$ref }); - // avoid circular references if two refs reference each other - // if (types[type.base] && types[type.base].$ref === definition.$ref) { - // const schema = getRef(openApi, definition); - // return [...properties] - // } - - const meta = { - $ref: definition.$ref, - name: type.base, - }; - types[type.base] = meta; - const schema = getRef(openApi, definition); - return [ - ...properties, - ...getModel({ - debug, - definition: schema, - meta, - openApi, - types, - }).properties, - ]; - } - - return [ - ...properties, - ...getModel({ - debug, - definition, - openApi, - parentDefinition: definition, - types, - }).properties, - ]; - }, [] as Model[]) - .filter( - (property) => !property.isRequired && required.includes(property.name), - ) - .map((property) => ({ - ...property, - isRequired: true, - })); - - return requiredProperties; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/getServer.ts b/packages/openapi-ts/src/openApi/v3/parser/getServer.ts deleted file mode 100644 index 3f74b8ab9..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/getServer.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { OpenApi } from '../interfaces/OpenApi'; - -export const getServer = (openApi: OpenApi): string => { - const server = openApi.servers?.[0]; - const variables = server?.variables || {}; - let url = server?.url || ''; - Object.entries(variables).forEach(([name, variable]) => { - url = url.replace(`{${name}}`, variable.default); - }); - return url.replace(/\/$/g, ''); -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/inferType.ts b/packages/openapi-ts/src/openApi/v3/parser/inferType.ts deleted file mode 100644 index 94583670c..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/inferType.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; - -export const inferType = ( - definition: OpenApiSchema, - definitionTypes: string[], -) => { - if (definition.enum && !definitionTypes.includes('boolean')) { - return 'enum'; - } - return; -}; - -export const isDefinitionTypeNullable = ( - definition: Pick, -) => getDefinitionTypes(definition).includes('null'); - -export const isDefinitionNullable = ( - definition: Pick, -) => definition.nullable === true || isDefinitionTypeNullable(definition); - -export const getDefinitionTypes = ({ type }: Pick) => { - if (Array.isArray(type)) { - return type; - } - if (type) { - return [type]; - } - return []; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/operation.ts b/packages/openapi-ts/src/openApi/v3/parser/operation.ts deleted file mode 100644 index 9ac0bc5e9..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/operation.ts +++ /dev/null @@ -1,182 +0,0 @@ -import type { - Operation, - OperationParameter, - OperationParameters, -} from '~/openApi/common/interfaces/client'; -import { getRef } from '~/openApi/common/parser/getRef'; -import { - getOperationResponseHeader, - operationNameFn, -} from '~/openApi/common/parser/operation'; -import { toSortedByRequired } from '~/openApi/common/parser/sort'; -import { getConfig } from '~/utils/config'; - -import type { Client } from '../../../types/client'; -import type { OpenApi } from '../interfaces/OpenApi'; -import type { OpenApiOperation } from '../interfaces/OpenApiOperation'; -import type { OpenApiRequestBody } from '../interfaces/OpenApiRequestBody'; -import { getOperationParameters } from './getOperationParameters'; -import { getOperationRequestBody } from './getOperationRequestBody'; -import { getOperationResponses } from './getOperationResponses'; - -// add global path parameters, skip duplicate names -const mergeParameters = ( - opParams: OperationParameter[], - globalParams: OperationParameter[], -): OperationParameter[] => { - let mergedParameters = [...opParams]; - let pendingParameters = [...globalParams]; - while (pendingParameters.length > 0) { - const pendingParam = pendingParameters[0]!; - pendingParameters = pendingParameters.slice(1); - const canMerge = mergedParameters.every( - (param) => - param.in !== pendingParam.in || param.name !== pendingParam.name, - ); - if (canMerge) { - mergedParameters = [...mergedParameters, pendingParam]; - } - } - return mergedParameters; -}; - -export const getOperation = ({ - debug, - method, - op, - openApi, - pathParams, - types, - url, -}: { - debug?: boolean; - method: Lowercase; - op: OpenApiOperation; - openApi: OpenApi; - pathParams: OperationParameters; - types: Client['types']; - url: string; -}): Operation => { - const operationWithoutName: Omit = { - $refs: [], - deprecated: Boolean(op.deprecated), - description: op.description || null, - id: op.operationId || null, - imports: [], - method: method.toUpperCase() as Operation['method'], - parameters: [], - parametersBody: pathParams.parametersBody, - parametersCookie: [], - parametersForm: [], - parametersHeader: [], - parametersPath: [], - parametersQuery: [], - path: url, - responseHeader: null, - responses: [], - summary: op.summary || null, - tags: op.tags || null, - }; - const operation = { - ...operationWithoutName, - name: operationNameFn({ - config: getConfig(), - method: operationWithoutName.method, - operationId: op.operationId, - path: operationWithoutName.path, - }), - }; - - if (op.parameters) { - const parameters = getOperationParameters({ - openApi, - parameters: op.parameters, - types, - }); - operation.$refs = [...operation.$refs, ...parameters.$refs]; - operation.imports = [...operation.imports, ...parameters.imports]; - operation.parameters = [...operation.parameters, ...parameters.parameters]; - operation.parametersBody = parameters.parametersBody; - operation.parametersCookie = [ - ...operation.parametersCookie, - ...parameters.parametersCookie, - ]; - operation.parametersForm = [ - ...operation.parametersForm, - ...parameters.parametersForm, - ]; - operation.parametersHeader = [ - ...operation.parametersHeader, - ...parameters.parametersHeader, - ]; - operation.parametersPath = [ - ...operation.parametersPath, - ...parameters.parametersPath, - ]; - operation.parametersQuery = [ - ...operation.parametersQuery, - ...parameters.parametersQuery, - ]; - } - - if (op.requestBody) { - const requestBodyDef = getRef(openApi, op.requestBody); - const requestBody = getOperationRequestBody({ - body: requestBodyDef, - debug, - openApi, - types, - }); - operation.$refs = [...operation.$refs, ...requestBody.$refs]; - operation.imports = [...operation.imports, ...requestBody.imports]; - operation.parameters = [...operation.parameters, requestBody]; - operation.parametersBody = requestBody; - } - - if (op.responses) { - operation.responses = getOperationResponses({ - openApi, - responses: op.responses, - types, - }); - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - - operation.responseHeader = getOperationResponseHeader(successResponses); - - successResponses.forEach((response) => { - operation.$refs = [...operation.$refs, ...response.$refs]; - operation.imports = [...operation.imports, ...response.imports]; - }); - } - - operation.parameters = mergeParameters( - operation.parameters, - pathParams.parameters, - ); - operation.parametersCookie = mergeParameters( - operation.parametersCookie, - pathParams.parametersCookie, - ); - operation.parametersForm = mergeParameters( - operation.parametersForm, - pathParams.parametersForm, - ); - operation.parametersHeader = mergeParameters( - operation.parametersHeader, - pathParams.parametersHeader, - ); - operation.parametersPath = mergeParameters( - operation.parametersPath, - pathParams.parametersPath, - ); - operation.parametersQuery = mergeParameters( - operation.parametersQuery, - pathParams.parametersQuery, - ); - - operation.parameters = toSortedByRequired(operation.parameters); - - return operation; -}; diff --git a/packages/openapi-ts/src/openApi/v3/parser/parameter.ts b/packages/openapi-ts/src/openApi/v3/parser/parameter.ts deleted file mode 100644 index 0f3a41954..000000000 --- a/packages/openapi-ts/src/openApi/v3/parser/parameter.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { OpenApiParameter } from '../interfaces/OpenApiParameter'; -import type { OpenApiSchema } from '../interfaces/OpenApiSchema'; - -export const getParameterSchema = ( - definition: OpenApiParameter, -): OpenApiSchema | undefined => { - if (definition.schema) { - return definition.schema; - } - - if (definition.content) { - // treat every media type the same for now, types should be modified to - // preserve this data so client knows which headers to use and how to - // parse response bodies - const contents = Object.entries(definition.content); - for (const [key, mediaTypeObject] of contents) { - if (mediaTypeObject.schema) { - const mediaType = key as keyof Required['content']; - return definition.content[mediaType].schema; - } - } - } - - return; -}; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/config.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/config.ts deleted file mode 100644 index 7d7064629..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { definePluginConfig } from '~/plugins/shared/utils/config'; - -import type { HeyApiClientLegacyAngularPlugin } from './types'; - -export const defaultConfig: HeyApiClientLegacyAngularPlugin['Config'] = { - config: {}, - handler: () => {}, - name: 'legacy/angular', - output: 'client', - tags: ['client'], -}; - -/** - * Type helper for `legacy/angular` plugin, returns {@link Plugin.Config} object - */ -export const defineConfig = definePluginConfig(defaultConfig); diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/index.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/index.ts deleted file mode 100644 index 4264db3e9..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { defaultConfig, defineConfig } from './config'; -export type { HeyApiClientLegacyAngularPlugin } from './types'; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/types.d.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/types.d.ts deleted file mode 100644 index 9072e138f..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-angular/types.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { DefinePlugin, Plugin } from '~/plugins'; -import type { Client } from '~/plugins/@hey-api/client-core/types'; - -export type UserConfig = Plugin.Name<'legacy/angular'> & - Pick; - -export type HeyApiClientLegacyAngularPlugin = DefinePlugin; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/config.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/config.ts deleted file mode 100644 index 796607fe9..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { definePluginConfig } from '~/plugins/shared/utils/config'; - -import type { HeyApiClientLegacyAxiosPlugin } from './types'; - -export const defaultConfig: HeyApiClientLegacyAxiosPlugin['Config'] = { - config: {}, - handler: () => {}, - name: 'legacy/axios', - output: 'client', - tags: ['client'], -}; - -/** - * Type helper for `legacy/axios` plugin, returns {@link Plugin.Config} object - */ -export const defineConfig = definePluginConfig(defaultConfig); diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/index.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/index.ts deleted file mode 100644 index 9f0d248ab..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { defaultConfig, defineConfig } from './config'; -export type { HeyApiClientLegacyAxiosPlugin } from './types'; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/types.d.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/types.d.ts deleted file mode 100644 index 5022702c8..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-axios/types.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { DefinePlugin, Plugin } from '~/plugins'; -import type { Client } from '~/plugins/@hey-api/client-core/types'; - -export type UserConfig = Plugin.Name<'legacy/axios'> & - Pick; - -export type HeyApiClientLegacyAxiosPlugin = DefinePlugin; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/config.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/config.ts deleted file mode 100644 index 730df72f0..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { definePluginConfig } from '~/plugins/shared/utils/config'; - -import type { HeyApiClientLegacyFetchPlugin } from './types'; - -export const defaultConfig: HeyApiClientLegacyFetchPlugin['Config'] = { - config: {}, - handler: () => {}, - name: 'legacy/fetch', - output: 'client', - tags: ['client'], -}; - -/** - * Type helper for `legacy/fetch` plugin, returns {@link Plugin.Config} object - */ -export const defineConfig = definePluginConfig(defaultConfig); diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/index.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/index.ts deleted file mode 100644 index dbdc1c440..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { defaultConfig, defineConfig } from './config'; -export type { HeyApiClientLegacyFetchPlugin } from './types'; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/types.d.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/types.d.ts deleted file mode 100644 index f6497c47f..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-fetch/types.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { DefinePlugin, Plugin } from '~/plugins'; -import type { Client } from '~/plugins/@hey-api/client-core/types'; - -export type UserConfig = Plugin.Name<'legacy/fetch'> & - Pick; - -export type HeyApiClientLegacyFetchPlugin = DefinePlugin; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-node/config.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-node/config.ts deleted file mode 100644 index 71e7051f0..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-node/config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { definePluginConfig } from '~/plugins/shared/utils/config'; - -import type { HeyApiClientLegacyNodePlugin } from './types'; - -export const defaultConfig: HeyApiClientLegacyNodePlugin['Config'] = { - config: {}, - handler: () => {}, - name: 'legacy/node', - output: 'client', - tags: ['client'], -}; - -/** - * Type helper for `legacy/node` plugin, returns {@link Plugin.Config} object - */ -export const defineConfig = definePluginConfig(defaultConfig); diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-node/index.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-node/index.ts deleted file mode 100644 index a1a22c74e..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-node/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { defaultConfig, defineConfig } from './config'; -export type { HeyApiClientLegacyNodePlugin } from './types'; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-node/types.d.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-node/types.d.ts deleted file mode 100644 index 34a193bd2..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-node/types.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { DefinePlugin, Plugin } from '~/plugins'; -import type { Client } from '~/plugins/@hey-api/client-core/types'; - -export type UserConfig = Plugin.Name<'legacy/node'> & - Pick; - -export type HeyApiClientLegacyNodePlugin = DefinePlugin; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/config.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/config.ts deleted file mode 100644 index 499b222f1..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { definePluginConfig } from '~/plugins/shared/utils/config'; - -import type { HeyApiClientLegacyXhrPlugin } from './types'; - -export const defaultConfig: HeyApiClientLegacyXhrPlugin['Config'] = { - config: {}, - handler: () => {}, - name: 'legacy/xhr', - output: 'client', - tags: ['client'], -}; - -/** - * Type helper for `legacy/xhr` plugin, returns {@link Plugin.Config} object - */ -export const defineConfig = definePluginConfig(defaultConfig); diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/index.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/index.ts deleted file mode 100644 index 4a279bffd..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { defaultConfig, defineConfig } from './config'; -export type { HeyApiClientLegacyXhrPlugin } from './types'; diff --git a/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/types.d.ts b/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/types.d.ts deleted file mode 100644 index 9cad4e080..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/legacy-xhr/types.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { DefinePlugin, Plugin } from '~/plugins'; -import type { Client } from '~/plugins/@hey-api/client-core/types'; - -export type UserConfig = Plugin.Name<'legacy/xhr'> & - Pick; - -export type HeyApiClientLegacyXhrPlugin = DefinePlugin; diff --git a/packages/openapi-ts/src/plugins/@hey-api/schemas/__tests__/schemas.test.ts b/packages/openapi-ts/src/plugins/@hey-api/schemas/__tests__/schemas.test.ts deleted file mode 100644 index 589c8ae06..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/schemas/__tests__/schemas.test.ts +++ /dev/null @@ -1,348 +0,0 @@ -import fs from 'node:fs'; - -import { Project } from '@hey-api/codegen-core'; -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import { client, openApi } from '~/generate/__tests__/mocks'; -import type { OpenApiV3Schema } from '~/openApi'; -import { PluginInstance } from '~/plugins/shared/utils/instance'; -import type { Files } from '~/types/utils'; -import { setConfig } from '~/utils/config'; - -import { handlerLegacy } from '../plugin-legacy'; - -vi.mock('node:fs'); - -describe('generateLegacySchemas', () => { - it('writes to filesystem', async () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - name: 'AppClient', - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - if ('openapi' in openApi) { - openApi.components = { - schemas: { - foo: { - type: 'object', - }, - }, - }; - } - - const files: Files = {}; - - await handlerLegacy({ - client, - files, - openApi, - plugin: new PluginInstance({ - config: { - exportFromIndex: false, - }, - context: { - config: { - // @ts-expect-error - parser: { - hooks: {}, - }, - }, - }, - dependencies: [], - gen: new Project({ - renderers: {}, - root: '.tmp', - }), - handler: () => {}, - name: '@hey-api/schemas', - output: 'schemas', - }), - }); - - files.schemas!.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining('schemas.gen.ts'), - expect.anything(), - ); - }); - - it('uses custom schema name', async () => { - const nameFn = vi.fn().mockReturnValue('customName'); - - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - name: 'AppClient', - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - nameBuilder: nameFn, - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - const schema: OpenApiV3Schema = { - type: 'object', - }; - - if ('openapi' in openApi) { - openApi.components = { - schemas: { - foo: schema, - }, - }; - } - - const files: Files = {}; - - await handlerLegacy({ - client, - files, - openApi, - plugin: new PluginInstance({ - config: { - exportFromIndex: false, - }, - context: { - config: { - // @ts-expect-error - parser: { - hooks: {}, - }, - }, - }, - dependencies: [], - gen: new Project({ - renderers: {}, - root: '.tmp', - }), - handler: () => {}, - name: '@hey-api/schemas', - output: 'schemas', - }), - }); - - files.schemas!.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining('schemas.gen.ts'), - expect.anything(), - ); - - expect(nameFn).toHaveBeenCalledWith('foo', schema); - }); -}); diff --git a/packages/openapi-ts/src/plugins/@hey-api/schemas/config.ts b/packages/openapi-ts/src/plugins/@hey-api/schemas/config.ts index 57d6f8642..c472fc93e 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/schemas/config.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/schemas/config.ts @@ -2,7 +2,6 @@ import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; import { handler } from './plugin'; -import { handlerLegacy } from './plugin-legacy'; import type { HeyApiSchemasPlugin } from './types'; export const defaultConfig: HeyApiSchemasPlugin['Config'] = { @@ -13,7 +12,6 @@ export const defaultConfig: HeyApiSchemasPlugin['Config'] = { type: 'json', }, handler, - handlerLegacy, name: '@hey-api/schemas', }; diff --git a/packages/openapi-ts/src/plugins/@hey-api/schemas/plugin-legacy.ts b/packages/openapi-ts/src/plugins/@hey-api/schemas/plugin-legacy.ts deleted file mode 100644 index ed0a5ebac..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/schemas/plugin-legacy.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { GeneratedFile } from '~/generate/file'; -import type { OpenApiV2Schema, OpenApiV3Schema } from '~/openApi'; -import { ensureValidTypeScriptJavaScriptIdentifier } from '~/openApi'; -import { tsc } from '~/tsc'; -import { getConfig } from '~/utils/config'; - -import type { HeyApiSchemasPlugin } from './types'; - -const ensureValidSchemaOutput = ( - schema: unknown, - parentKey?: string, -): object => { - const config = getConfig(); - - if (Array.isArray(schema)) { - return schema.map((item) => ensureValidSchemaOutput(item)); - } - - if (typeof schema !== 'object' || schema === null) { - return schema as object; - } - - const result = { ...schema }; - Object.entries(result).forEach(([key, value]) => { - if (config.plugins['@hey-api/schemas']?.config.type === 'form') { - if ( - [ - 'description', - 'x-enum-descriptions', - 'x-enum-varnames', - 'x-enumNames', - 'title', - ].includes(key) && - parentKey !== 'properties' - ) { - // @ts-expect-error - delete result[key]; - return; - } - } - - // refs are encoded probably by json-schema-ref-parser, didn't investigate - // further - if (key === '$ref' && typeof value === 'string') { - // @ts-expect-error - result[key] = decodeURIComponent(value); - } - - if (value && typeof value === 'object') { - // @ts-expect-error - result[key] = ensureValidSchemaOutput(value, key); - } - }); - return result; -}; - -const toSchemaName = ( - name: string, - schema: OpenApiV2Schema | OpenApiV3Schema, -): string => { - const config = getConfig(); - - const validName = ensureValidTypeScriptJavaScriptIdentifier(name); - - const plugin = config.plugins['@hey-api/schemas']; - - if (plugin?.config.nameBuilder) { - if (typeof plugin.config.nameBuilder === 'function') { - return plugin.config.nameBuilder(validName, schema); - } else { - return plugin.config.nameBuilder.replace('{{name}}', validName); - } - } - - return `${validName}Schema`; -}; - -export const handlerLegacy: HeyApiSchemasPlugin['LegacyHandler'] = ({ - files, - openApi, - plugin, -}) => { - const config = getConfig(); - - files.schemas = new GeneratedFile({ - dir: config.output.path, - exportFromIndex: plugin.config.exportFromIndex, - id: 'schemas', - name: 'schemas.ts', - }); - - const addSchema = ( - name: string, - schema: OpenApiV2Schema | OpenApiV3Schema, - ) => { - const obj = ensureValidSchemaOutput(schema); - const expression = tsc.objectExpression({ obj }); - const statement = tsc.constVariable({ - assertion: 'const', - exportConst: true, - expression, - name: toSchemaName(name, schema), - }); - files.schemas!.add(statement); - }; - - // OpenAPI 2.0 - if ('swagger' in openApi) { - Object.entries(openApi.definitions ?? {}).forEach(([name, definition]) => { - addSchema(name, definition); - }); - } - - // OpenAPI 3.x - if ('openapi' in openApi) { - Object.entries(openApi.components?.schemas ?? {}).forEach( - ([name, schema]) => { - addSchema(name, schema); - }, - ); - } -}; diff --git a/packages/openapi-ts/src/plugins/@hey-api/schemas/types.d.ts b/packages/openapi-ts/src/plugins/@hey-api/schemas/types.d.ts index 87af061fc..fe53bd0cb 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/schemas/types.d.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/schemas/types.d.ts @@ -1,4 +1,3 @@ -import type { OpenApiV2Schema, OpenApiV3Schema } from '~/openApi'; import type { OpenApiV2_0_XTypes } from '~/openApi/2.0.x'; import type { OpenApiV3_0_XTypes } from '~/openApi/3.0.x'; import type { OpenApiV3_1_XTypes } from '~/openApi/3.1.x'; @@ -27,8 +26,6 @@ export type UserConfig = Plugin.Name<'@hey-api/schemas'> & | (( name: string, schema: - | OpenApiV2Schema - | OpenApiV3Schema | OpenApiV2_0_XTypes['SchemaObject'] | OpenApiV3_0_XTypes['ReferenceObject'] | OpenApiV3_0_XTypes['SchemaObject'] diff --git a/packages/openapi-ts/src/plugins/@hey-api/sdk/__tests__/plugin.test.ts b/packages/openapi-ts/src/plugins/@hey-api/sdk/__tests__/plugin.test.ts deleted file mode 100644 index e03e4d0a3..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/sdk/__tests__/plugin.test.ts +++ /dev/null @@ -1,738 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import { Project } from '@hey-api/codegen-core'; -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import { openApi } from '~/generate/__tests__/mocks'; -import { GeneratedFile } from '~/generate/file'; -import { PluginInstance } from '~/plugins/shared/utils/instance'; -import type { Operation } from '~/types/client'; -import type { Config } from '~/types/config'; -import type { Files } from '~/types/utils'; -import { setConfig } from '~/utils/config'; - -import { handlerLegacy } from '../plugin-legacy'; - -vi.mock('node:fs'); - -describe('handlerLegacy', () => { - it('writes to filesystem', async () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - asClass: true, - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }); - - const client: Parameters[0]['client'] = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [ - { - $refs: [], - imports: [], - name: 'User', - operations: [ - { - $refs: [], - deprecated: false, - description: null, - id: null, - imports: [], - method: 'GET', - name: '', - parameters: [], - parametersBody: null, - parametersCookie: [], - parametersForm: [], - parametersHeader: [], - parametersPath: [], - parametersQuery: [], - path: '/api/v1/foo', - responseHeader: null, - responses: [], - service: '', - summary: null, - }, - ], - }, - ], - types: {}, - version: 'v1', - }; - - const files: Files = {}; - - files.types = new GeneratedFile({ - dir: '/', - id: 'types', - name: 'types.ts', - }); - - await handlerLegacy({ - client, - files, - openApi, - plugin: new PluginInstance({ - config: { - exportFromIndex: false, - }, - context: { - config: { - // @ts-expect-error - parser: { - hooks: {}, - }, - }, - }, - dependencies: [], - gen: new Project({ - renderers: {}, - root: '.tmp', - }), - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }), - }); - - files.sdk!.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining(path.resolve('sdk.gen.ts')), - expect.anything(), - ); - }); -}); - -describe('methodNameBuilder', () => { - // If the generated text has the expected method, tests are considered pass. - - const operation: Operation = { - $refs: [], - deprecated: false, - description: null, - id: 'User_get', - imports: [], - method: 'GET', - name: 'userGet', - parameters: [], - parametersBody: null, - parametersCookie: [], - parametersForm: [], - parametersHeader: [], - parametersPath: [], - parametersQuery: [], - path: '/users', - responseHeader: null, - responses: [], - service: 'User', - summary: null, - }; - - const client: Parameters[0]['client'] = { - config: {} as Config, - models: [], - server: 'http://localhost:8080', - services: [ - { - $refs: [], - imports: [], - name: 'User', - operations: [operation], - }, - ], - types: {}, - version: 'v1', - }; - - it('use default name', async () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - asClass: true, - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }); - - const files: Files = {}; - - files.types = new GeneratedFile({ - dir: '/', - id: 'types', - name: 'types.ts', - }); - - await handlerLegacy({ - client, - files, - openApi, - plugin: new PluginInstance({ - config: { - exportFromIndex: false, - }, - context: { - config: { - // @ts-expect-error - parser: { - hooks: {}, - }, - }, - }, - dependencies: [], - gen: new Project({ - renderers: {}, - root: '.tmp', - }), - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }), - }); - - files.sdk!.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining(path.resolve('sdk.gen.ts')), - expect.stringContaining('public static userGet()'), - ); - }); - - it('use methodNameBuilder when asClass is true', async () => { - const methodNameBuilder = vi.fn().mockReturnValue('customName'); - - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - asClass: true, - methodNameBuilder, - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }); - - const files: Files = {}; - - files.types = new GeneratedFile({ - dir: '/', - id: 'types', - name: 'types.ts', - }); - - await handlerLegacy({ - client, - files, - openApi, - plugin: new PluginInstance({ - config: { - exportFromIndex: false, - }, - context: { - config: { - // @ts-expect-error - parser: { - hooks: {}, - }, - }, - }, - dependencies: [], - gen: new Project({ - renderers: {}, - root: '.tmp', - }), - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }), - }); - - files.sdk!.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining(path.resolve('sdk.gen.ts')), - expect.stringContaining('public static customName()'), - ); - - expect(methodNameBuilder).toHaveBeenCalledWith(operation); - }); - - it('use methodNameBuilder when asClass is false', async () => { - const methodNameBuilder = vi.fn().mockReturnValue('customName'); - - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - asClass: false, - methodNameBuilder, - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }); - - const files: Files = {}; - - files.types = new GeneratedFile({ - dir: '/', - id: 'types', - name: 'types.ts', - }); - - await handlerLegacy({ - client, - files, - openApi, - plugin: new PluginInstance({ - config: { - exportFromIndex: false, - }, - context: { - config: { - // @ts-expect-error - parser: { - hooks: {}, - }, - }, - }, - dependencies: [], - gen: new Project({ - renderers: {}, - root: '.tmp', - }), - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }), - }); - - files.sdk!.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining(path.resolve('sdk.gen.ts')), - expect.stringContaining('public static customName()'), - ); - - expect(methodNameBuilder).toHaveBeenCalledWith(operation); - }); -}); diff --git a/packages/openapi-ts/src/plugins/@hey-api/sdk/config.ts b/packages/openapi-ts/src/plugins/@hey-api/sdk/config.ts index c1bce3e62..8000cf8d7 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/sdk/config.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/sdk/config.ts @@ -2,7 +2,6 @@ import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; import { handler } from './plugin'; -import { handlerLegacy } from './plugin-legacy'; import type { HeyApiSdkPlugin } from './types'; export const defaultConfig: HeyApiSdkPlugin['Config'] = { @@ -24,7 +23,6 @@ export const defaultConfig: HeyApiSdkPlugin['Config'] = { }, dependencies: ['@hey-api/typescript'], handler, - handlerLegacy, name: '@hey-api/sdk', resolveConfig: (plugin, context) => { if (plugin.config.client) { diff --git a/packages/openapi-ts/src/plugins/@hey-api/sdk/plugin-legacy.ts b/packages/openapi-ts/src/plugins/@hey-api/sdk/plugin-legacy.ts deleted file mode 100644 index 0ed757f26..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/sdk/plugin-legacy.ts +++ /dev/null @@ -1,942 +0,0 @@ -import type ts from 'typescript'; - -import { clientModulePath } from '~/generate/client'; -import { GeneratedFile } from '~/generate/file'; -import type { IR } from '~/ir/types'; -import { isOperationParameterRequired } from '~/openApi'; -import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; -import type { Comments, FunctionParameter } from '~/tsc'; -import { tsc } from '~/tsc'; -import type { FunctionTypeParameter, ObjectValue } from '~/tsc/types'; -import type { - Client, - Model, - Operation, - OperationParameter, - Service, -} from '~/types/client'; -import type { Config as ClientConfig } from '~/types/config'; -import { - getConfig, - isLegacyClient, - legacyNameFromConfig, -} from '~/utils/config'; -import { escapeComment, escapeName } from '~/utils/escape'; -import { reservedJavaScriptKeywordsRegExp } from '~/utils/regexp'; -import { stringCase } from '~/utils/stringCase'; -import { transformClassName } from '~/utils/transform'; -import { setUniqueTypeName } from '~/utils/type'; -import { unique } from '~/utils/unique'; - -import type { HeyApiSdkPlugin } from './types'; - -type OnNode = (node: ts.Node) => void; -type OnImport = (name: string) => void; - -export const generateImport = ({ - meta, - onImport, - ...setUniqueTypeNameArgs -}: Pick[0], 'client' | 'nameTransformer'> & - Pick & { - onImport: OnImport; - }) => { - // generate imports only for top-level models - if (!meta) { - // TODO: this used to return undefined. We could refactor this function to - // return undefined again, but we will need to improve types so we can safely - // do `const { name } = generateImport({ meta: ... })` (note when meta is defined - // we guarantee the response to be an object). For now, nothing relies on this - // response shape except for plugins, so it was acceptable to patch it that way - return { created: false, name: '' }; - } - - const { created, name } = setUniqueTypeName({ - meta, - ...setUniqueTypeNameArgs, - }); - if (name) { - onImport(name); - } - return { created, name }; -}; - -export const modelResponseTransformerTypeName = (name: string) => - `${name}ModelResponseTransformer`; - -export const operationDataTypeName = (name: string) => - `${stringCase({ - case: 'PascalCase', - value: name, - })}Data`; - -export const operationErrorTypeName = (name: string) => - `${stringCase({ - case: 'PascalCase', - value: name, - })}Error`; - -// operation response type ends with "Response", it's enough to append "Transformer" -export const operationResponseTransformerTypeName = (name: string) => - `${name}Transformer`; - -export const operationResponseTypeName = (name: string) => - `${stringCase({ - case: 'PascalCase', - value: name, - })}Response`; - -/** - * @param importedType unique type name returned from `setUniqueTypeName()` - * @returns options type - */ -export const operationOptionsLegacyParserType = ({ - importedType, - throwOnError, -}: { - importedType?: string | false; - throwOnError?: string; -}) => { - const optionsName = 'OptionsLegacyParser'; - // TODO: refactor this to be more generic, works for now - if (throwOnError) { - return `${optionsName}<${importedType || 'unknown'}, ${throwOnError}>`; - } - return importedType ? `${optionsName}<${importedType}>` : optionsName; -}; - -const toOperationParamType = ( - client: Client, - operation: Operation, -): FunctionParameter[] => { - const config = getConfig(); - - const { name: importedType } = setUniqueTypeName({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationDataTypeName, - }); - - const isRequired = isOperationParameterRequired(operation.parameters); - - if (!isLegacyClient(config)) { - return [ - { - isRequired, - name: 'options', - type: operationOptionsLegacyParserType({ - importedType, - throwOnError: 'ThrowOnError', - }), - }, - ]; - } - - if (!operation.parameters.length) { - return []; - } - - const getDefaultPrintable = ( - p: OperationParameter | Model, - ): string | undefined => { - if (p.default === undefined) { - return; - } - return JSON.stringify(p.default, null, 4); - }; - - // legacy configuration - if (!config.useOptions) { - return operation.parameters.map((p) => { - const typePath = `${importedType}['${p.name}']`; - return { - default: p?.default, - isRequired: - (!p.isRequired && !getDefaultPrintable(p) ? '?' : '') === '', - name: p.name, - type: typePath, - }; - }); - } - - return [ - { - default: isRequired ? undefined : {}, - name: 'data', - type: importedType, - }, - ]; -}; - -const toOperationReturnType = (client: Client, operation: Operation) => { - const config = getConfig(); - - let returnType = tsc.typeNode('void'); - - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - - // TODO: we should return nothing when successes don't exist - // can't remove this logic without removing request/name config - // as it complicates things - if (successResponses.length) { - const { name: importedType } = setUniqueTypeName({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationResponseTypeName, - }); - returnType = tsc.typeUnionNode({ - types: [importedType], - }); - } - - if ( - config.useOptions && - config.plugins['@hey-api/sdk']?.config.response === 'response' - ) { - returnType = tsc.typeNode('ApiResult', [returnType]); - } - - const clientPlugin = getClientPlugin(config); - if (clientPlugin.name === 'legacy/angular') { - returnType = tsc.typeNode('Observable', [returnType]); - } else { - returnType = tsc.typeNode('CancelablePromise', [returnType]); - } - - return returnType; -}; - -const toOperationComment = (operation: Operation): Comments => { - const config = getConfig(); - - if (!isLegacyClient(config)) { - const comment = [ - operation.deprecated && '@deprecated', - operation.summary && escapeComment(operation.summary), - operation.description && escapeComment(operation.description), - ]; - return comment; - } - - let params: string[] = []; - - if (operation.parameters.length) { - if (config.useOptions) { - params = [ - '@param data The data for the request.', - ...operation.parameters.map( - (parameter) => - `@param data.${parameter.name} ${parameter.description ? escapeComment(parameter.description) : ''}`, - ), - ]; - } else { - params = operation.parameters.map( - (parameter) => - `@param ${parameter.name} ${parameter.description ? escapeComment(parameter.description) : ''}`, - ); - } - } - - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - - const comment = [ - operation.deprecated && '@deprecated', - operation.summary && escapeComment(operation.summary), - operation.description && escapeComment(operation.description), - ...params, - ...successResponses.map( - (response) => - `@returns ${response.type} ${response.description ? escapeComment(response.description) : ''}`, - ), - '@throws ApiError', - ]; - return comment; -}; - -const toRequestOptions = ({ - client, - onClientImport, - onImport, - operation, -}: { - client: Client; - onClientImport: OnImport | undefined; - onImport: OnImport; - operation: Operation; -}) => { - const config = getConfig(); - - const name = operationResponseTypeName(operation.name); - const { name: responseTransformerName } = setUniqueTypeName({ - client, - meta: { - $ref: `transformers/${name}`, - name, - }, - nameTransformer: operationResponseTransformerTypeName, - }); - - if (responseTransformerName) { - onImport(responseTransformerName); - } - - if (!isLegacyClient(config)) { - let obj: ObjectValue[] = [ - { - spread: 'options', - }, - ]; - - const bodyParameters = operation.parameters.filter( - (parameter) => parameter.in === 'body' || parameter.in === 'formData', - ); - const contents = bodyParameters - .map( - (parameter) => - parameter.mediaType || - (parameter.in === 'formData' ? 'multipart/form-data' : undefined), - ) - .filter(Boolean) - .filter(unique); - if (contents.length === 1) { - if (contents[0] === 'multipart/form-data') { - obj = [ - ...obj, - { - spread: 'formDataBodySerializer', - }, - { - key: 'headers', - value: [ - { - // no need for Content-Type header, browser will set it automatically - key: 'Content-Type', - value: null, - }, - { - spread: 'options?.headers', - }, - ], - }, - ]; - onClientImport?.('formDataBodySerializer'); - } - - if (contents[0] === 'application/x-www-form-urlencoded') { - obj = [ - ...obj, - { - spread: 'urlSearchParamsBodySerializer', - }, - { - key: 'headers', - value: [ - { - key: 'Content-Type', - value: contents[0], - }, - { - spread: 'options?.headers', - }, - ], - }, - ]; - onClientImport?.('urlSearchParamsBodySerializer'); - } - } - - // TODO: set parseAs to skip inference if every result has the same - // content type. currently impossible because successes do not contain - // header information - - obj = [ - ...obj, - { - key: 'url', - value: operation.path, - }, - ]; - - if (responseTransformerName) { - obj = [ - ...obj, - { - key: 'responseTransformer', - value: responseTransformerName, - }, - ]; - } - - return tsc.objectExpression({ - identifiers: ['responseTransformer'], - obj, - }); - } - - const toObj = (parameters: OperationParameter[]) => - parameters.reduce( - (prev, curr) => { - const key = curr.prop; - const value = config.useOptions ? `data.${curr.name}` : curr.name; - if (key === value) { - prev[key] = key; - } else if (escapeName(key) === key) { - prev[key] = value; - } else { - prev[`'${key}'`] = value; - } - return prev; - }, - {} as Record, - ); - - const obj: Record = { - method: operation.method, - url: operation.path, - }; - - if (operation.parametersPath.length) { - obj.path = toObj(operation.parametersPath); - } - - if (operation.parametersCookie.length) { - obj.cookies = toObj(operation.parametersCookie); - } - - if (operation.parametersHeader.length) { - obj.headers = toObj(operation.parametersHeader); - } - - if (operation.parametersQuery.length) { - obj.query = toObj(operation.parametersQuery); - } - - if (operation.parametersForm.length) { - obj.formData = toObj(operation.parametersForm); - } - - if (operation.parametersBody) { - if (operation.parametersBody.in === 'formData') { - if (config.useOptions) { - obj.formData = `data.${operation.parametersBody.name}`; - } else { - obj.formData = operation.parametersBody.name; - } - } - if (operation.parametersBody.in === 'body') { - if (config.useOptions) { - obj.body = `data.${operation.parametersBody.name}`; - } else { - obj.body = operation.parametersBody.name; - } - } - } - - if (operation.parametersBody?.mediaType) { - obj.mediaType = operation.parametersBody?.mediaType; - } - - if (operation.responseHeader) { - obj.responseHeader = operation.responseHeader; - } - - if (responseTransformerName) { - obj.responseTransformer = responseTransformerName; - } - - const errorResponses = operation.responses.filter((response) => - response.responseTypes.includes('error'), - ); - if (errorResponses.length > 0) { - const errors: Record = {}; - errorResponses.forEach((response) => { - errors[response.code] = response.description ?? ''; - }); - obj.errors = errors; - } - - return tsc.objectExpression({ - identifiers: [ - 'body', - 'cookies', - 'formData', - 'headers', - 'path', - 'query', - 'responseTransformer', - ], - obj, - shorthand: true, - }); -}; - -export const serviceFunctionIdentifier = ({ - config, - handleIllegal, - id, - operation, -}: { - config: ClientConfig; - handleIllegal?: boolean; - id: string; - operation: IR.OperationObject | Operation; -}) => { - if (config.plugins['@hey-api/sdk']?.config.methodNameBuilder) { - return config.plugins['@hey-api/sdk'].config.methodNameBuilder(operation); - } - - if (handleIllegal && id.match(reservedJavaScriptKeywordsRegExp)) { - return `${id}_`; - } - - return id; -}; - -const toOperationStatements = ({ - client, - onClientImport, - onImport, - operation, -}: { - client: Client; - onClientImport?: OnImport; - onImport: OnImport; - operation: Operation; -}) => { - const config = getConfig(); - - const options = toRequestOptions({ - client, - onClientImport, - onImport, - operation, - }); - - if (!isLegacyClient(config)) { - const errorType = setUniqueTypeName({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationErrorTypeName, - }).name; - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - const responseType = successResponses.length - ? setUniqueTypeName({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationResponseTypeName, - }).name - : 'void'; - return [ - tsc.returnFunctionCall({ - args: [options], - name: `(options?.client ?? client).${operation.method.toLocaleLowerCase()}`, - types: - errorType && responseType - ? [responseType, errorType, 'ThrowOnError'] - : errorType - ? ['unknown', errorType, 'ThrowOnError'] - : responseType - ? [responseType, 'unknown', 'ThrowOnError'] - : [], - }), - ]; - } - - if (legacyNameFromConfig(config)) { - return [ - tsc.returnFunctionCall({ - args: [options], - name: 'this.httpRequest.request', - }), - ]; - } - - const clientPlugin = getClientPlugin(config); - if (clientPlugin.name === 'legacy/angular') { - return [ - tsc.returnFunctionCall({ - args: ['OpenAPI', 'this.http', options], - name: '__request', - }), - ]; - } - - return [ - tsc.returnFunctionCall({ - args: ['OpenAPI', options], - name: '__request', - }), - ]; -}; - -const processService = ({ - client, - onClientImport, - onImport, - onNode, - service, -}: { - client: Client; - onClientImport: OnImport; - onImport: OnImport; - onNode: OnNode; - service: Service; -}) => { - const config = getConfig(); - - const clientPlugin = getClientPlugin(config); - const isLegacy = isLegacyClient(config); - - for (const operation of service.operations) { - if (operation.parameters.length) { - generateImport({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationDataTypeName, - onImport, - }); - } - - if (!isLegacy) { - generateImport({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationErrorTypeName, - onImport, - }); - } - - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - if (successResponses.length) { - generateImport({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationResponseTypeName, - onImport, - }); - } - } - - const throwOnErrorTypeGeneric: FunctionTypeParameter = { - default: - ('throwOnError' in clientPlugin.config - ? clientPlugin.config.throwOnError - : false) ?? false, - extends: 'boolean', - name: 'ThrowOnError', - }; - - if ( - !config.plugins['@hey-api/sdk']?.config.asClass && - !legacyNameFromConfig(config) - ) { - for (const operation of service.operations) { - const compileFunctionParams = { - parameters: toOperationParamType(client, operation), - returnType: !isLegacy - ? undefined - : toOperationReturnType(client, operation), - statements: toOperationStatements({ - client, - onClientImport, - onImport, - operation, - }), - types: !isLegacy ? [throwOnErrorTypeGeneric] : undefined, - }; - const expression = - clientPlugin.name === 'legacy/angular' - ? tsc.anonymousFunction(compileFunctionParams) - : tsc.arrowFunction(compileFunctionParams); - const statement = tsc.constVariable({ - comment: toOperationComment(operation), - exportConst: true, - expression, - name: serviceFunctionIdentifier({ - config, - handleIllegal: true, - id: operation.name, - operation, - }), - }); - onNode(statement); - } - return; - } - - let members: ts.ClassElement[] = service.operations.map((operation) => { - const node = tsc.methodDeclaration({ - accessLevel: 'public', - comment: toOperationComment(operation), - isStatic: - legacyNameFromConfig(config) === undefined && - clientPlugin.name !== 'legacy/angular', - name: serviceFunctionIdentifier({ - config, - id: operation.name, - operation, - }), - parameters: toOperationParamType(client, operation), - returnType: !isLegacy - ? undefined - : toOperationReturnType(client, operation), - statements: toOperationStatements({ - client, - onClientImport, - onImport, - operation, - }), - types: !isLegacy ? [throwOnErrorTypeGeneric] : undefined, - }); - return node; - }); - - if (!members.length) { - return; - } - - // Push constructor to front if needed - if (legacyNameFromConfig(config)) { - members = [ - tsc.constructorDeclaration({ - multiLine: false, - parameters: [ - { - accessLevel: 'public', - isReadOnly: true, - name: 'httpRequest', - type: 'BaseHttpRequest', - }, - ], - }), - ...members, - ]; - } else if (clientPlugin.name === 'legacy/angular') { - members = [ - tsc.constructorDeclaration({ - multiLine: false, - parameters: [ - { - accessLevel: 'public', - isReadOnly: true, - name: 'http', - type: 'HttpClient', - }, - ], - }), - ...members, - ]; - } - - const _members: Array = []; - members.forEach((member, index) => { - // add newline between each class member - if (index) { - // @ts-expect-error - _members.push(tsc.identifier({ text: '\n' })); - } - - _members.push(member); - }); - - const statement = tsc.classDeclaration({ - decorator: - clientPlugin.name === 'legacy/angular' - ? { args: [{ providedIn: 'root' }], name: 'Injectable' } - : undefined, - exportClass: true, - name: transformClassName({ - config, - name: service.name, - }), - nodes: _members, - }); - onNode(statement); -}; - -export const handlerLegacy: HeyApiSdkPlugin['LegacyHandler'] = ({ - client, - files, - plugin, -}) => { - const config = getConfig(); - - const isLegacy = isLegacyClient(config); - - const sdkOutput = 'sdk'; - - files.sdk = new GeneratedFile({ - dir: config.output.path, - exportFromIndex: plugin.config.exportFromIndex, - id: 'sdk', - name: `${sdkOutput}.ts`, - }); - - // Import required packages and core files. - if (!isLegacy) { - files.sdk.import({ - module: clientModulePath({ config, sourceOutput: sdkOutput }), - name: 'createClient', - }); - files.sdk.import({ - module: clientModulePath({ config, sourceOutput: sdkOutput }), - name: 'createConfig', - }); - files.sdk.import({ - asType: true, - module: clientModulePath({ config, sourceOutput: sdkOutput }), - name: 'OptionsLegacyParser', - }); - } else { - const clientPlugin = getClientPlugin(config); - if (clientPlugin.name === 'legacy/angular') { - files.sdk.import({ - module: '@angular/core', - name: 'Injectable', - }); - - if (!legacyNameFromConfig(config)) { - files.sdk.import({ - module: '@angular/common/http', - name: 'HttpClient', - }); - } - - files.sdk.import({ - asType: true, - module: 'rxjs', - name: 'Observable', - }); - } else { - files.sdk.import({ - asType: true, - module: './core/CancelablePromise', - name: 'CancelablePromise', - }); - } - - if (config.plugins['@hey-api/sdk']?.config.response === 'response') { - files.sdk.import({ - asType: true, - module: './core/ApiResult', - name: 'ApiResult', - }); - } - - if (legacyNameFromConfig(config)) { - const clientPlugin = getClientPlugin(config); - files.sdk.import({ - asType: clientPlugin.name !== 'legacy/angular', - module: './core/BaseHttpRequest', - name: 'BaseHttpRequest', - }); - } else { - files.sdk.import({ - module: './core/OpenAPI', - name: 'OpenAPI', - }); - files.sdk.import({ - alias: '__request', - module: './core/request', - name: 'request', - }); - } - } - - // define client first - if (!isLegacy) { - const clientPlugin = getClientPlugin(config); - const statement = tsc.constVariable({ - exportConst: true, - expression: tsc.callExpression({ - functionName: 'createClient', - parameters: [ - tsc.callExpression({ - functionName: 'createConfig', - parameters: [ - 'throwOnError' in clientPlugin && clientPlugin.throwOnError - ? tsc.objectExpression({ - obj: [ - { - key: 'throwOnError', - value: true, - }, - ], - }) - : undefined, - ], - }), - ], - }), - name: 'client', - }); - files.sdk.add(statement); - } - - for (const service of client.services) { - processService({ - client, - onClientImport: (imported) => { - files.sdk!.import({ - module: clientModulePath({ config, sourceOutput: sdkOutput }), - name: imported, - }); - }, - onImport: (imported) => { - files.sdk!.import({ - // this detection could be done safer, but it shouldn't cause any issues - asType: !imported.endsWith('Transformer'), - module: `./${files.types!.nameWithoutExtension()}`, - name: imported, - }); - }, - onNode: (node) => { - files.sdk!.add(node); - }, - service, - }); - } -}; diff --git a/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/functions.ts b/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/functions.ts index 836b9bb2e..88f2aa55b 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/functions.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/functions.ts @@ -1,15 +1,36 @@ +import type { IR } from '~/ir/types'; import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; import { createOperationComment, isOperationOptionsRequired, } from '~/plugins/shared/utils/operation'; import { tsc } from '~/tsc'; +import { reservedJavaScriptKeywordsRegExp } from '~/utils/regexp'; -import { serviceFunctionIdentifier } from '../plugin-legacy'; import type { HeyApiSdkPlugin } from '../types'; import { nuxtTypeComposable, nuxtTypeDefault } from './constants'; import { operationParameters, operationStatements } from './operation'; +const serviceFunctionIdentifier = ({ + id, + operation, + plugin, +}: { + id: string; + operation: IR.OperationObject; + plugin: HeyApiSdkPlugin['Instance']; +}) => { + if (plugin.config.methodNameBuilder) { + return plugin.config.methodNameBuilder(operation); + } + + if (id.match(reservedJavaScriptKeywordsRegExp)) { + return `${id}_`; + } + + return id; +}; + export const generateFlatSdk = ({ plugin, }: { @@ -55,10 +76,9 @@ export const generateFlatSdk = ({ tool: 'sdk', }, name: serviceFunctionIdentifier({ - config: plugin.context.config, - handleIllegal: true, id: operation.id, operation, + plugin, }), }); const node = tsc.constVariable({ diff --git a/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/operation.ts b/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/operation.ts index 97f383e2a..26084d154 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/operation.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/sdk/shared/operation.ts @@ -4,7 +4,7 @@ import type ts from 'typescript'; import type { Context } from '~/ir/context'; import { statusCodeToGroup } from '~/ir/operation'; import type { IR } from '~/ir/types'; -import { sanitizeNamespaceIdentifier } from '~/openApi'; +import { sanitizeNamespaceIdentifier } from '~/openApi/common/parser/sanitize'; import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; import { toRefs } from '~/plugins/shared/utils/refs'; import type { Property } from '~/tsc'; diff --git a/packages/openapi-ts/src/plugins/@hey-api/sdk/types.d.ts b/packages/openapi-ts/src/plugins/@hey-api/sdk/types.d.ts index 0ae872362..ca21b3627 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/sdk/types.d.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/sdk/types.d.ts @@ -2,7 +2,6 @@ import type { IR } from '~/ir/types'; import type { DefinePlugin, Plugin } from '~/plugins'; import type { PluginClientNames, PluginValidatorNames } from '~/plugins/types'; import type { StringName } from '~/types/case'; -import type { Operation } from '~/types/client'; import type { IApi } from './api'; @@ -78,9 +77,9 @@ export type UserConfig = Plugin.Name<'@hey-api/sdk'> & instance?: string | boolean; /** * Customise the name of methods within the service. By default, - * {@link IR.OperationObject.id} or {@link Operation.name} is used. + * {@link IR.OperationObject.id} is used. */ - methodNameBuilder?: (operation: IR.OperationObject | Operation) => string; + methodNameBuilder?: (operation: IR.OperationObject) => string; // TODO: parser - rename operationId option to something like inferId?: boolean /** * Use operation ID to generate operation names? @@ -257,9 +256,9 @@ export type Config = Plugin.Name<'@hey-api/sdk'> & instance: string | boolean; /** * Customise the name of methods within the service. By default, - * {@link IR.OperationObject.id} or {@link Operation.name} is used. + * {@link IR.OperationObject.id} is used. */ - methodNameBuilder?: (operation: IR.OperationObject | Operation) => string; + methodNameBuilder?: (operation: IR.OperationObject) => string; // TODO: parser - rename operationId option to something like inferId?: boolean /** * Use operation ID to generate operation names? diff --git a/packages/openapi-ts/src/plugins/@hey-api/transformers/config.ts b/packages/openapi-ts/src/plugins/@hey-api/transformers/config.ts index cab3de648..e0d806aef 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/transformers/config.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/transformers/config.ts @@ -3,7 +3,6 @@ import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; import { bigIntExpressions, dateExpressions } from './expressions'; import { handler } from './plugin'; -import { handlerLegacy } from './plugin-legacy'; import type { HeyApiTransformersPlugin } from './types'; export const defaultConfig: HeyApiTransformersPlugin['Config'] = { @@ -17,7 +16,6 @@ export const defaultConfig: HeyApiTransformersPlugin['Config'] = { }, dependencies: ['@hey-api/typescript'], handler, - handlerLegacy, name: '@hey-api/transformers', resolveConfig: (plugin) => { if (!plugin.config.transformers) { diff --git a/packages/openapi-ts/src/plugins/@hey-api/transformers/plugin-legacy.ts b/packages/openapi-ts/src/plugins/@hey-api/transformers/plugin-legacy.ts deleted file mode 100644 index ae6df43c9..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/transformers/plugin-legacy.ts +++ /dev/null @@ -1,356 +0,0 @@ -import type ts from 'typescript'; - -import { createOperationKey } from '~/ir/operation'; -import { - modelResponseTransformerTypeName, - operationResponseTransformerTypeName, - operationResponseTypeName, -} from '~/plugins/@hey-api/sdk/plugin-legacy'; -import { - generateType, - type TypesProps, -} from '~/plugins/@hey-api/typescript/plugin-legacy'; -import { tsc } from '~/tsc'; -import type { ModelMeta, OperationResponse } from '~/types/client'; -import { getConfig } from '~/utils/config'; -import { isModelDate, unsetUniqueTypeName } from '~/utils/type'; - -import type { HeyApiTransformersPlugin } from './types'; - -interface ModelProps extends TypesProps { - meta?: ModelMeta; - path: Array; -} - -const dataVariableName = 'data'; - -const isVoidResponse = (response: OperationResponse) => - response.base === 'unknown' && - response.export === 'generic' && - response.type === 'unknown'; - -const getRefModels = ({ - client, - model, -}: Pick) => { - const refModels = model.$refs.map((ref) => { - const refModel = client.models.find((model) => model.meta?.$ref === ref); - if (!refModel) { - throw new Error( - `Ref ${ref} could not be found. Transformers cannot be generated without having access to all refs.`, - ); - } - return refModel; - }); - return refModels; -}; - -const ensureModelResponseTransformerExists = ( - props: Omit, -) => { - const modelName = props.model.meta!.name; - - const { name } = generateType({ - ...props, - meta: { - $ref: `transformers/${modelName}`, - name: modelName, - }, - nameTransformer: modelResponseTransformerTypeName, - onCreated: (name) => { - const statements = processModel({ - ...props, - meta: { - $ref: `transformers/${modelName}`, - name, - }, - path: [dataVariableName], - }); - generateResponseTransformer({ - ...props, - async: false, - name, - statements, - }); - }, - type: `(${dataVariableName}: any) => ${modelName}`, - }); - - const result = { - created: Boolean(props.client.types[name]), - name, - }; - return result; -}; - -const processArray = (props: ModelProps) => { - const { model } = props; - const refModels = getRefModels(props); - - if (refModels.length === 1) { - const { created, name: nameModelResponseTransformer } = - ensureModelResponseTransformerExists({ ...props, model: refModels[0]! }); - - if (!created) { - return []; - } - - return [ - tsc.transformArrayMutation({ - path: props.path, - transformerName: nameModelResponseTransformer, - }), - ]; - } - - if ( - isModelDate(model) || - (model.link && - !Array.isArray(model.link) && - model.link.export === 'any-of' && - model.link.properties.find((property) => isModelDate(property))) - ) { - return [ - tsc.transformArrayMap({ - path: props.path, - transformExpression: tsc.conditionalExpression({ - condition: tsc.identifier({ text: 'item' }), - whenFalse: tsc.identifier({ text: 'item' }), - whenTrue: tsc.transformNewDate({ - parameterName: 'item', - }), - }), - }), - ]; - } - - // Not transform for this type - return []; -}; - -const processProperty = (props: ModelProps) => { - const { model } = props; - const path = [...props.path, model.name]; - - if ( - model.type === 'string' && - model.export !== 'array' && - isModelDate(model) - ) { - return [tsc.transformDateMutation({ path })]; - } - - // otherwise we recurse in case it's an object/array, and if it's not that will just bail with [] - return processModel({ - ...props, - model, - path, - }); -}; - -const processModel = (props: ModelProps): ts.Statement[] => { - const { model } = props; - - switch (model.export) { - case 'array': - return processArray(props); - case 'interface': - return model.properties.flatMap((property) => - processProperty({ ...props, model: property }), - ); - case 'reference': { - if (model.$refs.length !== 1) { - return []; - } - const refModels = getRefModels(props); - - const { created, name: nameModelResponseTransformer } = - ensureModelResponseTransformerExists({ - ...props, - model: refModels[0]!, - }); - - if (!created) { - return []; - } - - return model.in === 'response' - ? [ - tsc.expressionToStatement({ - expression: tsc.callExpression({ - functionName: nameModelResponseTransformer, - parameters: [dataVariableName], - }), - }), - ] - : tsc.transformFunctionMutation({ - path: props.path, - transformerName: nameModelResponseTransformer, - }); - } - // unsupported - default: - return []; - } -}; - -const generateResponseTransformer = ({ - async, - client, - name, - onNode, - onRemoveNode, - statements, -}: Pick & { - async: boolean; - name: string; - statements: Array; -}) => { - const result = { - created: false, - name, - }; - - if (!statements.length) { - // clean up created type for response transformer if it turns out - // the transformer was never generated - unsetUniqueTypeName({ - client, - name, - }); - onRemoveNode?.(); - return result; - } - - const expression = tsc.arrowFunction({ - async, - multiLine: true, - parameters: [ - { - name: dataVariableName, - }, - ], - statements: [ - ...statements, - tsc.returnVariable({ - expression: dataVariableName, - }), - ], - }); - const statement = tsc.constVariable({ - exportConst: true, - expression, - name, - typeName: name, - }); - onNode(statement); - - return { - created: true, - name, - }; -}; - -// handles only response transformers for now -export const handlerLegacy: HeyApiTransformersPlugin['LegacyHandler'] = ({ - client, - files, -}) => { - const config = getConfig(); - - const onNode: TypesProps['onNode'] = (node) => { - files.types?.add(node); - }; - const onRemoveNode: TypesProps['onRemoveNode'] = () => { - files.types?.removeNode_LEGACY(); - }; - - for (const service of client.services) { - for (const operation of service.operations) { - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - - if (!successResponses.length) { - continue; - } - - const nonVoidResponses = successResponses.filter( - (response) => !isVoidResponse(response), - ); - - if (!nonVoidResponses.length) { - continue; - } - - if (nonVoidResponses.length > 1) { - if (config.logs.level === 'debug') { - console.warn( - `❗️ Transformers warning: route ${createOperationKey(operation)} has ${nonVoidResponses.length} non-void success responses. This is currently not handled and we will not generate a response transformer. Please open an issue if you'd like this feature https://github.com/hey-api/openapi-ts/issues`, - ); - } - continue; - } - - const name = operationResponseTypeName(operation.name); - generateType({ - client, - meta: { - $ref: `transformers/${name}`, - name, - }, - nameTransformer: operationResponseTransformerTypeName, - onCreated: (nameCreated) => { - const statements = - successResponses.length > 1 - ? successResponses.flatMap((response) => { - const statements = processModel({ - client, - meta: { - $ref: `transformers/${name}`, - name, - }, - model: response, - onNode, - onRemoveNode, - path: [dataVariableName], - }); - - // assume unprocessed responses are void - if (!statements.length) { - return []; - } - - return [ - tsc.ifStatement({ - expression: tsc.safeAccessExpression(['data']), - thenStatement: tsc.block({ statements }), - }), - ]; - }) - : processModel({ - client, - meta: { - $ref: `transformers/${name}`, - name, - }, - model: successResponses[0]!, - onNode, - onRemoveNode, - path: [dataVariableName], - }); - generateResponseTransformer({ - async: true, - client, - name: nameCreated, - onNode, - onRemoveNode, - statements, - }); - }, - onNode, - type: `(${dataVariableName}: any) => Promise<${name}>`, - }); - } - } -}; diff --git a/packages/openapi-ts/src/plugins/@hey-api/typescript/__tests__/plugin.test.ts b/packages/openapi-ts/src/plugins/@hey-api/typescript/__tests__/plugin.test.ts deleted file mode 100644 index 0a04dd96e..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/typescript/__tests__/plugin.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -import fs from 'node:fs'; - -import { Project } from '@hey-api/codegen-core'; -import type ts from 'typescript'; -import { describe, expect, it, vi } from 'vitest'; - -import { openApi } from '~/generate/__tests__/mocks'; -import { GeneratedFile } from '~/generate/file'; -import { PluginInstance } from '~/plugins/shared/utils/instance'; -import type { Config } from '~/types/config'; -import { setConfig } from '~/utils/config'; - -import { handlerLegacy } from '../plugin-legacy'; - -vi.mock('node:fs'); - -describe('generateLegacyTypes', () => { - it('writes to filesystem', async () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - name: 'AppClient', - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: true, - }); - - const client: Parameters[0]['client'] = { - config: {} as Config, - models: [ - { - $refs: [], - base: 'User', - description: null, - enum: [], - enums: [], - export: 'interface', - imports: [], - in: '', - isDefinition: true, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - meta: { - $ref: '#/components/schemas/User', - name: 'User', - }, - name: 'User', - properties: [], - template: null, - type: 'User', - }, - ], - server: 'http://localhost:8080', - services: [], - types: {}, - version: 'v1', - }; - - const files = { - types: new GeneratedFile({ - dir: '/', - id: 'types', - name: 'types.ts', - }), - }; - - await handlerLegacy({ - client, - files, - openApi, - plugin: new PluginInstance({ - config: { - exportFromIndex: false, - }, - context: { - config: { - // @ts-expect-error - parser: { - hooks: {}, - }, - }, - }, - dependencies: [], - gen: new Project({ - renderers: {}, - root: '.tmp', - }), - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }), - }); - - files.types.write(); - - expect(fs.writeFileSync).toHaveBeenCalledWith( - expect.stringContaining('types.gen.ts'), - expect.anything(), - ); - }); -}); diff --git a/packages/openapi-ts/src/plugins/@hey-api/typescript/config.ts b/packages/openapi-ts/src/plugins/@hey-api/typescript/config.ts index 5c458da01..dbc316388 100644 --- a/packages/openapi-ts/src/plugins/@hey-api/typescript/config.ts +++ b/packages/openapi-ts/src/plugins/@hey-api/typescript/config.ts @@ -2,7 +2,6 @@ import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; import { handler } from './plugin'; -import { handlerLegacy } from './plugin-legacy'; import type { HeyApiTypeScriptPlugin } from './types'; export const defaultConfig: HeyApiTypeScriptPlugin['Config'] = { @@ -15,7 +14,6 @@ export const defaultConfig: HeyApiTypeScriptPlugin['Config'] = { tree: false, }, handler, - handlerLegacy, name: '@hey-api/typescript', resolveConfig: (plugin, context) => { plugin.config.definitions = context.valueToObject({ diff --git a/packages/openapi-ts/src/plugins/@hey-api/typescript/plugin-legacy.ts b/packages/openapi-ts/src/plugins/@hey-api/typescript/plugin-legacy.ts deleted file mode 100644 index cc368fe34..000000000 --- a/packages/openapi-ts/src/plugins/@hey-api/typescript/plugin-legacy.ts +++ /dev/null @@ -1,637 +0,0 @@ -import type ts from 'typescript'; - -import { GeneratedFile } from '~/generate/file'; -import { isOperationParameterRequired } from '~/openApi'; -import { - operationDataTypeName, - operationErrorTypeName, - operationResponseTypeName, -} from '~/plugins/@hey-api/sdk/plugin-legacy'; -import { type Comments, tsc } from '~/tsc'; -import type { Client, Method, Model, OperationParameter } from '~/types/client'; -import { getConfig, isLegacyClient } from '~/utils/config'; -import { enumEntry, enumUnionType } from '~/utils/enum'; -import { escapeComment } from '~/utils/escape'; -import { sortByName, sorterByName } from '~/utils/sort'; -import { - setUniqueTypeName, - type SetUniqueTypeNameResult, - toType, -} from '~/utils/type'; - -import type { HeyApiTypeScriptPlugin } from './types'; - -export interface TypesProps { - client: Client; - model: Model; - onNode: (node: ts.Node) => void; - onRemoveNode?: VoidFunction; -} - -const treeName = '$OpenApiTs'; - -export const emptyModel: Model = { - $refs: [], - base: '', - description: null, - enum: [], - enums: [], - export: 'interface', - imports: [], - in: '', - isDefinition: false, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: '', - properties: [], - template: null, - type: '', -}; - -const generateEnum = ({ - comments, - leadingComment, - meta, - obj, - onNode, - ...setUniqueTypeNameArgs -}: Omit[0], 'name'> & - Pick[0], 'client' | 'nameTransformer'> & - Pick & - Pick) => { - // generate types only for top-level models - if (!meta) { - return; - } - - const { created, name } = setUniqueTypeName({ - create: true, - meta, - ...setUniqueTypeNameArgs, - }); - if (created) { - const config = getConfig(); - const pluginTypeScript = config.plugins['@hey-api/typescript']; - const node = tsc.enumDeclaration({ - asConst: - typeof pluginTypeScript?.config.enums === 'object' && - pluginTypeScript.config.enums.mode === 'typescript-const', - comments, - leadingComment, - name, - obj, - }); - onNode(node); - } -}; - -export const generateType = ({ - comment, - meta, - onCreated, - onNode, - type, - ...setUniqueTypeNameArgs -}: Omit[0], 'name'> & - Pick[0], 'client' | 'nameTransformer'> & - Pick & - Pick & { - onCreated?: (name: string) => void; - }): SetUniqueTypeNameResult => { - // generate types only for top-level models - if (!meta) { - return { - created: false, - name: '', - }; - } - - const result = setUniqueTypeName({ - create: true, - meta, - ...setUniqueTypeNameArgs, - }); - const { created, name } = result; - if (created) { - const node = tsc.typeAliasDeclaration({ - comment, - exportType: true, - name, - type, - }); - onNode(node); - - onCreated?.(name); - } - return result; -}; - -const processComposition = (props: TypesProps) => { - const enumDeclarations = [] as ts.EnumDeclaration[]; - - processType(props); - - props.model.enums.forEach((enumerator) => - processScopedEnum({ - ...props, - model: enumerator, - onNode: (node) => { - enumDeclarations.push(node as ts.EnumDeclaration); - }, - }), - ); - - if (enumDeclarations.length) { - props.onNode( - tsc.namespaceDeclaration({ - name: props.model.name, - statements: enumDeclarations, - }), - ); - } -}; - -const processEnum = ({ client, model, onNode }: TypesProps) => { - const config = getConfig(); - - const properties: Record = {}; - const comments: Record = {}; - model.enum.forEach((enumerator) => { - const { key, value } = enumEntry(enumerator); - properties[key] = value; - const comment = enumerator.customDescription || enumerator.description; - if (comment) { - comments[key] = [escapeComment(comment)]; - } - }); - - const comment = [ - model.description && escapeComment(model.description), - model.deprecated && '@deprecated', - ]; - - const pluginTypeScript = config.plugins['@hey-api/typescript']; - if ( - pluginTypeScript?.config && - typeof pluginTypeScript.config.enums === 'object' && - pluginTypeScript.config.enums.enabled && - (pluginTypeScript.config.enums.mode === 'typescript' || - pluginTypeScript.config.enums.mode === 'typescript-const') - ) { - generateEnum({ - asConst: pluginTypeScript.config.enums.mode === 'typescript-const', - client, - comments, - leadingComment: comment, - meta: model.meta, - obj: properties, - onNode, - }); - return; - } - - generateType({ - client, - comment, - meta: model.meta, - onCreated: (name) => { - // create a separate JavaScript object export - const pluginTypeScript = config.plugins['@hey-api/typescript']; - if ( - pluginTypeScript?.config && - typeof pluginTypeScript.config.enums === 'object' && - pluginTypeScript.config.enums.enabled && - pluginTypeScript.config.enums.mode === 'javascript' - ) { - const expression = tsc.objectExpression({ - multiLine: true, - obj: Object.entries(properties).map(([key, value]) => ({ - comments: comments[key], - key, - value, - })), - unescape: true, - }); - const node = tsc.constVariable({ - assertion: 'const', - comment, - exportConst: true, - expression, - name, - }); - onNode(node); - } - }, - onNode, - type: enumUnionType(model.enum), - }); -}; - -const processScopedEnum = ({ model, onNode }: TypesProps) => { - const properties: Record = {}; - const comments: Record = {}; - model.enum.forEach((enumerator) => { - const { key, value } = enumEntry(enumerator); - properties[key] = value; - const comment = enumerator.customDescription || enumerator.description; - if (comment) { - comments[key] = [escapeComment(comment)]; - } - }); - const config = getConfig(); - const pluginTypeScript = config.plugins['@hey-api/typescript']; - onNode( - tsc.enumDeclaration({ - asConst: - typeof pluginTypeScript?.config.enums === 'object' && - pluginTypeScript.config.enums.mode === 'typescript-const', - comments, - leadingComment: [ - model.description && escapeComment(model.description), - model.deprecated && '@deprecated', - ], - name: model.meta?.name || model.name, - obj: properties, - }), - ); -}; - -const processType = ({ client, model, onNode }: TypesProps) => { - generateType({ - client, - comment: [ - model.description && escapeComment(model.description), - model.deprecated && '@deprecated', - ], - meta: model.meta, - onNode, - type: toType(model), - }); -}; - -const processModel = (props: TypesProps) => { - switch (props.model.export) { - case 'all-of': - case 'any-of': - case 'one-of': - case 'interface': - return processComposition(props); - case 'enum': - return processEnum(props); - default: - return processType(props); - } -}; - -interface MethodMap { - $ref?: string; - req?: OperationParameter[]; - res?: Record; -} - -type PathMap = { - [method in Method]?: MethodMap; -}; - -type PathsMap = Record; - -const processServiceTypes = ({ - client, - onNode, -}: Pick) => { - const pathsMap: PathsMap = {}; - - const config = getConfig(); - - if ( - !config.plugins['@hey-api/sdk'] && - !config.plugins['@hey-api/typescript']?.config.tree - ) { - return; - } - - const isLegacy = isLegacyClient(config); - - for (const service of client.services) { - for (const operation of service.operations) { - if (!operation.parameters.length && !operation.responses.length) { - continue; - } - - if (!pathsMap[operation.path]) { - pathsMap[operation.path] = {}; - } - const pathMap = pathsMap[operation.path]!; - - if (!pathMap[operation.method]) { - pathMap[operation.method] = {}; - } - const methodMap = pathMap[operation.method]!; - methodMap.$ref = operation.name; - - if (operation.responses.length > 0) { - if (!methodMap.res) { - methodMap.res = {}; - } - - if (Array.isArray(methodMap.res)) { - continue; - } - - operation.responses.forEach((response) => { - methodMap.res![response.code] = response; - }); - } - - if (operation.parameters.length > 0) { - let bodyParameters: OperationParameter = { - mediaType: null, - ...emptyModel, - in: 'body', - name: 'body', - prop: 'body', - }; - let bodyParameter = operation.parameters.filter( - (parameter) => parameter.in === 'body', - ); - if (!bodyParameter.length) { - bodyParameter = operation.parameters.filter( - (parameter) => parameter.in === 'formData', - ); - } - - if (bodyParameter.length === 1) { - bodyParameters = { - ...emptyModel, - ...bodyParameter[0]!, - in: 'body', - isRequired: bodyParameter[0]!.isRequired, - name: 'body', - prop: 'body', - }; - // assume we have multiple formData parameters from Swagger 2.0 - } else if (bodyParameter.length > 1) { - bodyParameters = { - ...emptyModel, - in: 'body', - isRequired: bodyParameter.some((parameter) => parameter.isRequired), - mediaType: 'multipart/form-data', - name: 'body', - prop: 'body', - properties: bodyParameter, - }; - } - - const headerParameters: OperationParameter = { - ...emptyModel, - in: 'header', - isRequired: isOperationParameterRequired( - operation.parameters.filter( - (parameter) => parameter.in === 'header', - ), - ), - mediaType: null, - name: isLegacy ? 'header' : 'headers', - prop: isLegacy ? 'header' : 'headers', - properties: operation.parameters - .filter((parameter) => parameter.in === 'header') - .sort(sorterByName), - }; - const pathParameters: OperationParameter = { - ...emptyModel, - in: 'path', - isRequired: isOperationParameterRequired( - operation.parameters.filter((parameter) => parameter.in === 'path'), - ), - mediaType: null, - name: 'path', - prop: 'path', - properties: operation.parameters - .filter((parameter) => parameter.in === 'path') - .sort(sorterByName), - }; - const queryParameters: OperationParameter = { - ...emptyModel, - in: 'query', - isRequired: isOperationParameterRequired( - operation.parameters.filter( - (parameter) => parameter.in === 'query', - ), - ), - mediaType: null, - name: 'query', - prop: 'query', - properties: operation.parameters - .filter((parameter) => parameter.in === 'query') - .sort(sorterByName), - }; - const operationProperties = !isLegacy - ? [ - bodyParameters, - headerParameters, - pathParameters, - queryParameters, - ].filter( - (param) => - param.properties.length || - param.$refs.length || - param.mediaType, - ) - : sortByName([...operation.parameters]); - - methodMap.req = operationProperties; - - // create type export for operation data - generateType({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationDataTypeName, - onNode, - type: toType({ - ...emptyModel, - isRequired: true, - properties: operationProperties, - }), - }); - } - - const successResponses = operation.responses.filter((response) => - response.responseTypes.includes('success'), - ); - - if (successResponses.length > 0) { - // create type export for operation response - generateType({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationResponseTypeName, - onNode, - type: toType({ - ...emptyModel, - export: 'any-of', - isRequired: true, - properties: successResponses, - }), - }); - - const errorResponses = operation.responses.filter((response) => - response.responseTypes.includes('error'), - ); - - if (!isLegacy) { - // create type export for operation error - generateType({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationErrorTypeName, - onNode, - type: toType( - errorResponses.length - ? { - ...emptyModel, - export: 'one-of', - isRequired: true, - properties: errorResponses, - } - : { - ...emptyModel, - base: 'unknown', - isRequired: true, - type: 'unknown', - }, - ), - }); - } - } - } - } - - const properties = Object.entries(pathsMap).map(([path, pathMap]) => { - const pathParameters = Object.entries(pathMap) - .map(([_method, methodMap]) => { - const method = _method as Method; - - let methodParameters: Model[] = []; - - if (methodMap.req) { - const operationName = methodMap.$ref!; - const { name: base } = setUniqueTypeName({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operationName, - name: operationName, - }, - nameTransformer: operationDataTypeName, - }); - const reqKey: Model = { - ...emptyModel, - base, - export: 'reference', - isRequired: true, - name: 'req', - properties: [], - type: base, - }; - methodParameters = [...methodParameters, reqKey]; - } - - if (methodMap.res) { - const reqResParameters = Object.entries(methodMap.res).map( - ([code, base]) => { - // TODO: move query params into separate query key - const value: Model = { - ...emptyModel, - ...base, - isRequired: true, - name: String(code), - }; - return value; - }, - ); - - const resKey: Model = { - ...emptyModel, - isRequired: true, - name: 'res', - properties: reqResParameters, - }; - methodParameters = [...methodParameters, resKey]; - } - - const methodKey: Model = { - ...emptyModel, - isRequired: true, - name: method.toLocaleLowerCase(), - properties: methodParameters, - }; - return methodKey; - }) - .filter(Boolean); - const pathKey: Model = { - ...emptyModel, - isRequired: true, - name: `'${path}'`, - properties: pathParameters as Model[], - }; - return pathKey; - }); - - if (config.plugins['@hey-api/typescript']?.config.tree) { - generateType({ - client, - meta: { - $ref: '@hey-api/openapi-ts', - name: treeName, - }, - onNode, - type: toType({ - ...emptyModel, - properties, - }), - }); - } -}; - -export const handlerLegacy: HeyApiTypeScriptPlugin['LegacyHandler'] = ({ - client, - files, - plugin, -}) => { - const config = getConfig(); - - files.types = new GeneratedFile({ - dir: config.output.path, - exportFromIndex: plugin.config.exportFromIndex, - id: 'types', - name: 'types.ts', - }); - - const onNode: TypesProps['onNode'] = (node) => { - files.types?.add(node); - }; - - for (const model of client.models) { - processModel({ client, model, onNode }); - } - - processServiceTypes({ client, onNode }); -}; diff --git a/packages/openapi-ts/src/plugins/@tanstack/angular-query-experimental/config.ts b/packages/openapi-ts/src/plugins/@tanstack/angular-query-experimental/config.ts index 0e50763b0..aca32a6a9 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/angular-query-experimental/config.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/angular-query-experimental/config.ts @@ -1,5 +1,4 @@ import { handler } from '~/plugins/@tanstack/query-core/plugin'; -import { handlerLegacy } from '~/plugins/@tanstack/query-core/plugin-legacy'; import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; @@ -14,7 +13,6 @@ export const defaultConfig: TanStackAngularQueryPlugin['Config'] = { }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackAngularQueryPlugin['Handler'], - handlerLegacy: handlerLegacy as TanStackAngularQueryPlugin['LegacyHandler'], name: '@tanstack/angular-query-experimental', output: '@tanstack/angular-query-experimental', resolveConfig: (plugin, context) => { diff --git a/packages/openapi-ts/src/plugins/@tanstack/query-core/plugin-legacy.ts b/packages/openapi-ts/src/plugins/@tanstack/query-core/plugin-legacy.ts deleted file mode 100644 index 977ca4334..000000000 --- a/packages/openapi-ts/src/plugins/@tanstack/query-core/plugin-legacy.ts +++ /dev/null @@ -1,1324 +0,0 @@ -import ts from 'typescript'; - -import { clientModulePath } from '~/generate/client'; -import { relativeModulePath } from '~/generate/utils'; -import { createOperationKey } from '~/ir/operation'; -import { getPaginationKeywordsRegExp } from '~/ir/pagination'; -import type { IR } from '~/ir/types'; -import { isOperationParameterRequired } from '~/openApi'; -import { - getClientBaseUrlKey, - getClientPlugin, -} from '~/plugins/@hey-api/client-core/utils'; -import { - generateImport, - operationDataTypeName, - operationErrorTypeName, - operationOptionsLegacyParserType, - operationResponseTypeName, - serviceFunctionIdentifier, -} from '~/plugins/@hey-api/sdk/plugin-legacy'; -import type { TanStackAngularQueryPlugin } from '~/plugins/@tanstack/angular-query-experimental'; -import type { TanStackReactQueryPlugin } from '~/plugins/@tanstack/react-query'; -import type { TanStackSolidQueryPlugin } from '~/plugins/@tanstack/solid-query'; -import type { TanStackSvelteQueryPlugin } from '~/plugins/@tanstack/svelte-query'; -import type { TanStackVueQueryPlugin } from '~/plugins/@tanstack/vue-query'; -import { type Property, tsc } from '~/tsc'; -import type { ImportExportItem } from '~/tsc/module'; -import type { ImportExportItemObject } from '~/tsc/utils'; -import type { - Client, - Method, - Model, - Operation, - OperationParameter, -} from '~/types/client'; -import type { Config } from '~/types/config'; -import type { Files } from '~/types/utils'; -import { getConfig, isLegacyClient } from '~/utils/config'; -import { transformClassName } from '~/utils/transform'; - -const toInfiniteQueryOptionsName = (operation: Operation) => - `${serviceFunctionIdentifier({ - config: getConfig(), - id: operation.name, - operation, - })}InfiniteOptions`; - -const toMutationOptionsName = (operation: Operation) => - `${serviceFunctionIdentifier({ - config: getConfig(), - id: operation.name, - operation, - })}Mutation`; - -const toQueryOptionsName = ({ - config, - id, - operation, -}: { - config: Config; - id: string; - operation: IR.OperationObject | Operation; -}) => - `${serviceFunctionIdentifier({ - config, - id, - operation, - })}Options`; - -const toQueryKeyName = ({ - config, - id, - isInfinite, - operation, -}: { - config: Config; - id: string; - isInfinite?: boolean; - operation: IR.OperationObject | Operation; -}) => - `${serviceFunctionIdentifier({ - config, - id, - operation, - })}${isInfinite ? 'Infinite' : ''}QueryKey`; - -const getPaginationIn = (parameter: OperationParameter) => { - switch (parameter.in) { - case 'formData': - return 'body'; - case 'header': - return 'headers'; - default: - return parameter.in; - } -}; - -const createInfiniteParamsFn = 'createInfiniteParams'; -const createQueryKeyFn = 'createQueryKey'; -const infiniteQueryOptionsFn = 'infiniteQueryOptions'; -const mutationOptionsFn = 'mutationOptions'; -const queryKeyName = 'QueryKey'; -const queryOptionsFn = 'queryOptions'; -const TOptionsType = 'TOptions'; - -const createInfiniteParamsFunction = ({ - file, -}: { - file: Files[keyof Files]; -}) => { - const fn = tsc.constVariable({ - expression: tsc.arrowFunction({ - multiLine: true, - parameters: [ - { - name: 'queryKey', - type: tsc.typeNode('QueryKey'), - }, - { - name: 'page', - type: tsc.typeNode('K'), - }, - ], - statements: [ - tsc.constVariable({ - expression: tsc.identifier({ - text: 'queryKey[0]', - }), - name: 'params', - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ - text: 'page', - }), - name: tsc.identifier({ text: 'body' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'body', - }), - right: tsc.objectExpression({ - multiLine: true, - obj: [ - { - assertion: 'any', - spread: 'queryKey[0].body', - }, - { - assertion: 'any', - spread: 'page.body', - }, - ], - }), - }), - }), - ], - }), - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ - text: 'page', - }), - name: tsc.identifier({ text: 'headers' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'headers', - }), - right: tsc.objectExpression({ - multiLine: true, - obj: [ - { - spread: 'queryKey[0].headers', - }, - { - spread: 'page.headers', - }, - ], - }), - }), - }), - ], - }), - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ - text: 'page', - }), - name: tsc.identifier({ text: 'path' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'path', - }), - right: tsc.objectExpression({ - multiLine: true, - obj: [ - { - spread: 'queryKey[0].path', - }, - { - spread: 'page.path', - }, - ], - }), - }), - }), - ], - }), - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ - text: 'page', - }), - name: tsc.identifier({ text: 'query' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'query', - }), - right: tsc.objectExpression({ - multiLine: true, - obj: [ - { - spread: 'queryKey[0].query', - }, - { - spread: 'page.query', - }, - ], - }), - }), - }), - ], - }), - }), - tsc.returnVariable({ - expression: ts.factory.createAsExpression( - ts.factory.createAsExpression( - tsc.identifier({ text: 'params' }), - ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword), - ), - ts.factory.createTypeQueryNode(tsc.identifier({ text: 'page' })), - ), - }), - ], - types: [ - { - extends: tsc.typeReferenceNode({ - typeName: tsc.identifier({ - text: "Pick[0], 'body' | 'headers' | 'path' | 'query'>", - }), - }), - name: 'K', - }, - ], - }), - name: createInfiniteParamsFn, - }); - file.add(fn); -}; - -const createQueryKeyFunction = ({ file }: { file: Files[keyof Files] }) => { - const returnType = tsc.indexedAccessTypeNode({ - indexType: tsc.typeNode(0), - objectType: tsc.typeNode(queryKeyName, [tsc.typeNode(TOptionsType)]), - }); - - const infiniteIdentifier = tsc.identifier({ text: 'infinite' }); - const baseUrlKey = getClientBaseUrlKey(getConfig()); - - const fn = tsc.constVariable({ - expression: tsc.arrowFunction({ - multiLine: true, - parameters: [ - { - name: 'id', - type: tsc.typeNode('string'), - }, - { - isRequired: false, - name: 'options', - type: tsc.typeNode(TOptionsType), - }, - { - isRequired: false, - name: 'infinite', - type: tsc.typeNode('boolean'), - }, - ], - returnType, - statements: [ - tsc.constVariable({ - assertion: returnType, - expression: tsc.objectExpression({ - multiLine: false, - obj: [ - { - key: '_id', - value: tsc.identifier({ text: 'id' }), - }, - { - key: baseUrlKey, - value: tsc.identifier({ - text: `options?.${baseUrlKey} || (options?.client ?? _heyApiClient).getConfig().${baseUrlKey}`, - }), - }, - ], - }), - name: 'params', - typeName: returnType, - }), - tsc.ifStatement({ - expression: infiniteIdentifier, - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: '_infinite', - }), - right: infiniteIdentifier, - }), - }), - ], - }), - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ text: 'options' }), - isOptional: true, - name: tsc.identifier({ text: 'body' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'body', - }), - right: tsc.propertyAccessExpression({ - expression: 'options', - name: 'body', - }), - }), - }), - ], - }), - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ text: 'options' }), - isOptional: true, - name: tsc.identifier({ text: 'headers' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'headers', - }), - right: tsc.propertyAccessExpression({ - expression: 'options', - name: 'headers', - }), - }), - }), - ], - }), - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ text: 'options' }), - isOptional: true, - name: tsc.identifier({ text: 'path' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'path', - }), - right: tsc.propertyAccessExpression({ - expression: 'options', - name: 'path', - }), - }), - }), - ], - }), - }), - tsc.ifStatement({ - expression: tsc.propertyAccessExpression({ - expression: tsc.identifier({ text: 'options' }), - isOptional: true, - name: tsc.identifier({ text: 'query' }), - }), - thenStatement: tsc.block({ - statements: [ - tsc.expressionToStatement({ - expression: tsc.binaryExpression({ - left: tsc.propertyAccessExpression({ - expression: 'params', - name: 'query', - }), - right: tsc.propertyAccessExpression({ - expression: 'options', - name: 'query', - }), - }), - }), - ], - }), - }), - tsc.returnVariable({ - expression: 'params', - }), - ], - types: [ - { - extends: tsc.typeReferenceNode({ - typeName: tsc.identifier({ text: 'OptionsLegacyParser' }), - }), - name: TOptionsType, - }, - ], - }), - name: createQueryKeyFn, - }); - file.add(fn); -}; - -const createQueryKeyType = ({ file }: { file: Files[keyof Files] }) => { - const properties: Property[] = [ - { - name: '_id', - type: tsc.keywordTypeNode({ - keyword: 'string', - }), - }, - { - isRequired: false, - name: '_infinite', - type: tsc.keywordTypeNode({ - keyword: 'boolean', - }), - }, - ]; - - const queryKeyType = tsc.typeAliasDeclaration({ - name: queryKeyName, - type: tsc.typeTupleNode({ - types: [ - tsc.typeIntersectionNode({ - types: [ - tsc.typeReferenceNode({ - typeName: `Pick<${TOptionsType}, '${getClientBaseUrlKey(getConfig())}' | 'body' | 'headers' | 'path' | 'query'>`, - }), - tsc.typeInterfaceNode({ - properties, - useLegacyResolution: true, - }), - ], - }), - ], - }), - typeParameters: [ - { - extends: tsc.typeReferenceNode({ - typeName: tsc.identifier({ text: 'OptionsLegacyParser' }), - }), - name: TOptionsType, - }, - ], - }); - file.add(queryKeyType); -}; - -const createTypeData = ({ - client, - file, - operation, - typesModulePath, -}: { - client: Client; - file: Files[keyof Files]; - operation: Operation; - typesModulePath: string; -}) => { - const { name: nameTypeData } = generateImport({ - client, - meta: operation.parameters.length - ? { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - } - : undefined, - nameTransformer: operationDataTypeName, - onImport: (name) => { - file.import({ - asType: true, - module: typesModulePath, - name, - }); - }, - }); - - const typeData = operationOptionsLegacyParserType({ - importedType: nameTypeData, - }); - - return { typeData }; -}; - -const createTypeError = ({ - client, - file, - operation, - pluginName, - typesModulePath, -}: { - client: Client; - file: Files[keyof Files]; - operation: Operation; - pluginName: string; - typesModulePath: string; -}) => { - const config = getConfig(); - - const { name: nameTypeError } = generateImport({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationErrorTypeName, - onImport: (name) => { - file.import({ - asType: true, - module: typesModulePath, - name, - }); - }, - }); - - let typeError: ImportExportItemObject = { - asType: true, - name: nameTypeError, - }; - if (!typeError.name) { - typeError = file.import({ - asType: true, - module: pluginName, - name: 'DefaultError', - }); - } - - const clientPlugin = getClientPlugin(config); - if (clientPlugin.name === '@hey-api/client-axios') { - const axiosError = file.import({ - asType: true, - module: 'axios', - name: 'AxiosError', - }); - typeError = { - ...axiosError, - name: `${axiosError.name}<${typeError.name}>`, - }; - } - - return { typeError }; -}; - -const createTypeResponse = ({ - client, - file, - operation, - typesModulePath, -}: { - client: Client; - file: Files[keyof Files]; - operation: Operation; - typesModulePath: string; -}) => { - const { name: nameTypeResponse } = generateImport({ - client, - meta: { - // TODO: this should be exact ref to operation for consistency, - // but name should work too as operation ID is unique - $ref: operation.name, - name: operation.name, - }, - nameTransformer: operationResponseTypeName, - onImport: (imported) => { - file.import({ - asType: true, - module: typesModulePath, - name: imported, - }); - }, - }); - - const typeResponse = nameTypeResponse || 'void'; - - return { typeResponse }; -}; - -const createQueryKeyLiteral = ({ - id, - isInfinite, -}: { - id: string; - isInfinite?: boolean; -}) => { - const queryKeyLiteral = tsc.arrayLiteralExpression({ - elements: [ - tsc.callExpression({ - functionName: createQueryKeyFn, - parameters: [ - tsc.ots.string(id), - 'options', - isInfinite ? tsc.ots.boolean(true) : undefined, - ], - }), - ], - multiLine: false, - }); - return queryKeyLiteral; -}; - -export const handlerLegacy = ({ - client, - files, - plugin, -}: Parameters< - | TanStackAngularQueryPlugin['LegacyHandler'] - | TanStackReactQueryPlugin['LegacyHandler'] - | TanStackSolidQueryPlugin['LegacyHandler'] - | TanStackSvelteQueryPlugin['LegacyHandler'] - | TanStackVueQueryPlugin['LegacyHandler'] ->[0]) => { - const config = getConfig(); - - if (isLegacyClient(config)) { - throw new Error('TanStack Query plugin does not support legacy clients'); - } - - const file = files[plugin.name]!; - - file.import({ - asType: true, - module: clientModulePath({ config, sourceOutput: plugin.output }), - name: 'OptionsLegacyParser', - }); - - const typesModulePath = relativeModulePath({ - moduleOutput: files.types!.nameWithoutExtension(), - sourceOutput: plugin.output, - }); - - const mutationsType = - plugin.name === '@tanstack/angular-query-experimental' || - plugin.name === '@tanstack/svelte-query' || - plugin.name === '@tanstack/solid-query' - ? 'MutationOptions' - : 'UseMutationOptions'; - - let typeInfiniteData!: ImportExportItem; - let hasCreateInfiniteParamsFunction = false; - let hasCreateQueryKeyParamsFunction = false; - let hasInfiniteQueries = false; - let hasMutations = false; - let hasQueries = false; - - const processedOperations = new Map(); - - for (const service of client.services) { - for (const operation of service.operations) { - // track processed operations to avoid creating duplicates - const operationKey = createOperationKey(operation); - if (processedOperations.has(operationKey)) { - continue; - } - processedOperations.set(operationKey, true); - - const queryFn = [ - config.plugins['@hey-api/sdk']?.config.asClass && - transformClassName({ - config, - name: service.name, - }), - serviceFunctionIdentifier({ - config, - handleIllegal: !config.plugins['@hey-api/sdk']?.config.asClass, - id: operation.name, - operation, - }), - ] - .filter(Boolean) - .join('.'); - let hasUsedQueryFn = false; - - // queries - if ( - plugin.config.queryOptions.enabled && - (['GET', 'POST'] as ReadonlyArray).includes(operation.method) - ) { - if (!hasQueries) { - hasQueries = true; - - if (!hasCreateQueryKeyParamsFunction) { - createQueryKeyType({ file }); - createQueryKeyFunction({ file }); - hasCreateQueryKeyParamsFunction = true; - } - - file.import({ - module: plugin.name, - name: queryOptionsFn, - }); - } - - hasUsedQueryFn = true; - - const { typeData } = createTypeData({ - client, - file, - operation, - typesModulePath, - }); - - const isRequired = isOperationParameterRequired(operation.parameters); - - const queryKeyStatement = tsc.constVariable({ - exportConst: true, - expression: tsc.arrowFunction({ - parameters: [ - { - isRequired, - name: 'options', - type: typeData, - }, - ], - statements: createQueryKeyLiteral({ - id: operation.name, - }), - }), - name: toQueryKeyName({ - config, - id: operation.name, - operation, - }), - }); - file.add(queryKeyStatement); - - const statement = tsc.constVariable({ - // TODO: describe options, same as the actual function call - comment: [], - exportConst: true, - expression: tsc.arrowFunction({ - parameters: [ - { - isRequired, - name: 'options', - type: typeData, - }, - ], - statements: [ - tsc.returnFunctionCall({ - args: [ - tsc.objectExpression({ - obj: [ - { - key: 'queryFn', - value: tsc.arrowFunction({ - async: true, - multiLine: true, - parameters: [ - { - destructure: [ - { - name: 'queryKey', - }, - { - name: 'signal', - }, - ], - }, - ], - statements: [ - tsc.constVariable({ - destructure: true, - expression: tsc.awaitExpression({ - expression: tsc.callExpression({ - functionName: queryFn, - parameters: [ - tsc.objectExpression({ - multiLine: true, - obj: [ - { - spread: 'options', - }, - { - spread: 'queryKey[0]', - }, - { - key: 'signal', - shorthand: true, - value: tsc.identifier({ - text: 'signal', - }), - }, - { - key: 'throwOnError', - value: true, - }, - ], - }), - ], - }), - }), - name: 'data', - }), - tsc.returnVariable({ - expression: 'data', - }), - ], - }), - }, - { - key: 'queryKey', - value: tsc.callExpression({ - functionName: toQueryKeyName({ - config, - id: operation.name, - operation, - }), - parameters: ['options'], - }), - }, - ], - }), - ], - name: queryOptionsFn, - }), - ], - }), - name: toQueryOptionsName({ - config, - id: operation.name, - operation, - }), - // TODO: add type error - // TODO: AxiosError - }); - file.add(statement); - } - - // infinite queries - if ( - plugin.config.infiniteQueryOptions && - (['GET', 'POST'] as ReadonlyArray).includes(operation.method) - ) { - // the actual pagination field might be nested inside parameter, e.g. body - let paginationField!: Model | OperationParameter; - - const paginationParameter = operation.parameters.find((parameter) => { - const paginationRegExp = getPaginationKeywordsRegExp( - config.parser.pagination, - ); - if (paginationRegExp.test(parameter.name)) { - paginationField = parameter; - return true; - } - - if (parameter.in !== 'body') { - return; - } - - if (parameter.export === 'reference') { - const ref = parameter.$refs[0]; - const refModel = client.models.find( - (model) => model.meta?.$ref === ref, - ); - return refModel?.properties.find((property) => { - const paginationRegExp = getPaginationKeywordsRegExp( - config.parser.pagination, - ); - if (paginationRegExp.test(property.name)) { - paginationField = property; - return true; - } - return; - }); - } - - return parameter.properties.find((property) => { - const paginationRegExp = getPaginationKeywordsRegExp( - config.parser.pagination, - ); - if (paginationRegExp.test(property.name)) { - paginationField = property; - return true; - } - return; - }); - }); - - if (paginationParameter && paginationField) { - if (!hasInfiniteQueries) { - hasInfiniteQueries = true; - - if (!hasCreateQueryKeyParamsFunction) { - createQueryKeyType({ file }); - createQueryKeyFunction({ file }); - hasCreateQueryKeyParamsFunction = true; - } - - if (!hasCreateInfiniteParamsFunction) { - createInfiniteParamsFunction({ file }); - hasCreateInfiniteParamsFunction = true; - } - - file.import({ - module: plugin.name, - name: infiniteQueryOptionsFn, - }); - - typeInfiniteData = file.import({ - asType: true, - module: plugin.name, - name: 'InfiniteData', - }); - } - - hasUsedQueryFn = true; - - const { typeData } = createTypeData({ - client, - file, - operation, - typesModulePath, - }); - const { typeError } = createTypeError({ - client, - file, - operation, - pluginName: plugin.name, - typesModulePath, - }); - const { typeResponse } = createTypeResponse({ - client, - file, - operation, - typesModulePath, - }); - - const isRequired = isOperationParameterRequired(operation.parameters); - - const typeQueryKey = `${queryKeyName}<${typeData}>`; - const typePageObjectParam = `Pick<${typeQueryKey}[0], 'body' | 'headers' | 'path' | 'query'>`; - const typePageParam = `${paginationField.base} | ${typePageObjectParam}`; - - const queryKeyStatement = tsc.constVariable({ - exportConst: true, - expression: tsc.arrowFunction({ - parameters: [ - { - isRequired, - name: 'options', - type: typeData, - }, - ], - returnType: typeQueryKey, - statements: createQueryKeyLiteral({ - id: operation.name, - isInfinite: true, - }), - }), - name: toQueryKeyName({ - config, - id: operation.name, - isInfinite: true, - operation, - }), - }); - file.add(queryKeyStatement); - - const statement = tsc.constVariable({ - // TODO: describe options, same as the actual function call - comment: [], - exportConst: true, - expression: tsc.arrowFunction({ - parameters: [ - { - isRequired, - name: 'options', - type: typeData, - }, - ], - statements: [ - tsc.returnFunctionCall({ - args: [ - tsc.objectExpression({ - comments: [ - { - jsdoc: false, - lines: ['@ts-ignore'], - }, - ], - obj: [ - { - key: 'queryFn', - value: tsc.arrowFunction({ - async: true, - multiLine: true, - parameters: [ - { - destructure: [ - { - name: 'pageParam', - }, - { - name: 'queryKey', - }, - { - name: 'signal', - }, - ], - }, - ], - statements: [ - tsc.constVariable({ - comment: [ - { - jsdoc: false, - lines: ['@ts-ignore'], - }, - ], - expression: tsc.conditionalExpression({ - condition: tsc.binaryExpression({ - left: tsc.typeOfExpression({ - text: 'pageParam', - }), - operator: '===', - right: tsc.ots.string('object'), - }), - whenFalse: tsc.objectExpression({ - multiLine: true, - obj: [ - { - key: getPaginationIn( - paginationParameter, - ), - value: tsc.objectExpression({ - multiLine: true, - obj: [ - { - key: paginationField.name, - value: tsc.identifier({ - text: 'pageParam', - }), - }, - ], - }), - }, - ], - }), - whenTrue: tsc.identifier({ - text: 'pageParam', - }), - }), - name: 'page', - typeName: typePageObjectParam, - }), - tsc.constVariable({ - expression: tsc.callExpression({ - functionName: 'createInfiniteParams', - parameters: ['queryKey', 'page'], - }), - name: 'params', - }), - tsc.constVariable({ - destructure: true, - expression: tsc.awaitExpression({ - expression: tsc.callExpression({ - functionName: queryFn, - parameters: [ - tsc.objectExpression({ - multiLine: true, - obj: [ - { - spread: 'options', - }, - { - spread: 'params', - }, - { - key: 'signal', - shorthand: true, - value: tsc.identifier({ - text: 'signal', - }), - }, - { - key: 'throwOnError', - value: true, - }, - ], - }), - ], - }), - }), - name: 'data', - }), - tsc.returnVariable({ - expression: 'data', - }), - ], - }), - }, - { - key: 'queryKey', - value: tsc.callExpression({ - functionName: toQueryKeyName({ - config, - id: operation.name, - isInfinite: true, - operation, - }), - parameters: ['options'], - }), - }, - ], - }), - ], - name: infiniteQueryOptionsFn, - // TODO: better types syntax - types: [ - typeResponse, - typeError.name!, - `${typeof typeInfiniteData === 'string' ? typeInfiniteData : typeInfiniteData.name}<${typeResponse}>`, - typeQueryKey, - typePageParam, - ], - }), - ], - }), - name: toInfiniteQueryOptionsName(operation), - }); - file.add(statement); - } - } - - // mutations - if ( - plugin.config.mutationOptions && - (['DELETE', 'PATCH', 'POST', 'PUT'] as ReadonlyArray).includes( - operation.method, - ) - ) { - if (!hasMutations) { - hasMutations = true; - - file.import({ - asType: true, - module: plugin.name, - name: mutationsType, - }); - } - - hasUsedQueryFn = true; - - const { typeData } = createTypeData({ - client, - file, - operation, - typesModulePath, - }); - const { typeError } = createTypeError({ - client, - file, - operation, - pluginName: plugin.name, - typesModulePath, - }); - const { typeResponse } = createTypeResponse({ - client, - file, - operation, - typesModulePath, - }); - - const fnOptions = 'fnOptions'; - - const expression = tsc.arrowFunction({ - parameters: [ - { - isRequired: false, - name: 'options', - type: `Partial<${typeData}>`, - }, - ], - statements: [ - tsc.constVariable({ - expression: tsc.objectExpression({ - obj: [ - { - key: 'mutationFn', - value: tsc.arrowFunction({ - async: true, - multiLine: true, - parameters: [ - { - name: fnOptions, - }, - ], - statements: [ - tsc.constVariable({ - destructure: true, - expression: tsc.awaitExpression({ - expression: tsc.callExpression({ - functionName: queryFn, - parameters: [ - tsc.objectExpression({ - multiLine: true, - obj: [ - { - spread: 'options', - }, - { - spread: fnOptions, - }, - { - key: 'throwOnError', - value: true, - }, - ], - }), - ], - }), - }), - name: 'data', - }), - tsc.returnVariable({ - expression: 'data', - }), - ], - }), - }, - ], - }), - name: mutationOptionsFn, - // TODO: better types syntax - typeName: `${mutationsType}<${typeResponse}, ${typeError.name}, ${typeData}>`, - }), - tsc.returnVariable({ - expression: mutationOptionsFn, - }), - ], - }); - const statement = tsc.constVariable({ - // TODO: describe options, same as the actual function call - comment: [], - exportConst: true, - expression, - name: toMutationOptionsName(operation), - }); - file.add(statement); - } - - if (hasQueries || hasInfiniteQueries) { - file.import({ - alias: '_heyApiClient', - module: relativeModulePath({ - moduleOutput: files.client!.nameWithoutExtension(), - sourceOutput: plugin.output, - }), - name: 'client', - }); - } - - if (hasUsedQueryFn) { - file.import({ - module: relativeModulePath({ - moduleOutput: files.sdk!.nameWithoutExtension(), - sourceOutput: plugin.output, - }), - name: queryFn.split('.')[0]!, - }); - } - } - } -}; diff --git a/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts b/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts index 8f5e2870a..df488559f 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/react-query/config.ts @@ -1,5 +1,4 @@ import { handler } from '~/plugins/@tanstack/query-core/plugin'; -import { handlerLegacy } from '~/plugins/@tanstack/query-core/plugin-legacy'; import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; @@ -14,7 +13,6 @@ export const defaultConfig: TanStackReactQueryPlugin['Config'] = { }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackReactQueryPlugin['Handler'], - handlerLegacy: handlerLegacy as TanStackReactQueryPlugin['LegacyHandler'], name: '@tanstack/react-query', output: '@tanstack/react-query', resolveConfig: (plugin, context) => { diff --git a/packages/openapi-ts/src/plugins/@tanstack/solid-query/config.ts b/packages/openapi-ts/src/plugins/@tanstack/solid-query/config.ts index 301b8d6d1..9e9cc8938 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/solid-query/config.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/solid-query/config.ts @@ -1,5 +1,4 @@ import { handler } from '~/plugins/@tanstack/query-core/plugin'; -import { handlerLegacy } from '~/plugins/@tanstack/query-core/plugin-legacy'; import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; @@ -14,7 +13,6 @@ export const defaultConfig: TanStackSolidQueryPlugin['Config'] = { }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackSolidQueryPlugin['Handler'], - handlerLegacy: handlerLegacy as TanStackSolidQueryPlugin['LegacyHandler'], name: '@tanstack/solid-query', output: '@tanstack/solid-query', resolveConfig: (plugin, context) => { diff --git a/packages/openapi-ts/src/plugins/@tanstack/svelte-query/config.ts b/packages/openapi-ts/src/plugins/@tanstack/svelte-query/config.ts index c0cf525b6..53258f11d 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/svelte-query/config.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/svelte-query/config.ts @@ -1,5 +1,4 @@ import { handler } from '~/plugins/@tanstack/query-core/plugin'; -import { handlerLegacy } from '~/plugins/@tanstack/query-core/plugin-legacy'; import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; @@ -14,7 +13,6 @@ export const defaultConfig: TanStackSvelteQueryPlugin['Config'] = { }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackSvelteQueryPlugin['Handler'], - handlerLegacy: handlerLegacy as TanStackSvelteQueryPlugin['LegacyHandler'], name: '@tanstack/svelte-query', output: '@tanstack/svelte-query', resolveConfig: (plugin, context) => { diff --git a/packages/openapi-ts/src/plugins/@tanstack/vue-query/config.ts b/packages/openapi-ts/src/plugins/@tanstack/vue-query/config.ts index 826d06617..d11812c3b 100644 --- a/packages/openapi-ts/src/plugins/@tanstack/vue-query/config.ts +++ b/packages/openapi-ts/src/plugins/@tanstack/vue-query/config.ts @@ -1,5 +1,4 @@ import { handler } from '~/plugins/@tanstack/query-core/plugin'; -import { handlerLegacy } from '~/plugins/@tanstack/query-core/plugin-legacy'; import { definePluginConfig } from '~/plugins/shared/utils/config'; import { Api } from './api'; @@ -14,7 +13,6 @@ export const defaultConfig: TanStackVueQueryPlugin['Config'] = { }, dependencies: ['@hey-api/sdk', '@hey-api/typescript'], handler: handler as TanStackVueQueryPlugin['Handler'], - handlerLegacy: handlerLegacy as TanStackVueQueryPlugin['LegacyHandler'], name: '@tanstack/vue-query', output: '@tanstack/vue-query', resolveConfig: (plugin, context) => { diff --git a/packages/openapi-ts/src/plugins/config.ts b/packages/openapi-ts/src/plugins/config.ts index 27198c07b..6cf17087b 100644 --- a/packages/openapi-ts/src/plugins/config.ts +++ b/packages/openapi-ts/src/plugins/config.ts @@ -13,16 +13,6 @@ import type { HeyApiClientNuxtPlugin } from '~/plugins/@hey-api/client-nuxt'; import { defaultConfig as heyApiClientNuxt } from '~/plugins/@hey-api/client-nuxt'; import type { HeyApiClientOfetchPlugin } from '~/plugins/@hey-api/client-ofetch'; import { defaultConfig as heyApiClientOfetch } from '~/plugins/@hey-api/client-ofetch'; -import type { HeyApiClientLegacyAngularPlugin } from '~/plugins/@hey-api/legacy-angular'; -import { defaultConfig as heyApiLegacyAngular } from '~/plugins/@hey-api/legacy-angular'; -import type { HeyApiClientLegacyAxiosPlugin } from '~/plugins/@hey-api/legacy-axios'; -import { defaultConfig as heyApiLegacyAxios } from '~/plugins/@hey-api/legacy-axios'; -import type { HeyApiClientLegacyFetchPlugin } from '~/plugins/@hey-api/legacy-fetch'; -import { defaultConfig as heyApiLegacyFetch } from '~/plugins/@hey-api/legacy-fetch'; -import type { HeyApiClientLegacyNodePlugin } from '~/plugins/@hey-api/legacy-node'; -import { defaultConfig as heyApiLegacyNode } from '~/plugins/@hey-api/legacy-node'; -import type { HeyApiClientLegacyXhrPlugin } from '~/plugins/@hey-api/legacy-xhr'; -import { defaultConfig as heyApiLegacyXhr } from '~/plugins/@hey-api/legacy-xhr'; import type { HeyApiSchemasPlugin } from '~/plugins/@hey-api/schemas'; import { defaultConfig as heyApiSchemas } from '~/plugins/@hey-api/schemas'; import type { HeyApiSdkPlugin } from '~/plugins/@hey-api/sdk'; @@ -73,11 +63,6 @@ export interface PluginConfigMap { '@tanstack/vue-query': TanStackVueQueryPlugin['Types']; arktype: ArktypePlugin['Types']; fastify: FastifyPlugin['Types']; - 'legacy/angular': HeyApiClientLegacyAngularPlugin['Types']; - 'legacy/axios': HeyApiClientLegacyAxiosPlugin['Types']; - 'legacy/fetch': HeyApiClientLegacyFetchPlugin['Types']; - 'legacy/node': HeyApiClientLegacyNodePlugin['Types']; - 'legacy/xhr': HeyApiClientLegacyXhrPlugin['Types']; valibot: ValibotPlugin['Types']; zod: ZodPlugin['Types']; } @@ -104,11 +89,6 @@ export const defaultPluginConfigs: { '@tanstack/vue-query': tanStackVueQuery, arktype, fastify, - 'legacy/angular': heyApiLegacyAngular, - 'legacy/axios': heyApiLegacyAxios, - 'legacy/fetch': heyApiLegacyFetch, - 'legacy/node': heyApiLegacyNode, - 'legacy/xhr': heyApiLegacyXhr, valibot, zod, }; diff --git a/packages/openapi-ts/src/plugins/types.d.ts b/packages/openapi-ts/src/plugins/types.d.ts index af3a02bff..90bbe0813 100644 --- a/packages/openapi-ts/src/plugins/types.d.ts +++ b/packages/openapi-ts/src/plugins/types.d.ts @@ -1,10 +1,7 @@ import type { ValueToObject } from '~/config/utils/config'; import type { Package } from '~/config/utils/package'; -import type { OpenApi as LegacyOpenApi } from '~/openApi'; import type { Hooks } from '~/parser/types/hooks'; import type { PluginInstance } from '~/plugins/shared/utils/instance'; -import type { Client as LegacyClient } from '~/types/client'; -import type { Files } from '~/types/utils'; export type PluginClientNames = | '@hey-api/client-angular' @@ -12,12 +9,7 @@ export type PluginClientNames = | '@hey-api/client-fetch' | '@hey-api/client-next' | '@hey-api/client-nuxt' - | '@hey-api/client-ofetch' - | 'legacy/angular' - | 'legacy/axios' - | 'legacy/fetch' - | 'legacy/node' - | 'legacy/xhr'; + | '@hey-api/client-ofetch'; export type PluginValidatorNames = 'arktype' | 'valibot' | 'zod'; @@ -83,7 +75,6 @@ export namespace Plugin { */ dependencies?: ReadonlyArray; handler: Handler; - handlerLegacy?: LegacyHandler; name: T['config']['name']; output?: NonNullable; /** @@ -159,16 +150,5 @@ export type DefinePlugin< plugin: PluginInstance>; }) => void; Instance: PluginInstance>; - /** - * Plugin implementation for legacy parser. - * - * @deprecated - */ - LegacyHandler: (args: { - client: LegacyClient; - files: Files; - openApi: LegacyOpenApi; - plugin: PluginInstance>; - }) => void; Types: Plugin.Types; }; diff --git a/packages/openapi-ts/src/tsc/utils.ts b/packages/openapi-ts/src/tsc/utils.ts index 67d119320..188b1ddb5 100644 --- a/packages/openapi-ts/src/tsc/utils.ts +++ b/packages/openapi-ts/src/tsc/utils.ts @@ -1,6 +1,5 @@ import ts from 'typescript'; -import { getConfig } from '~/utils/config'; import { unescapeName } from '~/utils/escape'; import type { AccessLevel } from './types'; @@ -66,9 +65,9 @@ export function tsNodeToString({ */ return unescapeUnicode(result); } catch { - if (getConfig().logs.level === 'debug') { - console.warn('Could not decode value:', result); - } + // if (getConfig().logs.level === 'debug') { + // console.warn('Could not decode value:', result); + // } return result; } } diff --git a/packages/openapi-ts/src/types/client.d.ts b/packages/openapi-ts/src/types/client.d.ts deleted file mode 100644 index 54b47e7e0..000000000 --- a/packages/openapi-ts/src/types/client.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { - Client as ParserClient, - Method, - Model, - ModelMeta, - Operation as ParserOperation, - OperationParameter, - OperationResponse, -} from '~/openApi'; - -export type { Method, Model, ModelMeta, OperationParameter, OperationResponse }; - -export interface Operation extends Omit { - service: string; -} - -export interface Service extends Pick { - operations: Operation[]; -} - -export interface Client extends Omit { - services: Service[]; -} diff --git a/packages/openapi-ts/src/types/config.d.ts b/packages/openapi-ts/src/types/config.d.ts index 9895eeb6d..a933a81db 100644 --- a/packages/openapi-ts/src/types/config.d.ts +++ b/packages/openapi-ts/src/types/config.d.ts @@ -76,55 +76,6 @@ export interface UserConfig { }; }[PluginNames] >; - - // DEPRECATED OPTIONS BELOW - - /** - * Manually set base in OpenAPI config instead of inferring from server value - * - * @deprecated - */ - // eslint-disable-next-line typescript-sort-keys/interface - base?: string; - /** - * Opt in to the experimental parser? - * - * @deprecated - * @default true - */ - experimentalParser?: boolean; - /** - * Generate core client classes? - * - * @deprecated - * @default true - */ - exportCore?: boolean; - /** - * Custom client class name. Please note this option is deprecated and - * will be removed in favor of clients. - * - * @deprecated - * @link https://heyapi.dev/openapi-ts/migrating.html#deprecated-name - */ - name?: string; - /** - * Path to custom request file. Please note this option is deprecated and - * will be removed in favor of clients. - * - * @deprecated - * @link https://heyapi.dev/openapi-ts/migrating.html#deprecated-request - */ - request?: string; - /** - * Use options or arguments functions. Please note this option is deprecated and - * will be removed in favor of clients. - * - * @deprecated - * @default true - * @link https://heyapi.dev/openapi-ts/migrating.html#deprecated-useoptions - */ - useOptions?: boolean; /** * @deprecated use `input.watch` instead */ @@ -133,33 +84,24 @@ export interface UserConfig { export type Config = Omit< Required, - | 'base' - | 'input' - | 'logs' - | 'name' - | 'output' - | 'parser' - | 'plugins' - | 'request' - | 'watch' -> & - Pick & { - /** - * Path to the input specification. - */ - input: ReadonlyArray; - logs: Logs; - /** - * Path to the output folder. - */ - output: Output; - /** - * Customize how the input is parsed and transformed before it's passed to - * plugins. - */ - parser: Parser; - pluginOrder: ReadonlyArray; - plugins: { - [K in PluginNames]?: Plugin.ConfigWithName; - }; + 'input' | 'logs' | 'output' | 'parser' | 'plugins' | 'watch' +> & { + /** + * Path to the input specification. + */ + input: ReadonlyArray; + logs: Logs; + /** + * Path to the output folder. + */ + output: Output; + /** + * Customize how the input is parsed and transformed before it's passed to + * plugins. + */ + parser: Parser; + pluginOrder: ReadonlyArray; + plugins: { + [K in PluginNames]?: Plugin.ConfigWithName; }; +}; diff --git a/packages/openapi-ts/src/types/types.d.ts b/packages/openapi-ts/src/types/types.d.ts index dfa6fc258..07360fa7a 100644 --- a/packages/openapi-ts/src/types/types.d.ts +++ b/packages/openapi-ts/src/types/types.d.ts @@ -1,9 +1,3 @@ -import type { Operation } from './client'; - -export namespace LegacyIR { - export type LegacyOperation = Operation; -} - export interface WatchValues { /** * Headers to be sent with each HEAD and/or GET request. This effectively diff --git a/packages/openapi-ts/src/types/utils.d.ts b/packages/openapi-ts/src/types/utils.d.ts index c73a2f710..41e9a180d 100644 --- a/packages/openapi-ts/src/types/utils.d.ts +++ b/packages/openapi-ts/src/types/utils.d.ts @@ -1,5 +1,3 @@ -import type { GeneratedFile } from '~/generate/file'; - /** * Converts all top-level ReadonlyArray properties to Array (shallow). */ @@ -18,9 +16,6 @@ export type DeepPartial = { : T[K]; }; -/** @deprecated */ -export type Files = Record; - /** * Accepts a value, a function returning a value, or a function returning a promise of a value. */ diff --git a/packages/openapi-ts/src/utils/__tests__/enum.test.ts b/packages/openapi-ts/src/utils/__tests__/enum.test.ts deleted file mode 100644 index 39b85169e..000000000 --- a/packages/openapi-ts/src/utils/__tests__/enum.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { enumKey } from '../enum'; - -describe('enumKey', () => { - it('returns custom name', () => { - expect(enumKey('foo', 'bar')).toBe('bar'); - }); - - it('returns number prefixed with underscore', () => { - expect(enumKey(100)).toBe("'_100'"); - }); - - it('returns empty string', () => { - expect(enumKey('')).toBe('EMPTY_STRING'); - }); - - it('returns uppercased value', () => { - expect(enumKey('abc')).toEqual('ABC'); - expect(enumKey('æbc')).toEqual('ÆBC'); - expect(enumKey('æb.c')).toEqual('ÆB_C'); - expect(enumKey('1æb.c')).toEqual('_1ÆB_C'); - expect(enumKey("'quoted'")).toEqual('_QUOTED_'); - }); -}); diff --git a/packages/openapi-ts/src/utils/__tests__/handlebars.test.ts b/packages/openapi-ts/src/utils/__tests__/handlebars.test.ts deleted file mode 100644 index 549bc30c7..000000000 --- a/packages/openapi-ts/src/utils/__tests__/handlebars.test.ts +++ /dev/null @@ -1,257 +0,0 @@ -import Handlebars from 'handlebars'; -import type ts from 'typescript'; -import { describe, expect, it } from 'vitest'; - -import { setConfig } from '../config'; -import { - registerHandlebarHelpers, - registerHandlebarTemplates, -} from '../handlebars'; - -describe('registerHandlebarHelpers', () => { - it('should register the helpers', () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: 'prettier', - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }); - registerHandlebarHelpers(); - const helpers = Object.keys(Handlebars.helpers); - expect(helpers).toContain('camelCase'); - expect(helpers).toContain('equals'); - expect(helpers).toContain('ifServicesResponse'); - expect(helpers).toContain('ifdef'); - expect(helpers).toContain('notEquals'); - expect(helpers).toContain('transformServiceName'); - }); -}); - -describe('registerHandlebarTemplates', () => { - it('should return correct templates', () => { - setConfig({ - configFile: '', - dryRun: false, - experimentalParser: false, - exportCore: true, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: 'prettier', - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: [ - '@hey-api/typescript', - '@hey-api/schemas', - 'legacy/fetch', - '@hey-api/sdk', - ], - plugins: { - '@hey-api/schemas': { - api: {}, - config: { - name: '@hey-api/schemas', - }, - handler: () => {}, - name: '@hey-api/schemas', - output: '', - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - '@hey-api/typescript': { - api: { - schemaToType: () => ({}) as ts.TypeNode, - }, - config: { - enums: 'javascript', - name: '@hey-api/typescript', - }, - handler: () => {}, - name: '@hey-api/typescript', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }); - const templates = registerHandlebarTemplates(); - expect(templates.core.settings).toBeDefined(); - expect(templates.core.apiError).toBeDefined(); - expect(templates.core.apiRequestOptions).toBeDefined(); - expect(templates.core.apiResult).toBeDefined(); - expect(templates.core.request).toBeDefined(); - }); -}); diff --git a/packages/openapi-ts/src/utils/__tests__/parse.test.ts b/packages/openapi-ts/src/utils/__tests__/parse.test.ts deleted file mode 100644 index 7ddd70b9c..000000000 --- a/packages/openapi-ts/src/utils/__tests__/parse.test.ts +++ /dev/null @@ -1,400 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { operationNameFn } from '~/openApi/common/parser/operation'; - -import { setConfig } from '../config'; - -describe('operationNameFn', () => { - const optionsCommon: Parameters[0] = { - configFile: '', - dryRun: true, - experimentalParser: false, - exportCore: false, - input: [ - { - path: '', - watch: { - enabled: false, - interval: 1_000, - timeout: 60_000, - }, - }, - ], - interactive: false, - logs: { - file: true, - level: 'info', - path: process.cwd(), - }, - output: { - clean: false, - fileName: { - case: 'preserve', - name: '{{name}}', - suffix: '.gen', - }, - format: null, - importFileExtension: undefined, - indexFile: true, - lint: null, - path: '', - tsConfig: null, - tsConfigPath: null, - }, - parser: { - hooks: {}, - pagination: { - keywords: [], - }, - transforms: { - enums: { - case: 'preserve', - enabled: false, - mode: 'root', - name: '', - }, - propertiesRequiredByDefault: false, - readWrite: { - enabled: false, - requests: { - case: 'preserve', - name: '', - }, - responses: { - case: 'preserve', - name: '', - }, - }, - }, - validate_EXPERIMENTAL: false, - }, - pluginOrder: ['legacy/fetch', '@hey-api/sdk'], - plugins: { - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - operationId: true, - response: 'body', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - 'legacy/fetch': { - config: { - name: 'legacy/fetch', - }, - handler: () => {}, - name: 'legacy/fetch', - output: '', - tags: ['client'], - }, - }, - useOptions: false, - }; - - const options1: Parameters[0] = { - ...optionsCommon, - plugins: { - ...optionsCommon.plugins, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - operationId: true, - response: 'body', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - }, - }; - - const options2: Parameters[0] = { - ...optionsCommon, - plugins: { - ...optionsCommon.plugins, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - operationId: false, - response: 'body', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - }, - }; - - const options3: Parameters[0] = { - ...optionsCommon, - pluginOrder: ['@hey-api/client-fetch', '@hey-api/sdk'], - plugins: { - '@hey-api/client-fetch': { - api: {}, - config: { - name: '@hey-api/client-fetch', - }, - handler: () => {}, - name: '@hey-api/client-fetch', - output: '', - tags: ['client'], - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - operationId: true, - response: 'body', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - }, - }; - - const options4: Parameters[0] = { - ...optionsCommon, - pluginOrder: ['@hey-api/client-fetch', '@hey-api/sdk'], - plugins: { - '@hey-api/client-fetch': { - api: {}, - config: { - name: '@hey-api/client-fetch', - }, - handler: () => {}, - name: '@hey-api/client-fetch', - output: '', - tags: ['client'], - }, - '@hey-api/sdk': { - api: {}, - config: { - name: '@hey-api/sdk', - operationId: false, - response: 'body', - }, - handler: () => {}, - name: '@hey-api/sdk', - output: '', - }, - }, - }; - - it.each([ - { - expected: 'getAllUsers', - method: 'GET', - operationId: 'GetAllUsers', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'getApiUsers', - method: 'GET', - operationId: undefined, - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'postApiUsers', - method: 'POST', - operationId: undefined, - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'getAllUsers', - method: 'GET', - operationId: 'GetAllUsers', - options: options1, - url: '/api/v1/users', - }, - { - expected: 'getApiV1Users', - method: 'GET', - operationId: undefined, - options: options1, - url: '/api/v1/users', - }, - { - expected: 'postApiV1Users', - method: 'POST', - operationId: undefined, - options: options1, - url: '/api/v1/users', - }, - { - expected: 'getApiV1UsersById', - method: 'GET', - operationId: undefined, - options: options1, - url: '/api/v1/users/{id}', - }, - { - expected: 'postApiV1UsersById', - method: 'POST', - operationId: undefined, - options: options1, - url: '/api/v1/users/{id}', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'fooBar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'FooBar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'Foo Bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'foo bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'foo-bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'foo_bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'foo.bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: '@foo.bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: '$foo.bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: '_foo.bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: '-foo.bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: '123.foo.bar', - options: options1, - url: '/api/v{api-version}/users', - }, - { - expected: 'getApiV1Users', - method: 'GET', - operationId: 'GetAllUsers', - options: options2, - url: '/api/v1/users', - }, - { - expected: 'getApiUsers', - method: 'GET', - operationId: 'fooBar', - options: options2, - url: '/api/v{api-version}/users', - }, - { - expected: 'getApiUsersByUserIdLocationByLocationId', - method: 'GET', - operationId: 'fooBar', - options: options2, - url: '/api/v{api-version}/users/{userId}/location/{locationId}', - }, - { - expected: 'getAllUsers', - method: 'GET', - operationId: 'GetAllUsers', - options: options3, - url: '/api/v1/users', - }, - { - expected: 'fooBar', - method: 'GET', - operationId: 'fooBar', - options: options3, - url: '/api/v{api-version}/users', - }, - { - expected: 'getApiV1Users', - method: 'GET', - operationId: 'GetAllUsers', - options: options4, - url: '/api/v1/users', - }, - { - expected: 'getApiVbyApiVersionUsers', - method: 'GET', - operationId: 'fooBar', - options: options4, - url: '/api/v{api-version}/users', - }, - { - expected: 'getApiVbyApiVersionUsersByUserIdLocationByLocationId', - method: 'GET', - operationId: 'fooBar', - options: options4, - url: '/api/v{api-version}/users/{userId}/location/{locationId}', - }, - ])( - 'getOperationName($url, $method, { operationId: $useOperationId }, $operationId) -> $expected', - ({ expected, method, operationId, options, url }) => { - setConfig(options); - expect( - operationNameFn({ - config: options, - method, - operationId, - path: url, - }), - ).toBe(expected); - }, - ); -}); diff --git a/packages/openapi-ts/src/utils/__tests__/postprocess.test.ts b/packages/openapi-ts/src/utils/__tests__/postprocess.test.ts deleted file mode 100644 index 44faf4cb8..000000000 --- a/packages/openapi-ts/src/utils/__tests__/postprocess.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -import { parseLegacy } from '~/openApi'; -import type { Config } from '~/types/config'; - -import { getServiceName, postProcessClient } from '../postprocess'; - -vi.mock('../config', () => { - const config: Partial = { - plugins: {}, - }; - return { - getConfig: () => config, - isLegacyClient: vi.fn().mockReturnValue(true), - }; -}); - -describe('getServiceName', () => { - it.each([ - { expected: '', input: '' }, - { expected: 'FooBar', input: 'FooBar' }, - { expected: 'FooBar', input: 'Foo Bar' }, - { expected: 'FooBar', input: 'foo bar' }, - { expected: 'FooBar', input: '@fooBar' }, - { expected: 'FooBar', input: '$fooBar' }, - { expected: 'FooBar', input: '123fooBar' }, - { - expected: 'NonAsciiÆøåÆøÅöôêÊ字符串', - input: 'non-ascii-æøåÆØÅöôêÊ字符串', - }, - ])('getServiceName($input) -> $expected', ({ expected, input }) => { - expect(getServiceName(input)).toEqual(expected); - }); -}); - -describe('getServices', () => { - it('should create a unnamed service if tags are empty', () => { - const parserClient = parseLegacy({ - openApi: { - info: { - title: 'x', - version: '1', - }, - openapi: '3.0.0', - paths: { - '/api/trips': { - get: { - responses: { - 200: { - description: 'x', - }, - default: { - description: 'default', - }, - }, - tags: [], - }, - }, - }, - }, - }); - const { services } = postProcessClient(parserClient, {} as Config); - - expect(services).toHaveLength(1); - expect(services[0]!.name).toEqual('Default'); - }); -}); - -describe('getServices', () => { - it('should create a unnamed service if tags are empty', () => { - const parserClient = parseLegacy({ - openApi: { - info: { - title: 'x', - version: '1', - }, - openapi: '3.0.0', - paths: { - '/api/trips': { - get: { - responses: { - 200: { - description: 'x', - }, - default: { - description: 'default', - }, - }, - tags: [], - }, - }, - }, - }, - }); - const { services } = postProcessClient(parserClient, {} as Config); - - expect(services).toHaveLength(1); - expect(services[0]!.name).toEqual('Default'); - }); -}); diff --git a/packages/openapi-ts/src/utils/__tests__/sort.test.ts b/packages/openapi-ts/src/utils/__tests__/sort.test.ts deleted file mode 100644 index 04bb1f33d..000000000 --- a/packages/openapi-ts/src/utils/__tests__/sort.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import type { Model, Service } from '~/types/client'; - -import { sort, sortByName } from '../sort'; - -describe('sort', () => { - it('should return correct index', () => { - expect(sort('a', 'b')).toEqual(-1); - expect(sort('b', 'a')).toEqual(1); - expect(sort('a', 'a')).toEqual(0); - expect(sort('', '')).toEqual(0); - }); -}); - -describe('sortByName', () => { - it('should handle empty lists', () => { - expect(sortByName([])).toEqual([]); - }); - - it('should return sorted list of models', () => { - const john: Model = { - $refs: [], - base: 'John', - description: null, - enum: [], - enums: [], - export: 'interface', - imports: [], - in: '', - isDefinition: true, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: 'John', - properties: [], - template: null, - type: 'John', - }; - const jane: Model = { - $refs: [], - base: 'Jane', - description: null, - enum: [], - enums: [], - export: 'interface', - imports: [], - in: '', - isDefinition: true, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: 'Jane', - properties: [], - template: null, - type: 'Jane', - }; - const doe: Model = { - $refs: [], - base: 'Doe', - description: null, - enum: [], - enums: [], - export: 'interface', - imports: [], - in: '', - isDefinition: true, - isNullable: false, - isReadOnly: false, - isRequired: false, - link: null, - name: 'Doe', - properties: [], - template: null, - type: 'Doe', - }; - const models: Model[] = [john, jane, doe]; - expect(sortByName(models)).toEqual([doe, jane, john]); - }); - - it('should return sorted list of services', () => { - const john: Service = { - $refs: [], - imports: [], - name: 'John', - operations: [], - }; - const jane: Service = { - $refs: [], - imports: [], - name: 'Jane', - operations: [], - }; - const doe: Service = { - $refs: [], - imports: [], - name: 'Doe', - operations: [], - }; - const services: Service[] = [john, jane, doe]; - expect(sortByName(services)).toEqual([doe, jane, john]); - }); - - it('should throw errors when trying to sort without a name entry', () => { - const values = ['some', 'string', 'array']; - // @ts-expect-error - expect(() => sortByName(values)).toThrow(TypeError); - }); -}); diff --git a/packages/openapi-ts/src/utils/__tests__/type.test.ts b/packages/openapi-ts/src/utils/__tests__/type.test.ts deleted file mode 100644 index 2474d75fe..000000000 --- a/packages/openapi-ts/src/utils/__tests__/type.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { describe, expect, it, type MockedFunction, vi } from 'vitest'; - -import type { Config } from '~/types/config'; - -import { isLegacyClient } from '../config'; -import { transformTypeKeyName } from '../type'; - -vi.mock('../config', () => { - const config: Partial = {}; - return { - getConfig: () => config, - isLegacyClient: vi.fn().mockReturnValue(true), - }; -}); - -describe('transformTypeKeyName', () => { - describe('legacy client', () => { - it.each([ - { expected: '', input: '' }, - { expected: 'foobar', input: 'foobar' }, - { expected: 'fooBar', input: 'fooBar' }, - { expected: 'fooBar', input: 'foo_bar' }, - { expected: 'fooBar', input: 'foo-bar' }, - { expected: 'fooBar', input: 'foo.bar' }, - { expected: 'fooBar', input: '@foo.bar' }, - { expected: 'fooBar', input: '$foo.bar' }, - { expected: 'fooBar', input: '123.foo.bar' }, - { expected: 'fooBar', input: 'Foo-Bar' }, - { expected: 'fooBar', input: 'FOO-BAR' }, - { expected: 'fooBar', input: 'foo[bar]' }, - { expected: 'fooBarArray', input: 'foo.bar[]' }, - ])('$input -> $expected', ({ expected, input }) => { - (isLegacyClient as MockedFunction).mockImplementationOnce( - () => true, - ); - expect(transformTypeKeyName(input)).toBe(expected); - }); - }); - - describe('client', () => { - it.each([ - { expected: '', input: '' }, - { expected: 'foobar', input: 'foobar' }, - { expected: 'fooBar', input: 'fooBar' }, - { expected: 'fooBar', input: 'foo_bar' }, - { expected: 'fooBar', input: 'foo-bar' }, - { expected: 'fooBar', input: 'foo.bar' }, - { expected: 'fooBar', input: '@foo.bar' }, - { expected: 'fooBar', input: '$foo.bar' }, - { expected: 'fooBar', input: '123.foo.bar' }, - { expected: 'fooBar', input: 'Foo-Bar' }, - { expected: 'fooBar', input: 'FOO-BAR' }, - { expected: 'fooBar', input: 'foo[bar]' }, - { expected: 'fooBarArray', input: 'foo.bar[]' }, - ])('$input -> $input', ({ input }) => { - (isLegacyClient as MockedFunction).mockImplementationOnce( - () => false, - ); - expect(transformTypeKeyName(input)).toBe(input); - }); - }); -}); diff --git a/packages/openapi-ts/src/utils/__tests__/unique.test.ts b/packages/openapi-ts/src/utils/__tests__/unique.test.ts deleted file mode 100644 index ef4260578..000000000 --- a/packages/openapi-ts/src/utils/__tests__/unique.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { unique } from '../unique'; - -describe('unique', () => { - it.each([ - { arr: ['a', 'b', 'c'], index: 0, result: true, value: 'a' }, - { arr: ['a', 'b', 'c'], index: 1, result: false, value: 'a' }, - { arr: ['a', 'b', 'c'], index: 2, result: false, value: 'a' }, - { arr: ['z', 'a', 'b'], index: 1, result: true, value: 'a' }, - { arr: ['y', 'z', 'a'], index: 2, result: true, value: 'a' }, - ])( - 'unique($value, $index, $arr) -> $result', - ({ arr, index, result, value }) => { - expect(unique(value, index, arr)).toEqual(result); - }, - ); - - it.each([ - { expected: ['a', 'b', 'c'], input: ['a', 'a', 'b', 'c', 'b', 'b'] }, - { expected: [1, 2, 3, 4, 5, 6], input: [1, 2, 3, 4, 4, 5, 6, 3] }, - ])( - 'should filter: $input to the unique array: $expected', - ({ expected, input }) => { - expect(input.filter(unique)).toEqual(expected); - }, - ); -}); diff --git a/packages/openapi-ts/src/utils/config.ts b/packages/openapi-ts/src/utils/config.ts deleted file mode 100644 index 304753734..000000000 --- a/packages/openapi-ts/src/utils/config.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { getClientPlugin } from '~/plugins/@hey-api/client-core/utils'; -import type { Config } from '~/types/config'; - -let _config: Config; - -export const getConfig = () => { - const config = _config; - const plugin = getClientPlugin(config); - // patch legacy config to avoid breaking handlebars - // @ts-expect-error - config.client = plugin; - return config; -}; - -export const setConfig = (config: Config) => { - _config = config; - return getConfig(); -}; - -export const isLegacyClient = (config: Config) => { - const plugin = getClientPlugin(config); - return plugin.name.startsWith('legacy/'); -}; - -/** - * Wrap legacy `name` option so we don't use it when not using legacy clients. - */ -export const legacyNameFromConfig = (config: Config) => { - if (!isLegacyClient(config)) { - return; - } - - return config.name; -}; diff --git a/packages/openapi-ts/src/utils/const.ts b/packages/openapi-ts/src/utils/const.ts deleted file mode 100644 index 3c01b4b75..000000000 --- a/packages/openapi-ts/src/utils/const.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const refParametersPartial = '#/components/parameters/'; - -export const refSchemasPartial = '#/components/schemas/'; diff --git a/packages/openapi-ts/src/utils/enum.ts b/packages/openapi-ts/src/utils/enum.ts deleted file mode 100644 index eef7f66df..000000000 --- a/packages/openapi-ts/src/utils/enum.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { Enum, Model } from '~/openApi'; -import { ensureValidTypeScriptJavaScriptIdentifier } from '~/openApi'; - -import { unescapeName } from './escape'; -import { sort } from './sort'; -import { unique } from './unique'; - -/** - * Sanitizes names of enums, so they are valid typescript identifiers of a certain form. - * - * 1: Replace all characters not legal as part of identifier with '_' - * 2: Add '_' prefix if first character of enum name has character not legal for start of identifier - * 3: Add '_' where the string transitions from lowercase to uppercase - * 4: Transform the whole string to uppercase - * - * Javascript identifier regexp pattern retrieved from https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers - */ -export const enumKey = (value?: string | number, customName?: string) => { - if (customName) { - return customName; - } - // prefix numbers with underscore - if (typeof value === 'number') { - return `'_${value}'`; - } - - let key = ''; - if (typeof value === 'string') { - key = value - .replace(/[^$\u200c\u200d\p{ID_Continue}]/gu, '_') - .replace(/^([^$_\p{ID_Start}])/u, '_$1') - .replace(/(\p{Lowercase})(\p{Uppercase}+)/gu, '$1_$2'); - } - key = key.trim(); - if (!key) { - key = 'empty_string'; - } - return key.toUpperCase(); -}; - -export const enumUnionType = (enums: Enum[]) => - enums - .map((enumerator) => enumValue(enumerator.value, true)) - .filter(unique) - .join(' | '); - -export const enumValue = (value?: string | number, union: boolean = false) => { - if (typeof value === 'string') { - if (value.includes("'") && union) { - return `"${value}"`; - } - return `'${value}'`; - } - return value; -}; - -export const enumEntry = (enumerator: Enum) => { - const key = enumKey(enumerator.value, enumerator.customName); - const value = enumValue(enumerator.value); - return { key, value }; -}; - -/** - * Represent enum in `meta` object for deduplication - */ -export const enumMeta = (model: Model): Required['meta'] => { - // serialize enum values in namespace for quick lookup - const serialized = model.enum - .map((enumerator) => enumEntry(enumerator)) - .sort((a, b) => sort(a.key, b.key)) - .map((enumerator) => `${enumerator.key}=${enumerator.value}`) - .join('&'); - return { - $ref: `enum/${model.name}/${serialized}`, - name: ensureValidTypeScriptJavaScriptIdentifier(unescapeName(model.name)), - }; -}; diff --git a/packages/openapi-ts/src/utils/getHttpRequestName.ts b/packages/openapi-ts/src/utils/getHttpRequestName.ts deleted file mode 100644 index 8b4e74aa5..000000000 --- a/packages/openapi-ts/src/utils/getHttpRequestName.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { PluginClientNames } from '~/plugins/types'; - -/** - * Generate the HttpRequest filename based on the selected client - * @param client HTTP client to generate - */ -export const getHttpRequestName = (clientName: PluginClientNames): string => { - switch (clientName) { - case 'legacy/angular': - return 'AngularHttpRequest'; - case 'legacy/axios': - return 'AxiosHttpRequest'; - case 'legacy/fetch': - return 'FetchHttpRequest'; - case 'legacy/node': - return 'NodeHttpRequest'; - case 'legacy/xhr': - return 'XHRHttpRequest'; - default: - return ''; - } -}; diff --git a/packages/openapi-ts/src/utils/handlebars.ts b/packages/openapi-ts/src/utils/handlebars.ts deleted file mode 100644 index b8eb52dc3..000000000 --- a/packages/openapi-ts/src/utils/handlebars.ts +++ /dev/null @@ -1,343 +0,0 @@ -import Handlebars from 'handlebars'; - -// @ts-expect-error -import templateClient from '~/legacy/handlebars/compiled/client'; -// @ts-expect-error -import angularGetHeaders from '~/legacy/handlebars/compiled/core/angular/getHeaders'; -// @ts-expect-error -import angularGetRequestBody from '~/legacy/handlebars/compiled/core/angular/getRequestBody'; -// @ts-expect-error -import angularGetResponseBody from '~/legacy/handlebars/compiled/core/angular/getResponseBody'; -// @ts-expect-error -import angularGetResponseHeader from '~/legacy/handlebars/compiled/core/angular/getResponseHeader'; -// @ts-expect-error -import angularRequest from '~/legacy/handlebars/compiled/core/angular/request'; -// @ts-expect-error -import angularSendRequest from '~/legacy/handlebars/compiled/core/angular/sendRequest'; -// @ts-expect-error -import templateCoreApiError from '~/legacy/handlebars/compiled/core/ApiError'; -// @ts-expect-error -import templateCoreApiRequestOptions from '~/legacy/handlebars/compiled/core/ApiRequestOptions'; -// @ts-expect-error -import templateCoreApiResult from '~/legacy/handlebars/compiled/core/ApiResult'; -// @ts-expect-error -import axiosGetHeaders from '~/legacy/handlebars/compiled/core/axios/getHeaders'; -// @ts-expect-error -import axiosGetRequestBody from '~/legacy/handlebars/compiled/core/axios/getRequestBody'; -// @ts-expect-error -import axiosGetResponseBody from '~/legacy/handlebars/compiled/core/axios/getResponseBody'; -// @ts-expect-error -import axiosGetResponseHeader from '~/legacy/handlebars/compiled/core/axios/getResponseHeader'; -// @ts-expect-error -import axiosRequest from '~/legacy/handlebars/compiled/core/axios/request'; -// @ts-expect-error -import axiosSendRequest from '~/legacy/handlebars/compiled/core/axios/sendRequest'; -// @ts-expect-error -import templateCoreBaseHttpRequest from '~/legacy/handlebars/compiled/core/BaseHttpRequest'; -// @ts-expect-error -import templateCancelablePromise from '~/legacy/handlebars/compiled/core/CancelablePromise'; -// @ts-expect-error -import fetchGetHeaders from '~/legacy/handlebars/compiled/core/fetch/getHeaders'; -// @ts-expect-error -import fetchGetRequestBody from '~/legacy/handlebars/compiled/core/fetch/getRequestBody'; -// @ts-expect-error -import fetchGetResponseBody from '~/legacy/handlebars/compiled/core/fetch/getResponseBody'; -// @ts-expect-error -import fetchGetResponseHeader from '~/legacy/handlebars/compiled/core/fetch/getResponseHeader'; -// @ts-expect-error -import fetchRequest from '~/legacy/handlebars/compiled/core/fetch/request'; -// @ts-expect-error -import fetchSendRequest from '~/legacy/handlebars/compiled/core/fetch/sendRequest'; -// @ts-expect-error -import functionBase64 from '~/legacy/handlebars/compiled/core/functions/base64'; -// @ts-expect-error -import functionCatchErrorCodes from '~/legacy/handlebars/compiled/core/functions/catchErrorCodes'; -// @ts-expect-error -import functionGetFormData from '~/legacy/handlebars/compiled/core/functions/getFormData'; -// @ts-expect-error -import functionGetQueryString from '~/legacy/handlebars/compiled/core/functions/getQueryString'; -// @ts-expect-error -import functionGetUrl from '~/legacy/handlebars/compiled/core/functions/getUrl'; -// @ts-expect-error -import functionIsBlob from '~/legacy/handlebars/compiled/core/functions/isBlob'; -// @ts-expect-error -import functionIsFormData from '~/legacy/handlebars/compiled/core/functions/isFormData'; -// @ts-expect-error -import functionIsString from '~/legacy/handlebars/compiled/core/functions/isString'; -// @ts-expect-error -import functionIsStringWithValue from '~/legacy/handlebars/compiled/core/functions/isStringWithValue'; -// @ts-expect-error -import functionIsSuccess from '~/legacy/handlebars/compiled/core/functions/isSuccess'; -// @ts-expect-error -import functionResolve from '~/legacy/handlebars/compiled/core/functions/resolve'; -// @ts-expect-error -import templateCoreHttpRequest from '~/legacy/handlebars/compiled/core/HttpRequest'; -// @ts-expect-error -import templateCoreSettings from '~/legacy/handlebars/compiled/core/OpenAPI'; -// @ts-expect-error -import templateCoreRequest from '~/legacy/handlebars/compiled/core/request'; -// @ts-expect-error -import xhrGetHeaders from '~/legacy/handlebars/compiled/core/xhr/getHeaders'; -// @ts-expect-error -import xhrGetRequestBody from '~/legacy/handlebars/compiled/core/xhr/getRequestBody'; -// @ts-expect-error -import xhrGetResponseBody from '~/legacy/handlebars/compiled/core/xhr/getResponseBody'; -// @ts-expect-error -import xhrGetResponseHeader from '~/legacy/handlebars/compiled/core/xhr/getResponseHeader'; -// @ts-expect-error -import xhrRequest from '~/legacy/handlebars/compiled/core/xhr/request'; -// @ts-expect-error -import xhrSendRequest from '~/legacy/handlebars/compiled/core/xhr/sendRequest'; - -import { getConfig } from './config'; -import { stringCase } from './stringCase'; -import { transformClassName } from './transform'; - -export const registerHandlebarHelpers = (): void => { - Handlebars.registerHelper( - 'camelCase', - function (this: unknown, name: string) { - return stringCase({ - case: 'camelCase', - value: name, - }); - }, - ); - - Handlebars.registerHelper( - 'equals', - function ( - this: unknown, - a: string, - b: string, - options: Handlebars.HelperOptions, - ) { - return a === b ? options.fn(this) : options.inverse(this); - }, - ); - - Handlebars.registerHelper( - 'ifServicesResponse', - function (this: unknown, value: string, options: Handlebars.HelperOptions) { - return getConfig().plugins['@hey-api/sdk']?.config.response === value - ? options.fn(this) - : options.inverse(this); - }, - ); - - Handlebars.registerHelper('ifdef', function (this: unknown, ...args): string { - const options = args.pop(); - if (!args.every((value) => !value)) { - return options.fn(this); - } - return options.inverse(this); - }); - - Handlebars.registerHelper( - 'notEquals', - function ( - this: unknown, - a: string, - b: string, - options: Handlebars.HelperOptions, - ) { - return a !== b ? options.fn(this) : options.inverse(this); - }, - ); - - Handlebars.registerHelper( - 'transformServiceName', - function (this: unknown, name: string) { - return transformClassName({ - config: getConfig(), - name, - }); - }, - ); -}; - -export interface Templates { - client: Handlebars.TemplateDelegate; - core: { - apiError: Handlebars.TemplateDelegate; - apiRequestOptions: Handlebars.TemplateDelegate; - apiResult: Handlebars.TemplateDelegate; - baseHttpRequest: Handlebars.TemplateDelegate; - cancelablePromise: Handlebars.TemplateDelegate; - httpRequest: Handlebars.TemplateDelegate; - request: Handlebars.TemplateDelegate; - settings: Handlebars.TemplateDelegate; - }; -} - -/** - * Read all the Handlebar templates that we need and return a wrapper object - * so we can easily access the templates in our generator/write functions. - */ -export const registerHandlebarTemplates = (): Templates => { - registerHandlebarHelpers(); - - // Main templates (entry points for the files we write to disk) - const templates: Templates = { - client: Handlebars.template(templateClient), - core: { - apiError: Handlebars.template(templateCoreApiError), - apiRequestOptions: Handlebars.template(templateCoreApiRequestOptions), - apiResult: Handlebars.template(templateCoreApiResult), - baseHttpRequest: Handlebars.template(templateCoreBaseHttpRequest), - cancelablePromise: Handlebars.template(templateCancelablePromise), - httpRequest: Handlebars.template(templateCoreHttpRequest), - request: Handlebars.template(templateCoreRequest), - settings: Handlebars.template(templateCoreSettings), - }, - }; - - // Generic functions used in 'request' file @see src/legacy/handlebars/templates/core/request.hbs for more info - Handlebars.registerPartial( - 'functions/base64', - Handlebars.template(functionBase64), - ); - Handlebars.registerPartial( - 'functions/catchErrorCodes', - Handlebars.template(functionCatchErrorCodes), - ); - Handlebars.registerPartial( - 'functions/getFormData', - Handlebars.template(functionGetFormData), - ); - Handlebars.registerPartial( - 'functions/getQueryString', - Handlebars.template(functionGetQueryString), - ); - Handlebars.registerPartial( - 'functions/getUrl', - Handlebars.template(functionGetUrl), - ); - Handlebars.registerPartial( - 'functions/isBlob', - Handlebars.template(functionIsBlob), - ); - Handlebars.registerPartial( - 'functions/isFormData', - Handlebars.template(functionIsFormData), - ); - Handlebars.registerPartial( - 'functions/isString', - Handlebars.template(functionIsString), - ); - Handlebars.registerPartial( - 'functions/isStringWithValue', - Handlebars.template(functionIsStringWithValue), - ); - Handlebars.registerPartial( - 'functions/isSuccess', - Handlebars.template(functionIsSuccess), - ); - Handlebars.registerPartial( - 'functions/resolve', - Handlebars.template(functionResolve), - ); - - // Specific files for the fetch client implementation - Handlebars.registerPartial( - 'fetch/getHeaders', - Handlebars.template(fetchGetHeaders), - ); - Handlebars.registerPartial( - 'fetch/getRequestBody', - Handlebars.template(fetchGetRequestBody), - ); - Handlebars.registerPartial( - 'fetch/getResponseBody', - Handlebars.template(fetchGetResponseBody), - ); - Handlebars.registerPartial( - 'fetch/getResponseHeader', - Handlebars.template(fetchGetResponseHeader), - ); - Handlebars.registerPartial( - 'fetch/request', - Handlebars.template(fetchRequest), - ); - Handlebars.registerPartial( - 'fetch/sendRequest', - Handlebars.template(fetchSendRequest), - ); - - // Specific files for the xhr client implementation - Handlebars.registerPartial( - 'xhr/getHeaders', - Handlebars.template(xhrGetHeaders), - ); - Handlebars.registerPartial( - 'xhr/getRequestBody', - Handlebars.template(xhrGetRequestBody), - ); - Handlebars.registerPartial( - 'xhr/getResponseBody', - Handlebars.template(xhrGetResponseBody), - ); - Handlebars.registerPartial( - 'xhr/getResponseHeader', - Handlebars.template(xhrGetResponseHeader), - ); - Handlebars.registerPartial('xhr/request', Handlebars.template(xhrRequest)); - Handlebars.registerPartial( - 'xhr/sendRequest', - Handlebars.template(xhrSendRequest), - ); - - // Specific files for the axios client implementation - Handlebars.registerPartial( - 'axios/getHeaders', - Handlebars.template(axiosGetHeaders), - ); - Handlebars.registerPartial( - 'axios/getRequestBody', - Handlebars.template(axiosGetRequestBody), - ); - Handlebars.registerPartial( - 'axios/getResponseBody', - Handlebars.template(axiosGetResponseBody), - ); - Handlebars.registerPartial( - 'axios/getResponseHeader', - Handlebars.template(axiosGetResponseHeader), - ); - Handlebars.registerPartial( - 'axios/request', - Handlebars.template(axiosRequest), - ); - Handlebars.registerPartial( - 'axios/sendRequest', - Handlebars.template(axiosSendRequest), - ); - - // Specific files for the angular client implementation - Handlebars.registerPartial( - 'angular/getHeaders', - Handlebars.template(angularGetHeaders), - ); - Handlebars.registerPartial( - 'angular/getRequestBody', - Handlebars.template(angularGetRequestBody), - ); - Handlebars.registerPartial( - 'angular/getResponseBody', - Handlebars.template(angularGetResponseBody), - ); - Handlebars.registerPartial( - 'angular/getResponseHeader', - Handlebars.template(angularGetResponseHeader), - ); - Handlebars.registerPartial( - 'angular/request', - Handlebars.template(angularRequest), - ); - Handlebars.registerPartial( - 'angular/sendRequest', - Handlebars.template(angularSendRequest), - ); - - return templates; -}; diff --git a/packages/openapi-ts/src/utils/meta.ts b/packages/openapi-ts/src/utils/meta.ts deleted file mode 100644 index af055a89e..000000000 --- a/packages/openapi-ts/src/utils/meta.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { getType } from '~/openApi'; - -import { refParametersPartial, refSchemasPartial } from './const'; -import { reservedJavaScriptKeywordsRegExp } from './regexp'; -import { cleanAndTransformTypeName } from './transform'; - -export const getParametersMeta = (definitionName: string) => { - const definitionType = getType({ type: definitionName }); - /** - * Prefix parameter names to avoid name conflicts with schemas. - * Assuming people are mostly interested in importing schema types - * and don't care about this name as much. It should be resolved in - * a cleaner way, there just isn't a good deduplication strategy - * today. This is a workaround in the meantime, hopefully reducing - * the chance of conflicts. - * - * Example where this would break: schema named `ParameterFoo` and - * parameter named `Foo` (this would transform to `ParameterFoo`) - * - * Note: there's a related code to this workaround in `getType()` - * method that needs to be cleaned up when this is addressed. - */ - const name = `Parameter${definitionType.base.replace(reservedJavaScriptKeywordsRegExp, '_$1')}`; - const meta = { - $ref: refParametersPartial + definitionName, - name, - }; - return meta; -}; - -/** - * @param definitionName Name of the schema definition in OpenAPI specification. - * @returns meta object - */ -export const getSchemasMeta = (definitionName: string) => { - const name = cleanAndTransformTypeName(definitionName); - const meta = { - $ref: refSchemasPartial + definitionName, - name, - }; - return meta; -}; diff --git a/packages/openapi-ts/src/utils/postprocess.ts b/packages/openapi-ts/src/utils/postprocess.ts deleted file mode 100644 index 6e6b6b9aa..000000000 --- a/packages/openapi-ts/src/utils/postprocess.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { Client as ParserClient, Model } from '~/openApi'; -import { sanitizeNamespaceIdentifier } from '~/openApi'; -import type { Client, Operation, Service } from '~/types/client'; -import type { Config } from '~/types/config'; - -import { getConfig, legacyNameFromConfig } from './config'; -import { sort } from './sort'; -import { stringCase } from './stringCase'; -import { unique } from './unique'; - -/** - * Post process client - * @param client Client object with all the models, services, etc. - */ -export function postProcessClient( - client: Omit, - config: Config, -): Client { - return { - ...client, - config, - models: client.models.map((model) => postProcessModel(model)), - services: postProcessOperations(client.operations).map(postProcessService), - types: {}, - }; -} - -const postProcessModel = (model: Model): Model => ({ - ...model, - $refs: model.$refs.filter((value, index, arr) => unique(value, index, arr)), - enum: model.enum.filter( - (value, index, arr) => - arr.findIndex((item) => item.value === value.value) === index, - ), - enums: model.enums.filter( - (value, index, arr) => - arr.findIndex((item) => item.name === value.name) === index, - ), - imports: model.imports - .filter( - (value, index, arr) => unique(value, index, arr) && value !== model.name, - ) - .sort(sort), -}); - -const postProcessOperations = ( - operations: ParserClient['operations'], -): Client['services'] => { - const config = getConfig(); - - const services = new Map(); - - operations.forEach((parserOperation) => { - const tags = - parserOperation.tags?.length && - (config.plugins['@hey-api/sdk']?.config.asClass || - legacyNameFromConfig(config)) - ? parserOperation.tags.filter(unique) - : ['Default']; - tags.forEach((tag) => { - const operation: Operation = { - ...parserOperation, - service: getServiceName(tag), - }; - const service = - services.get(operation.service) || getNewService(operation); - service.$refs = [...service.$refs, ...operation.$refs]; - service.imports = [...service.imports, ...operation.imports]; - service.operations = [...service.operations, operation]; - services.set(operation.service, service); - }); - }); - - return Array.from(services.values()); -}; - -const postProcessService = (service: Service): Service => { - const clone = { ...service }; - clone.operations = postProcessServiceOperations(clone); - clone.operations.forEach((operation) => { - clone.imports.push(...operation.imports); - }); - clone.imports = clone.imports.filter(unique).sort(sort); - return clone; -}; - -const postProcessServiceOperations = (service: Service): Operation[] => { - const names = new Map(); - - return service.operations.map((operation) => { - const clone = { ...operation }; - - // Parse the service parameters and successes, very similar to how we parse - // properties of models. These methods will extend the type if needed. - clone.imports.push( - ...clone.parameters.flatMap((parameter) => parameter.imports), - ); - const successResponses = clone.responses.filter((response) => - response.responseTypes.includes('success'), - ); - clone.imports.push(...successResponses.flatMap((result) => result.imports)); - - // Check if the operation name is unique, if not then prefix this with a number - const name = clone.name; - const index = names.get(name) || 0; - if (index > 0) { - clone.name = `${name}${index}`; - } - names.set(name, index + 1); - - return clone; - }); -}; - -export const getNewService = (operation: Operation): Service => ({ - $refs: [], - imports: [], - name: operation.service, - operations: [], -}); - -/** - * Convert the input value to a correct service name. This converts - * the input string to PascalCase. - */ -export const getServiceName = (value: string): string => - stringCase({ - case: 'PascalCase', - value: sanitizeNamespaceIdentifier(value), - }); diff --git a/packages/openapi-ts/src/utils/sort.ts b/packages/openapi-ts/src/utils/sort.ts deleted file mode 100644 index 809e6c944..000000000 --- a/packages/openapi-ts/src/utils/sort.ts +++ /dev/null @@ -1,12 +0,0 @@ -export function sort(a: string, b: string): number { - const nameA = a.toLocaleLowerCase(); - const nameB = b.toLocaleLowerCase(); - return nameA.localeCompare(nameB, 'en'); -} - -export const sorterByName = (a: T, b: T) => - sort(a.name, b.name); - -export function sortByName(items: T[]): T[] { - return items.sort(sorterByName); -} diff --git a/packages/openapi-ts/src/utils/transform.ts b/packages/openapi-ts/src/utils/transform.ts index a766161e6..89f8ddd2f 100644 --- a/packages/openapi-ts/src/utils/transform.ts +++ b/packages/openapi-ts/src/utils/transform.ts @@ -1,10 +1,5 @@ -import { ensureValidTypeScriptJavaScriptIdentifier } from '~/openApi'; import type { Config } from '~/types/config'; -import { getConfig } from './config'; -import { reservedJavaScriptKeywordsRegExp } from './regexp'; -import { stringCase } from './stringCase'; - export const transformClassName = ({ config, name, @@ -27,33 +22,3 @@ export const transformClassName = ({ return name; }; - -export const transformTypeName = (name: string) => { - const config = getConfig(); - if (config.plugins['@hey-api/typescript']?.config.style === 'PascalCase') { - return stringCase({ - case: 'PascalCase', - value: name, - }); - } - return name; -}; - -/** - * This method is meant to be used to process definition names - * and return a cleaned up, transformed version that is legal - * to use in the output code. - * - * For example, a definition with name "400" would result in "_400", - * "import" would result in "_import", etc. This also respects the - * casing configuration for types. - * - * @param name Name of the definition in OpenAPI specification. - * @returns A cleaned up, transformed name usable in output code. - */ -export const cleanAndTransformTypeName = (name: string) => { - const transformed = transformTypeName(name); - const cleaned = ensureValidTypeScriptJavaScriptIdentifier(transformed); - const result = cleaned.replace(reservedJavaScriptKeywordsRegExp, '_$1'); - return result; -}; diff --git a/packages/openapi-ts/src/utils/type.ts b/packages/openapi-ts/src/utils/type.ts deleted file mode 100644 index 04767ebb8..000000000 --- a/packages/openapi-ts/src/utils/type.ts +++ /dev/null @@ -1,351 +0,0 @@ -import type ts from 'typescript'; - -import type { Model } from '~/openApi'; -import { sanitizeOperationParameterName } from '~/openApi'; -import { type Property, tsc } from '~/tsc'; -import type { Client } from '~/types/client'; - -import { getConfig, isLegacyClient } from './config'; -import { refSchemasPartial } from './const'; -import { enumValue } from './enum'; -import { escapeComment, escapeName, unescapeName } from './escape'; -import { getSchemasMeta } from './meta'; -import { reservedJavaScriptKeywordsRegExp } from './regexp'; -import { stringCase } from './stringCase'; -import { unique } from './unique'; - -export const isModelDate = (model: Model): boolean => - model.format === 'date' || model.format === 'date-time'; - -const base = (model: Model) => { - const config = getConfig(); - - if (model.base === 'binary') { - return tsc.typeUnionNode({ - types: ['Blob', 'File'], - }); - } - - if ( - config.plugins['@hey-api/transformers']?.config.dates && - isModelDate(model) - ) { - return tsc.typeNode('Date'); - } - - return tsc.typeNode(model.base); -}; - -const typeReference = (model: Model) => { - // nullable is false when base is null to avoid duplicate null statements - const isNullable = model.base === 'null' ? false : model.isNullable; - let typeNode = base(model); - /** - * special handling for single reference. The current approach didn't handle - * transformed names, this fixes that. We should add a more robust solution, - * but this will work for now. - * {@link https://github.com/hey-api/openapi-ts/issues/768} - */ - if (model.export === 'reference' && model.$refs.length === 1) { - if (model.$refs[0]!.startsWith(refSchemasPartial)) { - const meta = getSchemasMeta(model.base); - typeNode = tsc.typeNode(meta.name); - } - } - const unionNode = tsc.typeUnionNode({ - isNullable, - types: [typeNode], - }); - return unionNode; -}; - -const typeArray = (model: Model) => { - if (model.link) { - // We treat an array of `model.link` as constant size array definition. - if (Array.isArray(model.link)) { - const types = model.link.map((m) => toType(m)); - const tuple = tsc.typeTupleNode({ - isNullable: model.isNullable, - types, - }); - return tuple; - } - - // Special case where we use tuple to define constant size array. - if ( - model.export === 'array' && - model.maxItems && - model.minItems && - model.maxItems === model.minItems && - model.maxItems <= 100 - ) { - const types = Array(model.maxItems).fill(toType(model.link)); - const tuple = tsc.typeTupleNode({ - isNullable: model.isNullable, - types, - }); - return tuple; - } - - return tsc.typeArrayNode([toType(model.link)], model.isNullable); - } - - return tsc.typeArrayNode([base(model)], model.isNullable); -}; - -const typeEnum = (model: Model) => { - const values = model.enum.map((enumerator) => enumValue(enumerator.value)); - return tsc.typeUnionNode({ - isNullable: model.isNullable, - types: values, - }); -}; - -const typeDict = (model: Model) => { - const type = - model.link && !Array.isArray(model.link) ? toType(model.link) : base(model); - return tsc.typeRecordNode(['string'], [type], model.isNullable, true); -}; - -const typeUnionOrIntersection = ({ - model, - style, -}: { - model: Model; - style: 'intersection' | 'union'; -}) => { - const types = model.properties - .map((model) => { - const str = tsc.nodeToString({ - node: toType(model), - unescape: true, - }); - return str; - }) - .filter(unique); - - const node = - style === 'union' - ? tsc.typeUnionNode({ - // avoid printing duplicate null statements - isNullable: - model.isNullable && - !model.properties.find((property) => property.isNullable), - types, - }) - : tsc.typeIntersectionNode({ - isNullable: model.isNullable, - types, - }); - - // top-level models don't need parentheses around them - if (model.meta) { - return node; - } - - return tsc.typeParenthesizedNode({ - type: node, - }); -}; - -const typeInterface = (model: Model) => { - if (!model.properties.length) { - return tsc.typeNode('unknown'); - } - - const config = getConfig(); - - const isLegacy = isLegacyClient(config); - - const properties: Property[] = model.properties.map((property) => { - let maybeRequired = property.isRequired ? '' : '?'; - let value = toType(property); - let name = !isLegacy - ? escapeName(unescapeName(transformTypeKeyName(property.name))) - : // special test for 1XX status codes. We need a more robust system - // for escaping values depending on context in which they're printed, - // but since this works for client packages, it's not worth it right now - /^\dXX$/.test(property.name) - ? escapeName(property.name) - : property.name; - // special case for additional properties type - if (property.name === '[key: string]') { - name = property.name; - if (maybeRequired) { - maybeRequired = ''; - value = tsc.typeUnionNode({ - types: [value, 'undefined'], - }); - } - } - return { - comment: [ - property.description && escapeComment(property.description), - property.deprecated && '@deprecated', - ], - isReadOnly: property.isReadOnly, - isRequired: maybeRequired === '', - name, - type: value, - }; - }); - - return tsc.typeInterfaceNode({ - isNullable: model.isNullable, - properties, - useLegacyResolution: true, - }); -}; - -export const toType = (model: Model): ts.TypeNode => { - switch (model.export) { - case 'all-of': - return typeUnionOrIntersection({ - model, - style: 'intersection', - }); - case 'any-of': - case 'one-of': - return typeUnionOrIntersection({ - model, - style: 'union', - }); - case 'array': - return typeArray(model); - case 'dictionary': - return typeDict(model); - case 'enum': - return typeEnum(model); - case 'interface': - return typeInterface(model); - case 'const': - case 'generic': - case 'reference': - default: - return typeReference(model); - } -}; - -export interface SetUniqueTypeNameResult { - /** - * Did this function add a new property to the `client.types` object? - */ - created: boolean; - /** - * Unique name for the exported type. - */ - name: string; -} - -/** - * Generates a unique name for the exported type for given model meta. - * @param args.client Internal client instance - * @param args.count Unique key for deduplication - * @param args.create If a name record does not exist, should it be created? - * @param args.meta Meta property from the model - * @param args.nameTransformer Function for transforming name into the final - * value. In different contexts, a different strategy might be used. For - * example, slashes `/` are invalid in TypeScript identifiers, but okay in - * a JavaScript object key name. - * @returns {SetUniqueTypeNameResult} - */ -export const setUniqueTypeName = ({ - client, - count = 1, - create = false, - meta, - nameTransformer, -}: Pick, 'meta'> & { - client: Client; - count?: number; - create?: boolean; - nameTransformer?: (value: string) => string; -}): SetUniqueTypeNameResult => { - let result: SetUniqueTypeNameResult = { - created: false, - name: '', - }; - let name = meta.name; - if (nameTransformer) { - name = nameTransformer(name); - } - if (count > 1) { - name = `${name}${count}`; - } - const type = client.types[name]; - if (!type) { - if (create) { - client.types[name] = meta; - result = { - created: true, - name, - }; - } - } else if (type.$ref === meta.$ref) { - result = { - created: false, - name, - }; - } else { - result = setUniqueTypeName({ - client, - count: count + 1, - create, - meta, - nameTransformer, - }); - } - return result; -}; - -export interface UnsetUniqueTypeNameResult { - /** - * Did this function delete a property from the `client.types` object? - */ - deleted: boolean; - /** - * Unique name removed from the `client.types` object. - */ - name: string; -} - -export const unsetUniqueTypeName = ({ - client, - name, -}: { - client: Client; - name: string; -}): UnsetUniqueTypeNameResult => { - let result: UnsetUniqueTypeNameResult = { - deleted: false, - name: '', - }; - if (!client.types[name]) { - return result; - } - delete client.types[name]; - result = { - deleted: true, - name, - }; - return result; -}; - -/** - * Replaces any invalid characters from a parameter name. - * For example: 'filter.someProperty' becomes 'filterSomeProperty'. - */ -export const transformTypeKeyName = (value: string): string => { - const config = getConfig(); - - // transform only for legacy clients - if (!isLegacyClient(config)) { - return value; - } - - const name = stringCase({ - case: 'camelCase', - value: sanitizeOperationParameterName(value), - }).replace(reservedJavaScriptKeywordsRegExp, '_$1'); - return name; -}; diff --git a/packages/openapi-ts/src/utils/unique.ts b/packages/openapi-ts/src/utils/unique.ts deleted file mode 100644 index 2e02e59ee..000000000 --- a/packages/openapi-ts/src/utils/unique.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function unique(value: T, index: number, arr: T[]): boolean { - return arr.indexOf(value) === index; -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0a6de0369..6b2ba4eec 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -112,54 +112,15 @@ importers: dev: devDependencies: - '@angular-devkit/build-angular': - specifier: 19.2.19 - version: 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(@angular/compiler@19.2.15)(@angular/platform-server@19.2.0(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.9.3)))(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.39.0)(yaml@2.8.1))(yaml@2.8.1) - '@angular/animations': - specifier: 19.2.15 - version: 19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)) - '@angular/cli': - specifier: 19.2.19 - version: 19.2.19(@types/node@22.10.5)(chokidar@4.0.3) - '@angular/common': - specifier: 19.2.15 - version: 19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2) - '@angular/compiler': - specifier: 19.2.15 - version: 19.2.15 - '@angular/compiler-cli': - specifier: 19.2.15 - version: 19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3) - '@angular/core': - specifier: 19.2.15 - version: 19.2.15(rxjs@7.8.2)(zone.js@0.15.1) - '@angular/forms': - specifier: 19.2.15 - version: 19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(rxjs@7.8.2) - '@angular/platform-browser': - specifier: 19.2.15 - version: 19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)) - '@angular/platform-browser-dynamic': - specifier: 19.2.15 - version: 19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))) - '@angular/router': - specifier: 19.2.15 - version: 19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(rxjs@7.8.2) - '@config/vite-base': - specifier: workspace:* - version: link:../packages/config-vite-base '@hey-api/codegen-core': specifier: workspace:* version: link:../packages/codegen-core - '@hey-api/custom-client': - specifier: workspace:* - version: link:../packages/custom-client '@hey-api/openapi-ts': specifier: workspace:* version: link:../packages/openapi-ts '@pinia/colada': specifier: 0.17.7 - version: 0.17.7(pinia@3.0.3(typescript@5.9.3)(vue@3.5.13(typescript@5.9.3)))(vue@3.5.13(typescript@5.9.3)) + version: 0.17.7(pinia@3.0.3(typescript@5.9.3)(vue@3.5.20(typescript@5.9.3)))(vue@3.5.20(typescript@5.9.3)) '@tanstack/angular-query-experimental': specifier: 5.73.3 version: 5.73.3(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)) @@ -174,61 +135,16 @@ importers: version: 5.73.3(svelte@5.19.9) '@tanstack/vue-query': specifier: 5.73.3 - version: 5.73.3(vue@3.5.13(typescript@5.9.3)) - '@types/cross-spawn': - specifier: 6.0.6 - version: 6.0.6 - ajv: - specifier: 8.17.1 - version: 8.17.1 + version: 5.73.3(vue@3.5.20(typescript@5.9.3)) arktype: specifier: 2.1.25 version: 2.1.25 - axios: - specifier: 1.8.2 - version: 1.8.2 - cross-spawn: - specifier: 7.0.6 - version: 7.0.6 - eslint: - specifier: 9.17.0 - version: 9.17.0(jiti@2.6.1) - fastify: - specifier: 5.2.0 - version: 5.2.0 - glob: - specifier: 11.0.3 - version: 11.0.3 - node-fetch: - specifier: 3.3.2 - version: 3.3.2 - nuxt: - specifier: 3.14.1592 - version: 3.14.1592(@netlify/blobs@9.1.2)(@parcel/watcher@2.5.1)(@types/node@22.10.5)(db0@0.3.2)(encoding@0.1.13)(eslint@9.17.0(jiti@2.6.1))(ioredis@5.7.0)(less@4.2.2)(magicast@0.3.5)(optionator@0.9.4)(rolldown@1.0.0-beta.45)(rollup@4.50.0)(sass@1.85.0)(terser@5.39.0)(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.39.0)(yaml@2.8.1)) - ofetch: - specifier: 1.4.1 - version: 1.4.1 - prettier: - specifier: 3.4.2 - version: 3.4.2 - rxjs: - specifier: 7.8.2 - version: 7.8.2 - ts-node: - specifier: 10.9.2 - version: 10.9.2(@types/node@22.10.5)(typescript@5.9.3) - tslib: - specifier: 2.8.1 - version: 2.8.1 typescript: specifier: 5.9.3 version: 5.9.3 valibot: specifier: 1.1.0 version: 1.1.0(typescript@5.9.3) - vue: - specifier: 3.5.13 - version: 3.5.13(typescript@5.9.3) zod: specifier: 4.1.12 version: 4.1.12 @@ -1335,9 +1251,6 @@ importers: commander: specifier: 14.0.1 version: 14.0.1 - handlebars: - specifier: 4.7.8 - version: 4.7.8 open: specifier: 10.2.0 version: 10.2.0 @@ -1387,12 +1300,9 @@ importers: eslint: specifier: 9.17.0 version: 9.17.0(jiti@2.6.1) - glob: - specifier: 11.0.3 - version: 11.0.3 nuxt: specifier: 3.14.1592 - version: 3.14.1592(@netlify/blobs@9.1.2)(@parcel/watcher@2.5.1)(@types/node@22.10.5)(db0@0.3.2)(encoding@0.1.13)(eslint@9.17.0(jiti@2.6.1))(ioredis@5.7.0)(less@4.2.2)(magicast@0.3.5)(optionator@0.9.4)(rolldown@1.0.0-beta.45)(rollup@4.50.0)(sass@1.85.0)(terser@5.43.1)(typescript@5.9.3)(vite@7.1.2(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) + version: 3.14.1592(@netlify/blobs@9.1.2)(@parcel/watcher@2.5.1)(@types/node@22.10.5)(db0@0.3.2)(encoding@0.1.13)(eslint@9.17.0(jiti@2.6.1))(ioredis@5.7.0)(less@4.2.2)(magicast@0.3.5)(optionator@0.9.4)(rolldown@1.0.0-beta.45)(rollup@4.50.0)(sass@1.85.0)(terser@5.43.1)(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)) ofetch: specifier: 1.4.1 version: 1.4.1 @@ -1419,7 +1329,7 @@ importers: devDependencies: '@angular-devkit/build-angular': specifier: 19.2.19 - version: 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(@angular/compiler@19.2.15)(@angular/platform-server@19.2.0(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.9.3)))(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1))(yaml@2.8.1) + version: 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(@angular/compiler@19.2.15)(@angular/platform-server@19.2.0(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.9.3)))(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.39.0)(yaml@2.8.1))(yaml@2.8.1) '@angular/animations': specifier: 19.2.15 version: 19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)) @@ -1501,15 +1411,12 @@ importers: fastify: specifier: 5.2.0 version: 5.2.0 - glob: - specifier: 11.0.3 - version: 11.0.3 node-fetch: specifier: 3.3.2 version: 3.3.2 nuxt: specifier: 3.14.1592 - version: 3.14.1592(@netlify/blobs@9.1.2)(@parcel/watcher@2.5.1)(@types/node@22.10.5)(db0@0.3.2)(encoding@0.1.13)(eslint@9.17.0(jiti@2.6.1))(ioredis@5.7.0)(less@4.2.2)(magicast@0.3.5)(optionator@0.9.4)(rolldown@1.0.0-beta.45)(rollup@4.50.0)(sass@1.85.0)(terser@5.43.1)(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) + version: 3.14.1592(@netlify/blobs@9.1.2)(@parcel/watcher@2.5.1)(@types/node@22.10.5)(db0@0.3.2)(encoding@0.1.13)(eslint@9.17.0(jiti@2.6.1))(ioredis@5.7.0)(less@4.2.2)(magicast@0.3.5)(optionator@0.9.4)(rolldown@1.0.0-beta.45)(rollup@4.50.0)(sass@1.85.0)(terser@5.39.0)(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.39.0)(yaml@2.8.1)) ofetch: specifier: 1.4.1 version: 1.4.1 @@ -9293,11 +9200,6 @@ packages: resolution: {integrity: sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==} hasBin: true - glob@11.0.3: - resolution: {integrity: sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==} - engines: {node: 20 || >=22} - hasBin: true - glob@7.2.3: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Glob versions prior to v9 are no longer supported @@ -9372,11 +9274,6 @@ packages: handle-thing@2.0.1: resolution: {integrity: sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg==} - handlebars@4.7.8: - resolution: {integrity: sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==} - engines: {node: '>=0.4.7'} - hasBin: true - has-bigints@1.1.0: resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} engines: {node: '>= 0.4'} @@ -9943,10 +9840,6 @@ packages: jackspeak@3.4.3: resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==} - jackspeak@4.1.1: - resolution: {integrity: sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==} - engines: {node: 20 || >=22} - jasmine-core@4.6.1: resolution: {integrity: sha512-VYz/BjjmC3klLJlLwA4Kw8ytk0zDSmbbDLNs794VnWmkcCB7I9aAL/D48VNQtmITyPvea2C3jdUMfc3kAoy0PQ==} @@ -11272,10 +11165,6 @@ packages: resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} engines: {node: '>=16 || 14 >=14.18'} - path-scurry@2.0.0: - resolution: {integrity: sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==} - engines: {node: 20 || >=22} - path-to-regexp@0.1.10: resolution: {integrity: sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==} @@ -13104,11 +12993,6 @@ packages: ufo@1.6.1: resolution: {integrity: sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==} - uglify-js@3.19.3: - resolution: {integrity: sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==} - engines: {node: '>=0.8.0'} - hasBin: true - ultrahtml@1.6.0: resolution: {integrity: sha512-R9fBn90VTJrqqLDwyMph+HGne8eqY1iPfYhPzZrvKpIfwkWZbcYlfpsb8B9dTvBfpy1/hqAD7Wi8EKfP9e8zdw==} @@ -14148,9 +14032,6 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} - wordwrap@1.0.0: - resolution: {integrity: sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==} - wrap-ansi@6.2.0: resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==} engines: {node: '>=8'} @@ -14352,7 +14233,7 @@ snapshots: dependencies: '@ampproject/remapping': 2.3.0 '@angular-devkit/architect': 0.1902.0(chokidar@4.0.3) - '@angular-devkit/build-webpack': 0.1902.0(chokidar@4.0.3)(webpack-dev-server@5.2.0(webpack@5.98.0))(webpack@5.98.0) + '@angular-devkit/build-webpack': 0.1902.0(chokidar@4.0.3)(webpack-dev-server@5.2.0(webpack@5.98.0(esbuild@0.25.0)))(webpack@5.98.0(esbuild@0.25.0)) '@angular-devkit/core': 19.2.0(chokidar@4.0.3) '@angular/build': 19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/platform-server@19.2.0(@angular/common@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.0(@angular/animations@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))))(@angular/ssr@19.2.15(5c03da8199d2fcdf9ff93b70f9349edd))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(less@4.2.2)(postcss@8.5.2)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.8.3)))(terser@5.39.0)(typescript@5.8.3)(yaml@2.8.1) '@angular/compiler-cli': 19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3) @@ -14366,11 +14247,11 @@ snapshots: '@babel/preset-env': 7.26.9(@babel/core@7.26.9) '@babel/runtime': 7.26.9 '@discoveryjs/json-ext': 0.6.3 - '@ngtools/webpack': 19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(typescript@5.8.3)(webpack@5.98.0) + '@ngtools/webpack': 19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(typescript@5.8.3)(webpack@5.98.0(esbuild@0.25.0)) '@vitejs/plugin-basic-ssl': 1.2.0(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.39.0)(yaml@2.8.1)) ansi-colors: 4.1.3 autoprefixer: 10.4.20(postcss@8.5.2) - babel-loader: 9.2.1(@babel/core@7.26.9)(webpack@5.98.0) + babel-loader: 9.2.1(@babel/core@7.26.9)(webpack@5.98.0(esbuild@0.25.0)) browserslist: 4.25.4 copy-webpack-plugin: 12.0.2(webpack@5.98.0) css-loader: 7.1.2(webpack@5.98.0) @@ -14390,7 +14271,7 @@ snapshots: picomatch: 4.0.2 piscina: 4.8.0 postcss: 8.5.2 - postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0) + postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0(esbuild@0.25.0)) resolve-url-loader: 5.0.0 rxjs: 7.8.1 sass: 1.85.0 @@ -14403,8 +14284,8 @@ snapshots: tslib: 2.8.1 typescript: 5.8.3 webpack: 5.98.0(esbuild@0.25.0) - webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.4)) - webpack-dev-server: 5.2.0(webpack@5.98.0) + webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.0)) + webpack-dev-server: 5.2.0(webpack@5.98.0(esbuild@0.25.0)) webpack-merge: 6.0.1 webpack-subresource-integrity: 5.1.0(webpack@5.98.0) optionalDependencies: @@ -14440,7 +14321,7 @@ snapshots: dependencies: '@ampproject/remapping': 2.3.0 '@angular-devkit/architect': 0.1902.0(chokidar@4.0.3) - '@angular-devkit/build-webpack': 0.1902.0(chokidar@4.0.3)(webpack-dev-server@5.2.0(webpack@5.98.0))(webpack@5.98.0) + '@angular-devkit/build-webpack': 0.1902.0(chokidar@4.0.3)(webpack-dev-server@5.2.0(webpack@5.98.0(esbuild@0.25.0)))(webpack@5.98.0(esbuild@0.25.0)) '@angular-devkit/core': 19.2.0(chokidar@4.0.3) '@angular/build': 19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/platform-server@19.2.0(@angular/common@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.0(@angular/animations@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1))))(@angular/ssr@19.2.15(5c03da8199d2fcdf9ff93b70f9349edd))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(less@4.2.2)(postcss@8.5.2)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.8.3)))(terser@5.39.0)(typescript@5.8.3)(yaml@2.8.1) '@angular/compiler-cli': 19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3) @@ -14454,11 +14335,11 @@ snapshots: '@babel/preset-env': 7.26.9(@babel/core@7.26.9) '@babel/runtime': 7.26.9 '@discoveryjs/json-ext': 0.6.3 - '@ngtools/webpack': 19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(typescript@5.8.3)(webpack@5.98.0) + '@ngtools/webpack': 19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(typescript@5.8.3)(webpack@5.98.0(esbuild@0.25.0)) '@vitejs/plugin-basic-ssl': 1.2.0(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) ansi-colors: 4.1.3 autoprefixer: 10.4.20(postcss@8.5.2) - babel-loader: 9.2.1(@babel/core@7.26.9)(webpack@5.98.0) + babel-loader: 9.2.1(@babel/core@7.26.9)(webpack@5.98.0(esbuild@0.25.0)) browserslist: 4.25.4 copy-webpack-plugin: 12.0.2(webpack@5.98.0) css-loader: 7.1.2(webpack@5.98.0) @@ -14478,7 +14359,7 @@ snapshots: picomatch: 4.0.2 piscina: 4.8.0 postcss: 8.5.2 - postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0) + postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0(esbuild@0.25.0)) resolve-url-loader: 5.0.0 rxjs: 7.8.1 sass: 1.85.0 @@ -14491,8 +14372,8 @@ snapshots: tslib: 2.8.1 typescript: 5.8.3 webpack: 5.98.0(esbuild@0.25.0) - webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.4)) - webpack-dev-server: 5.2.0(webpack@5.98.0) + webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.0)) + webpack-dev-server: 5.2.0(webpack@5.98.0(esbuild@0.25.0)) webpack-merge: 6.0.1 webpack-subresource-integrity: 5.1.0(webpack@5.98.0) optionalDependencies: @@ -14566,7 +14447,7 @@ snapshots: picomatch: 4.0.2 piscina: 4.8.0 postcss: 8.5.2 - postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0) + postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0(esbuild@0.25.0)) resolve-url-loader: 5.0.0 rxjs: 7.8.1 sass: 1.85.0 @@ -14579,8 +14460,8 @@ snapshots: tslib: 2.8.1 typescript: 5.8.3 webpack: 5.98.0(esbuild@0.25.4) - webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.4)) - webpack-dev-server: 5.2.2(webpack@5.98.0(esbuild@0.25.4)) + webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.0)) + webpack-dev-server: 5.2.2(webpack@5.98.0) webpack-merge: 6.0.1 webpack-subresource-integrity: 5.1.0(webpack@5.98.0) optionalDependencies: @@ -14616,7 +14497,7 @@ snapshots: dependencies: '@ampproject/remapping': 2.3.0 '@angular-devkit/architect': 0.1902.19(chokidar@4.0.3) - '@angular-devkit/build-webpack': 0.1902.19(chokidar@4.0.3)(webpack-dev-server@5.2.2(webpack@5.98.0(esbuild@0.25.4)))(webpack@5.98.0(esbuild@0.25.4)) + '@angular-devkit/build-webpack': 0.1902.19(chokidar@4.0.3)(webpack-dev-server@5.2.2(webpack@5.98.0))(webpack@5.98.0) '@angular-devkit/core': 19.2.19(chokidar@4.0.3) '@angular/build': 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(@angular/compiler@19.2.15)(@angular/platform-server@19.2.0(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(less@4.2.2)(postcss@8.5.2)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.9.3)))(terser@5.39.0)(typescript@5.9.3)(yaml@2.8.1) '@angular/compiler-cli': 19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3) @@ -14630,7 +14511,7 @@ snapshots: '@babel/preset-env': 7.26.9(@babel/core@7.26.10) '@babel/runtime': 7.26.10 '@discoveryjs/json-ext': 0.6.3 - '@ngtools/webpack': 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(typescript@5.9.3)(webpack@5.98.0(esbuild@0.25.4)) + '@ngtools/webpack': 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(typescript@5.9.3)(webpack@5.98.0) '@vitejs/plugin-basic-ssl': 1.2.0(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.39.0)(yaml@2.8.1)) ansi-colors: 4.1.3 autoprefixer: 10.4.20(postcss@8.5.2) @@ -14654,94 +14535,7 @@ snapshots: picomatch: 4.0.2 piscina: 4.8.0 postcss: 8.5.2 - postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.9.3)(webpack@5.98.0(esbuild@0.25.4)) - resolve-url-loader: 5.0.0 - rxjs: 7.8.1 - sass: 1.85.0 - sass-loader: 16.0.5(sass@1.85.0)(webpack@5.98.0) - semver: 7.7.1 - source-map-loader: 5.0.0(webpack@5.98.0) - source-map-support: 0.5.21 - terser: 5.39.0 - tree-kill: 1.2.2 - tslib: 2.8.1 - typescript: 5.9.3 - webpack: 5.98.0(esbuild@0.25.4) - webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.4)) - webpack-dev-server: 5.2.2(webpack@5.98.0(esbuild@0.25.4)) - webpack-merge: 6.0.1 - webpack-subresource-integrity: 5.1.0(webpack@5.98.0) - optionalDependencies: - '@angular/platform-server': 19.2.0(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))) - esbuild: 0.25.4 - karma: 6.4.4 - tailwindcss: 3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.9.3)) - transitivePeerDependencies: - - '@angular/compiler' - - '@rspack/core' - - '@swc/core' - - '@types/node' - - bufferutil - - chokidar - - debug - - html-webpack-plugin - - jiti - - lightningcss - - node-sass - - sass-embedded - - stylus - - sugarss - - supports-color - - tsx - - uglify-js - - utf-8-validate - - vite - - webpack-cli - - yaml - - '@angular-devkit/build-angular@19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(@angular/compiler@19.2.15)(@angular/platform-server@19.2.0(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.9.3)))(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1))(yaml@2.8.1)': - dependencies: - '@ampproject/remapping': 2.3.0 - '@angular-devkit/architect': 0.1902.19(chokidar@4.0.3) - '@angular-devkit/build-webpack': 0.1902.19(chokidar@4.0.3)(webpack-dev-server@5.2.2(webpack@5.98.0(esbuild@0.25.4)))(webpack@5.98.0(esbuild@0.25.4)) - '@angular-devkit/core': 19.2.19(chokidar@4.0.3) - '@angular/build': 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(@angular/compiler@19.2.15)(@angular/platform-server@19.2.0(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/compiler@19.2.15)(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(@angular/platform-browser@19.2.15(@angular/animations@19.2.15(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1)))(@angular/common@19.2.15(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))(rxjs@7.8.2))(@angular/core@19.2.15(rxjs@7.8.2)(zone.js@0.15.1))))(@types/node@22.10.5)(chokidar@4.0.3)(jiti@2.6.1)(karma@6.4.4)(less@4.2.2)(postcss@8.5.2)(tailwindcss@3.4.14(ts-node@10.9.2(@types/node@22.10.5)(typescript@5.9.3)))(terser@5.39.0)(typescript@5.9.3)(yaml@2.8.1) - '@angular/compiler-cli': 19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3) - '@babel/core': 7.26.10 - '@babel/generator': 7.26.10 - '@babel/helper-annotate-as-pure': 7.25.9 - '@babel/helper-split-export-declaration': 7.24.7 - '@babel/plugin-transform-async-generator-functions': 7.26.8(@babel/core@7.26.10) - '@babel/plugin-transform-async-to-generator': 7.25.9(@babel/core@7.26.10) - '@babel/plugin-transform-runtime': 7.26.10(@babel/core@7.26.10) - '@babel/preset-env': 7.26.9(@babel/core@7.26.10) - '@babel/runtime': 7.26.10 - '@discoveryjs/json-ext': 0.6.3 - '@ngtools/webpack': 19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(typescript@5.9.3)(webpack@5.98.0(esbuild@0.25.4)) - '@vitejs/plugin-basic-ssl': 1.2.0(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) - ansi-colors: 4.1.3 - autoprefixer: 10.4.20(postcss@8.5.2) - babel-loader: 9.2.1(@babel/core@7.26.10)(webpack@5.98.0) - browserslist: 4.25.4 - copy-webpack-plugin: 12.0.2(webpack@5.98.0) - css-loader: 7.1.2(webpack@5.98.0) - esbuild-wasm: 0.25.4 - fast-glob: 3.3.3 - http-proxy-middleware: 3.0.5 - istanbul-lib-instrument: 6.0.3 - jsonc-parser: 3.3.1 - karma-source-map-support: 1.4.0 - less: 4.2.2 - less-loader: 12.2.0(less@4.2.2)(webpack@5.98.0) - license-webpack-plugin: 4.0.2(webpack@5.98.0) - loader-utils: 3.3.1 - mini-css-extract-plugin: 2.9.2(webpack@5.98.0) - open: 10.1.0 - ora: 5.4.1 - picomatch: 4.0.2 - piscina: 4.8.0 - postcss: 8.5.2 - postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.9.3)(webpack@5.98.0(esbuild@0.25.4)) + postcss-loader: 8.1.1(postcss@8.5.2)(typescript@5.9.3)(webpack@5.98.0) resolve-url-loader: 5.0.0 rxjs: 7.8.1 sass: 1.85.0 @@ -14754,8 +14548,8 @@ snapshots: tslib: 2.8.1 typescript: 5.9.3 webpack: 5.98.0(esbuild@0.25.4) - webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.4)) - webpack-dev-server: 5.2.2(webpack@5.98.0(esbuild@0.25.4)) + webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.0)) + webpack-dev-server: 5.2.2(webpack@5.98.0) webpack-merge: 6.0.1 webpack-subresource-integrity: 5.1.0(webpack@5.98.0) optionalDependencies: @@ -14786,12 +14580,12 @@ snapshots: - webpack-cli - yaml - '@angular-devkit/build-webpack@0.1902.0(chokidar@4.0.3)(webpack-dev-server@5.2.0(webpack@5.98.0))(webpack@5.98.0)': + '@angular-devkit/build-webpack@0.1902.0(chokidar@4.0.3)(webpack-dev-server@5.2.0(webpack@5.98.0(esbuild@0.25.0)))(webpack@5.98.0(esbuild@0.25.0))': dependencies: '@angular-devkit/architect': 0.1902.0(chokidar@4.0.3) rxjs: 7.8.1 - webpack: 5.98.0(esbuild@0.25.4) - webpack-dev-server: 5.2.0(webpack@5.98.0) + webpack: 5.98.0(esbuild@0.25.0) + webpack-dev-server: 5.2.0(webpack@5.98.0(esbuild@0.25.0)) transitivePeerDependencies: - chokidar @@ -14799,17 +14593,17 @@ snapshots: dependencies: '@angular-devkit/architect': 0.1902.15(chokidar@4.0.3) rxjs: 7.8.1 - webpack: 5.98.0(esbuild@0.25.4) - webpack-dev-server: 5.2.2(webpack@5.98.0(esbuild@0.25.4)) + webpack: 5.98.0(esbuild@0.25.0) + webpack-dev-server: 5.2.2(webpack@5.98.0) transitivePeerDependencies: - chokidar - '@angular-devkit/build-webpack@0.1902.19(chokidar@4.0.3)(webpack-dev-server@5.2.2(webpack@5.98.0(esbuild@0.25.4)))(webpack@5.98.0(esbuild@0.25.4))': + '@angular-devkit/build-webpack@0.1902.19(chokidar@4.0.3)(webpack-dev-server@5.2.2(webpack@5.98.0))(webpack@5.98.0)': dependencies: '@angular-devkit/architect': 0.1902.19(chokidar@4.0.3) rxjs: 7.8.1 - webpack: 5.98.0(esbuild@0.25.4) - webpack-dev-server: 5.2.2(webpack@5.98.0(esbuild@0.25.4)) + webpack: 5.98.0(esbuild@0.25.0) + webpack-dev-server: 5.2.2(webpack@5.98.0) transitivePeerDependencies: - chokidar @@ -18219,23 +18013,23 @@ snapshots: '@next/swc-win32-x64-msvc@15.2.4': optional: true - '@ngtools/webpack@19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(typescript@5.8.3)(webpack@5.98.0)': + '@ngtools/webpack@19.2.0(@angular/compiler-cli@19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3))(typescript@5.8.3)(webpack@5.98.0(esbuild@0.25.0))': dependencies: '@angular/compiler-cli': 19.2.0(@angular/compiler@19.2.0(@angular/core@19.2.0(rxjs@7.8.2)(zone.js@0.15.1)))(typescript@5.8.3) typescript: 5.8.3 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) '@ngtools/webpack@19.2.15(@angular/compiler-cli@19.2.14(@angular/compiler@19.2.14)(typescript@5.8.3))(typescript@5.8.3)(webpack@5.98.0)': dependencies: '@angular/compiler-cli': 19.2.14(@angular/compiler@19.2.14)(typescript@5.8.3) typescript: 5.8.3 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) - '@ngtools/webpack@19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(typescript@5.9.3)(webpack@5.98.0(esbuild@0.25.4))': + '@ngtools/webpack@19.2.19(@angular/compiler-cli@19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3))(typescript@5.9.3)(webpack@5.98.0)': dependencies: '@angular/compiler-cli': 19.2.15(@angular/compiler@19.2.15)(typescript@5.9.3) typescript: 5.9.3 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) '@nodelib/fs.scandir@2.1.5': dependencies: @@ -18332,12 +18126,12 @@ snapshots: - magicast - supports-color - '@nuxt/devtools-kit@1.7.0(magicast@0.3.5)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1))': + '@nuxt/devtools-kit@1.7.0(magicast@0.3.5)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0))': dependencies: '@nuxt/kit': 3.15.4(magicast@0.3.5) '@nuxt/schema': 3.16.2 execa: 7.2.0 - vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1) + vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0) transitivePeerDependencies: - magicast - supports-color @@ -18496,13 +18290,13 @@ snapshots: - utf-8-validate - vue - '@nuxt/devtools@1.7.0(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1))(vue@3.5.13(typescript@5.9.3))': + '@nuxt/devtools@1.7.0(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0))(vue@3.5.13(typescript@5.9.3))': dependencies: '@antfu/utils': 0.7.10 - '@nuxt/devtools-kit': 1.7.0(magicast@0.3.5)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) + '@nuxt/devtools-kit': 1.7.0(magicast@0.3.5)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)) '@nuxt/devtools-wizard': 1.7.0 '@nuxt/kit': 3.15.4(magicast@0.3.5) - '@vue/devtools-core': 7.6.8(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1))(vue@3.5.13(typescript@5.9.3)) + '@vue/devtools-core': 7.6.8(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0))(vue@3.5.13(typescript@5.9.3)) '@vue/devtools-kit': 7.6.8 birpc: 0.2.19 consola: 3.4.2 @@ -18531,9 +18325,9 @@ snapshots: sirv: 3.0.2 tinyglobby: 0.2.15 unimport: 3.14.6(rollup@4.50.0) - vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1) - vite-plugin-inspect: 0.8.9(@nuxt/kit@3.15.4(magicast@0.3.5))(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) - vite-plugin-vue-inspector: 5.3.2(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) + vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0) + vite-plugin-inspect: 0.8.9(@nuxt/kit@3.15.4(magicast@0.3.5))(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)) + vite-plugin-vue-inspector: 5.3.2(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)) which: 3.0.1 ws: 8.18.3 transitivePeerDependencies: @@ -19044,6 +18838,12 @@ snapshots: pinia: 3.0.3(typescript@5.9.3)(vue@3.5.13(typescript@5.9.3)) vue: 3.5.13(typescript@5.9.3) + '@pinia/colada@0.17.7(pinia@3.0.3(typescript@5.9.3)(vue@3.5.20(typescript@5.9.3)))(vue@3.5.20(typescript@5.9.3))': + dependencies: + '@vue/devtools-api': 8.0.3 + pinia: 3.0.3(typescript@5.9.3)(vue@3.5.20(typescript@5.9.3)) + vue: 3.5.20(typescript@5.9.3) + '@pkgjs/parseargs@0.11.0': optional: true @@ -20354,6 +20154,14 @@ snapshots: vue: 3.5.13(typescript@5.9.3) vue-demi: 0.14.10(vue@3.5.13(typescript@5.9.3)) + '@tanstack/vue-query@5.73.3(vue@3.5.20(typescript@5.9.3))': + dependencies: + '@tanstack/match-sorter-utils': 8.19.4 + '@tanstack/query-core': 5.73.3 + '@vue/devtools-api': 6.6.4 + vue: 3.5.20(typescript@5.9.3) + vue-demi: 0.14.10(vue@3.5.20(typescript@5.9.3)) + '@tsconfig/node10@1.0.11': {} '@tsconfig/node12@1.0.11': {} @@ -21305,14 +21113,14 @@ snapshots: transitivePeerDependencies: - vite - '@vue/devtools-core@7.6.8(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1))(vue@3.5.13(typescript@5.9.3))': + '@vue/devtools-core@7.6.8(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0))(vue@3.5.13(typescript@5.9.3))': dependencies: '@vue/devtools-kit': 7.7.7 '@vue/devtools-shared': 7.7.7 mitt: 3.0.1 nanoid: 5.1.5 pathe: 1.1.2 - vite-hot-client: 0.2.4(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)) + vite-hot-client: 0.2.4(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)) vue: 3.5.13(typescript@5.9.3) transitivePeerDependencies: - vite @@ -21958,14 +21766,14 @@ snapshots: '@babel/core': 7.26.10 find-cache-dir: 4.0.0 schema-utils: 4.3.2 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) - babel-loader@9.2.1(@babel/core@7.26.9)(webpack@5.98.0): + babel-loader@9.2.1(@babel/core@7.26.9)(webpack@5.98.0(esbuild@0.25.0)): dependencies: '@babel/core': 7.26.9 find-cache-dir: 4.0.0 schema-utils: 4.3.2 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) babel-plugin-polyfill-corejs2@0.4.14(@babel/core@7.26.10): dependencies: @@ -22552,7 +22360,7 @@ snapshots: normalize-path: 3.0.0 schema-utils: 4.3.2 serialize-javascript: 6.0.2 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) core-js-compat@3.45.1: dependencies: @@ -22625,7 +22433,7 @@ snapshots: postcss-value-parser: 4.2.0 semver: 7.7.2 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) css-select@5.2.2: dependencies: @@ -24237,15 +24045,6 @@ snapshots: package-json-from-dist: 1.0.1 path-scurry: 1.11.1 - glob@11.0.3: - dependencies: - foreground-child: 3.3.1 - jackspeak: 4.1.1 - minimatch: 10.0.3 - minipass: 7.1.2 - package-json-from-dist: 1.0.1 - path-scurry: 2.0.0 - glob@7.2.3: dependencies: fs.realpath: 1.0.0 @@ -24343,15 +24142,6 @@ snapshots: handle-thing@2.0.1: {} - handlebars@4.7.8: - dependencies: - minimist: 1.2.8 - neo-async: 2.6.2 - source-map: 0.6.1 - wordwrap: 1.0.0 - optionalDependencies: - uglify-js: 3.19.3 - has-bigints@1.1.0: {} has-flag@4.0.0: {} @@ -24927,10 +24717,6 @@ snapshots: optionalDependencies: '@pkgjs/parseargs': 0.11.0 - jackspeak@4.1.1: - dependencies: - '@isaacs/cliui': 8.0.2 - jasmine-core@4.6.1: {} jasmine-core@5.2.0: {} @@ -25168,7 +24954,7 @@ snapshots: dependencies: less: 4.2.2 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) less@4.2.2: dependencies: @@ -25193,7 +24979,7 @@ snapshots: dependencies: webpack-sources: 3.3.3 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) light-my-request@6.6.0: dependencies: @@ -25744,7 +25530,7 @@ snapshots: dependencies: schema-utils: 4.3.2 tapable: 2.2.3 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) minimalistic-assert@1.0.1: {} @@ -26579,10 +26365,10 @@ snapshots: - vue-tsc - xml2js - nuxt@3.14.1592(@netlify/blobs@9.1.2)(@parcel/watcher@2.5.1)(@types/node@22.10.5)(db0@0.3.2)(encoding@0.1.13)(eslint@9.17.0(jiti@2.6.1))(ioredis@5.7.0)(less@4.2.2)(magicast@0.3.5)(optionator@0.9.4)(rolldown@1.0.0-beta.45)(rollup@4.50.0)(sass@1.85.0)(terser@5.43.1)(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)): + nuxt@3.14.1592(@netlify/blobs@9.1.2)(@parcel/watcher@2.5.1)(@types/node@22.10.5)(db0@0.3.2)(encoding@0.1.13)(eslint@9.17.0(jiti@2.6.1))(ioredis@5.7.0)(less@4.2.2)(magicast@0.3.5)(optionator@0.9.4)(rolldown@1.0.0-beta.45)(rollup@4.50.0)(sass@1.85.0)(terser@5.43.1)(typescript@5.9.3)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)): dependencies: '@nuxt/devalue': 2.0.2 - '@nuxt/devtools': 1.7.0(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1))(vue@3.5.13(typescript@5.9.3)) + '@nuxt/devtools': 1.7.0(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0))(vue@3.5.13(typescript@5.9.3)) '@nuxt/kit': 3.14.1592(magicast@0.3.5)(rollup@4.50.0) '@nuxt/schema': 3.14.1592(magicast@0.3.5)(rollup@4.50.0) '@nuxt/telemetry': 2.6.6(magicast@0.3.5) @@ -27047,11 +26833,6 @@ snapshots: lru-cache: 10.4.3 minipass: 7.1.2 - path-scurry@2.0.0: - dependencies: - lru-cache: 11.2.2 - minipass: 7.1.2 - path-to-regexp@0.1.10: {} path-to-regexp@0.1.12: {} @@ -27102,6 +26883,13 @@ snapshots: optionalDependencies: typescript: 5.9.3 + pinia@3.0.3(typescript@5.9.3)(vue@3.5.20(typescript@5.9.3)): + dependencies: + '@vue/devtools-api': 7.7.7 + vue: 3.5.20(typescript@5.9.3) + optionalDependencies: + typescript: 5.9.3 + pino-abstract-transport@2.0.0: dependencies: split2: 4.2.0 @@ -27220,25 +27008,25 @@ snapshots: ts-node: 10.9.2(@types/node@22.10.5)(typescript@5.9.3) optional: true - postcss-loader@8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0): + postcss-loader@8.1.1(postcss@8.5.2)(typescript@5.8.3)(webpack@5.98.0(esbuild@0.25.0)): dependencies: cosmiconfig: 9.0.0(typescript@5.8.3) jiti: 1.21.7 postcss: 8.5.2 semver: 7.7.2 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) transitivePeerDependencies: - typescript - postcss-loader@8.1.1(postcss@8.5.2)(typescript@5.9.3)(webpack@5.98.0(esbuild@0.25.4)): + postcss-loader@8.1.1(postcss@8.5.2)(typescript@5.9.3)(webpack@5.98.0): dependencies: cosmiconfig: 9.0.0(typescript@5.9.3) jiti: 1.21.7 postcss: 8.5.2 semver: 7.7.2 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) transitivePeerDependencies: - typescript @@ -28063,7 +27851,7 @@ snapshots: neo-async: 2.6.2 optionalDependencies: sass: 1.85.0 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) sass@1.85.0: dependencies: @@ -28430,7 +28218,7 @@ snapshots: dependencies: iconv-lite: 0.6.3 source-map-js: 1.2.1 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) source-map-support@0.5.21: dependencies: @@ -28868,7 +28656,7 @@ snapshots: schema-utils: 4.3.2 serialize-javascript: 6.0.2 terser: 5.43.1 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) optionalDependencies: esbuild: 0.25.0 @@ -28879,7 +28667,7 @@ snapshots: schema-utils: 4.3.2 serialize-javascript: 6.0.2 terser: 5.43.1 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) optionalDependencies: esbuild: 0.25.4 @@ -29217,9 +29005,6 @@ snapshots: ufo@1.6.1: {} - uglify-js@3.19.3: - optional: true - ultrahtml@1.6.0: {} unbox-primitive@1.1.0: @@ -29686,9 +29471,9 @@ snapshots: dependencies: vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.39.0)(yaml@2.8.1) - vite-hot-client@0.2.4(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)): + vite-hot-client@0.2.4(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)): dependencies: - vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1) + vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0) vite-hot-client@2.1.0(vite@7.1.2(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)): dependencies: @@ -29870,7 +29655,7 @@ snapshots: - rollup - supports-color - vite-plugin-inspect@0.8.9(@nuxt/kit@3.15.4(magicast@0.3.5))(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)): + vite-plugin-inspect@0.8.9(@nuxt/kit@3.15.4(magicast@0.3.5))(rollup@4.50.0)(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)): dependencies: '@antfu/utils': 0.7.10 '@rollup/pluginutils': 5.2.0(rollup@4.50.0) @@ -29881,7 +29666,7 @@ snapshots: perfect-debounce: 1.0.0 picocolors: 1.1.1 sirv: 3.0.2 - vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1) + vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0) optionalDependencies: '@nuxt/kit': 3.15.4(magicast@0.3.5) transitivePeerDependencies: @@ -29948,7 +29733,7 @@ snapshots: transitivePeerDependencies: - supports-color - vite-plugin-vue-inspector@5.3.2(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1)): + vite-plugin-vue-inspector@5.3.2(vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0)): dependencies: '@babel/core': 7.28.3 '@babel/plugin-proposal-decorators': 7.28.0(@babel/core@7.28.3) @@ -29959,7 +29744,7 @@ snapshots: '@vue/compiler-dom': 3.5.21 kolorist: 1.8.0 magic-string: 0.30.18 - vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1) + vite: 7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0) transitivePeerDependencies: - supports-color @@ -30083,6 +29868,23 @@ snapshots: terser: 5.39.0 yaml: 2.8.1 + vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.0): + dependencies: + esbuild: 0.25.9 + fdir: 6.5.0(picomatch@4.0.3) + picomatch: 4.0.3 + postcss: 8.5.6 + rollup: 4.50.0 + tinyglobby: 0.2.15 + optionalDependencies: + '@types/node': 22.10.5 + fsevents: 2.3.3 + jiti: 2.6.1 + less: 4.2.2 + sass: 1.85.0 + terser: 5.43.1 + yaml: 2.8.0 + vite@7.1.5(@types/node@22.10.5)(jiti@2.6.1)(less@4.2.2)(sass@1.85.0)(terser@5.43.1)(yaml@2.8.1): dependencies: esbuild: 0.25.9 @@ -30320,6 +30122,10 @@ snapshots: dependencies: vue: 3.5.13(typescript@5.9.3) + vue-demi@0.14.10(vue@3.5.20(typescript@5.9.3)): + dependencies: + vue: 3.5.20(typescript@5.9.3) + vue-devtools-stub@0.1.0: {} vue-eslint-parser@9.4.3(eslint@9.17.0(jiti@2.6.1)): @@ -30418,7 +30224,7 @@ snapshots: webidl-conversions@7.0.0: {} - webpack-dev-middleware@7.4.2(webpack@5.98.0(esbuild@0.25.4)): + webpack-dev-middleware@7.4.2(webpack@5.98.0(esbuild@0.25.0)): dependencies: colorette: 2.0.20 memfs: 4.38.2 @@ -30427,9 +30233,9 @@ snapshots: range-parser: 1.2.1 schema-utils: 4.3.2 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) - webpack-dev-server@5.2.0(webpack@5.98.0): + webpack-dev-server@5.2.0(webpack@5.98.0(esbuild@0.25.0)): dependencies: '@types/bonjour': 3.5.13 '@types/connect-history-api-fallback': 1.5.4 @@ -30456,17 +30262,17 @@ snapshots: serve-index: 1.9.1 sockjs: 0.3.24 spdy: 4.0.2 - webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.4)) + webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.0)) ws: 8.18.3 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) transitivePeerDependencies: - bufferutil - debug - supports-color - utf-8-validate - webpack-dev-server@5.2.2(webpack@5.98.0(esbuild@0.25.4)): + webpack-dev-server@5.2.2(webpack@5.98.0): dependencies: '@types/bonjour': 3.5.13 '@types/connect-history-api-fallback': 1.5.4 @@ -30494,10 +30300,10 @@ snapshots: serve-index: 1.9.1 sockjs: 0.3.24 spdy: 4.0.2 - webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.4)) + webpack-dev-middleware: 7.4.2(webpack@5.98.0(esbuild@0.25.0)) ws: 8.18.3 optionalDependencies: - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) transitivePeerDependencies: - bufferutil - debug @@ -30515,7 +30321,7 @@ snapshots: webpack-subresource-integrity@5.1.0(webpack@5.98.0): dependencies: typed-assert: 1.0.9 - webpack: 5.98.0(esbuild@0.25.4) + webpack: 5.98.0(esbuild@0.25.0) webpack-virtual-modules@0.6.2: {} @@ -30689,8 +30495,6 @@ snapshots: word-wrap@1.2.5: {} - wordwrap@1.0.0: {} - wrap-ansi@6.2.0: dependencies: ansi-styles: 4.3.0 -- 2.51.2