From f11f8c7d3e529d4e9b8105b5a7f632ad49e3edbd Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Wed, 23 Oct 2024 16:33:54 +0000 Subject: [PATCH] ci: regenerated with OpenAPI Doc , Speakeasy CLI 1.421.0 --- .speakeasy/workflow.lock | 9 +- ts/.gitignore | 1 + ts/.npmignore | 1 + ts/.speakeasy/gen.lock | 101 ++- ts/.speakeasy/gen.yaml | 3 +- ts/FUNCTIONS.md | 2 +- ts/README.md | 142 ++-- ts/RELEASES.md | 12 +- ts/USAGE.md | 6 +- ts/docs/models/components/errort.md | 4 +- ts/docs/models/components/httpmetadata.md | 8 +- ts/docs/models/components/pet.md | 4 +- .../models/operations/createpetsresponse.md | 12 +- ts/docs/models/operations/listpetsresponse.md | 20 +- .../models/operations/showpetbyidrequest.md | 2 +- .../models/operations/showpetbyidresponse.md | 12 +- ts/docs/sdks/pets/README.md | 32 +- ts/jsr.json | 2 +- ts/package-lock.json | 22 +- ts/package.json | 5 +- ts/src/funcs/petsCreatePets.ts | 171 ++--- ts/src/funcs/petsListPets.ts | 184 ++--- ts/src/funcs/petsShowPetById.ts | 182 ++--- ts/src/hooks/hooks.ts | 167 ++--- ts/src/hooks/index.ts | 2 +- ts/src/hooks/types.ts | 107 +-- ts/src/index.ts | 2 +- ts/src/lib/config.ts | 64 +- ts/src/lib/files.ts | 18 - ts/src/lib/matchers.ts | 409 +++++------ ts/src/lib/schemas.ts | 96 +-- ts/src/lib/sdks.ts | 651 +++++++++--------- ts/src/lib/security.ts | 279 ++++---- ts/src/models/components/error.ts | 35 +- ts/src/models/components/httpmetadata.ts | 92 +-- ts/src/models/components/pet.ts | 34 +- ts/src/models/errors/httpclienterrors.ts | 38 +- ts/src/models/errors/sdkerror.ts | 28 +- ts/src/models/operations/createpets.ts | 80 +-- ts/src/models/operations/listpets.ts | 149 ++-- ts/src/models/operations/showpetbyid.ts | 136 ++-- ts/src/sdk/pets.ts | 66 +- ts/src/sdk/sdk.ts | 8 +- ts/src/types/index.ts | 8 +- 44 files changed, 1762 insertions(+), 1644 deletions(-) diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock index 9423834..94725cd 100644 --- a/.speakeasy/workflow.lock +++ b/.speakeasy/workflow.lock @@ -1,8 +1,8 @@ -speakeasyVersion: 1.389.1 +speakeasyVersion: 1.421.0 sources: petstore: sourceNamespace: petstore - sourceRevisionDigest: sha256:145cb6c7453343c769be7b7c98ee52ce2263365b0f18d89584458e36079d9647 + sourceRevisionDigest: sha256:5139f7eb35bd185e818a5cee58a68734ff027b5a2fa7c7e4bb5c1bff0ecaaf90 sourceBlobDigest: sha256:7c35756702030633a8d2ebb1d378d34f883126319b06edcd798ac7bb2fddb189 tags: - latest @@ -13,19 +13,16 @@ targets: sourceNamespace: petstore sourceRevisionDigest: sha256:6a996d4448a1cfaff5b5e81ec5b7599026c4eef7cd858867aad756131168440a sourceBlobDigest: sha256:08ce70c4bc584c427d03c413e2fca26efe2f363bf8b80668cabf2915dc45af63 - outLocation: go second-target: source: petstore sourceNamespace: petstore sourceRevisionDigest: sha256:22dea4fa269cfc90ef29c704b6a25e91601d47b45da74b25f6f8550d09740bf7 sourceBlobDigest: sha256:0988cc3ebcf0b14954c082c37c08f8a965b0ec72781ffd459a9d4e105519f1da - outLocation: py third-target: source: petstore sourceNamespace: petstore - sourceRevisionDigest: sha256:145cb6c7453343c769be7b7c98ee52ce2263365b0f18d89584458e36079d9647 + sourceRevisionDigest: sha256:5139f7eb35bd185e818a5cee58a68734ff027b5a2fa7c7e4bb5c1bff0ecaaf90 sourceBlobDigest: sha256:7c35756702030633a8d2ebb1d378d34f883126319b06edcd798ac7bb2fddb189 - outLocation: ts workflow: workflowVersion: 1.0.0 speakeasyVersion: latest diff --git a/ts/.gitignore b/ts/.gitignore index 3dea90f..09c4b62 100644 --- a/ts/.gitignore +++ b/ts/.gitignore @@ -1,3 +1,4 @@ +/__tests__ /funcs /core.* /esm diff --git a/ts/.npmignore b/ts/.npmignore index 3ef05d1..06cd8ab 100644 --- a/ts/.npmignore +++ b/ts/.npmignore @@ -7,3 +7,4 @@ /cjs /.tshy /.tshy-* +/__tests__ diff --git a/ts/.speakeasy/gen.lock b/ts/.speakeasy/gen.lock index 3f14abd..4f95a49 100755 --- a/ts/.speakeasy/gen.lock +++ b/ts/.speakeasy/gen.lock @@ -3,10 +3,10 @@ id: f4be10ce-8651-4157-98c6-d75e2342372f management: docChecksum: 1bdb7a6f8bf3995d4b40475228403253 docVersion: 1.0.0 - speakeasyVersion: 1.389.1 - generationVersion: 2.409.0 - releaseVersion: 0.3.0 - configChecksum: faaa20b2350ac2b25e59b50425d3b460 + speakeasyVersion: 1.421.0 + generationVersion: 2.438.15 + releaseVersion: 0.4.0 + configChecksum: 0e4d4f7770c9dbcb2f8a13cfc85df0f5 repoURL: https://github.com/ryan-timothy-albert/multi-sdk-sample.git repoSubDirectory: ts installationURL: https://gitpkg.now.sh/ryan-timothy-albert/multi-sdk-sample/ts @@ -14,28 +14,43 @@ management: features: typescript: additionalDependencies: 0.1.0 - core: 3.16.0 + core: 3.18.2 defaultEnabledRetries: 0.1.0 envVarSecurityUsage: 0.1.1 - flattening: 2.81.1 + flattening: 2.82.0 globalSecurityCallbacks: 0.1.0 globalServerURLs: 2.82.4 responseFormat: 0.2.3 retries: 2.83.0 sdkHooks: 0.1.0 generatedFiles: - - src/funcs/petsListPets.ts - - src/funcs/petsCreatePets.ts - - src/funcs/petsShowPetById.ts - - src/sdk/pets.ts - - src/sdk/sdk.ts - .eslintrc.cjs + - .gitattributes - .npmignore + - CONTRIBUTING.md - FUNCTIONS.md - RUNTIMES.md + - USAGE.md + - docs/lib/utils/retryconfig.md + - docs/models/components/errort.md + - docs/models/components/httpmetadata.md + - docs/models/components/pet.md + - docs/models/operations/createpetsresponse.md + - docs/models/operations/listpetsrequest.md + - docs/models/operations/listpetsresponse.md + - docs/models/operations/showpetbyidrequest.md + - docs/models/operations/showpetbyidresponse.md + - docs/sdks/pets/README.md + - docs/sdks/ryts/README.md - jsr.json - package.json - src/core.ts + - src/funcs/petsCreatePets.ts + - src/funcs/petsListPets.ts + - src/funcs/petsShowPetById.ts + - src/hooks/hooks.ts + - src/hooks/index.ts + - src/hooks/types.ts - src/index.ts - src/lib/base64.ts - src/lib/config.ts @@ -52,10 +67,21 @@ generatedFiles: - src/lib/sdks.ts - src/lib/security.ts - src/lib/url.ts - - src/sdk/index.ts + - src/models/components/error.ts + - src/models/components/httpmetadata.ts + - src/models/components/index.ts + - src/models/components/pet.ts - src/models/errors/httpclienterrors.ts + - src/models/errors/index.ts - src/models/errors/sdkerror.ts - src/models/errors/sdkvalidationerror.ts + - src/models/operations/createpets.ts + - src/models/operations/index.ts + - src/models/operations/listpets.ts + - src/models/operations/showpetbyid.ts + - src/sdk/index.ts + - src/sdk/pets.ts + - src/sdk/sdk.ts - src/types/blobs.ts - src/types/constdatetime.ts - src/types/enums.ts @@ -65,29 +91,28 @@ generatedFiles: - src/types/rfcdate.ts - src/types/streams.ts - tsconfig.json - - src/models/operations/listpets.ts - - src/models/operations/createpets.ts - - src/models/operations/showpetbyid.ts - - src/models/components/error.ts - - src/models/components/pet.ts - - src/models/components/httpmetadata.ts - - src/models/errors/index.ts - - src/models/operations/index.ts - - src/models/components/index.ts - - docs/models/operations/listpetsrequest.md - - docs/models/operations/listpetsresponse.md - - docs/models/operations/createpetsresponse.md - - docs/models/operations/showpetbyidrequest.md - - docs/models/operations/showpetbyidresponse.md - - docs/models/components/errort.md - - docs/models/components/pet.md - - docs/models/components/httpmetadata.md - - docs/sdks/ryts/README.md - - docs/lib/utils/retryconfig.md - - docs/sdks/pets/README.md - - USAGE.md - - .gitattributes - - src/hooks/hooks.ts - - src/hooks/types.ts - - src/hooks/index.ts - - CONTRIBUTING.md +examples: + listPets: + speakeasy-default-list-pets: + responses: + "200": + application/json: [] + default: + application/json: {"code": 767425, "message": ""} + createPets: + speakeasy-default-create-pets: + requestBody: + application/json: {"id": 596804, "name": ""} + responses: + default: + application/json: {"code": 589113, "message": ""} + showPetById: + speakeasy-default-show-pet-by-id: + parameters: + path: + petId: "" + responses: + "200": + application/json: {"id": 763078, "name": ""} + default: + application/json: {"code": 743784, "message": ""} diff --git a/ts/.speakeasy/gen.yaml b/ts/.speakeasy/gen.yaml index 6b555f2..00806f4 100755 --- a/ts/.speakeasy/gen.yaml +++ b/ts/.speakeasy/gen.yaml @@ -12,7 +12,7 @@ generation: auth: oAuth2ClientCredentialsEnabled: true typescript: - version: 0.3.0 + version: 0.4.0 additionalDependencies: dependencies: {} devDependencies: {} @@ -22,6 +22,7 @@ typescript: clientServerStatusCodesAsErrors: true enumFormat: enum flattenGlobalSecurity: true + flatteningOrder: body-first imports: option: openapi paths: diff --git a/ts/FUNCTIONS.md b/ts/FUNCTIONS.md index 71f6b2a..9e3d89b 100644 --- a/ts/FUNCTIONS.md +++ b/ts/FUNCTIONS.md @@ -50,7 +50,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); diff --git a/ts/README.md b/ts/README.md index ebde1eb..860ec38 100644 --- a/ts/README.md +++ b/ts/README.md @@ -87,10 +87,10 @@ import { RyTs } from "ryan-test-1"; const ryTs = new RyTs(); async function run() { - const result = await ryTs.pets.listPets(); + const result = await ryTs.pets.listPets(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -101,11 +101,17 @@ run(); ## Available Resources and Operations +
+Available methods + ### [pets](docs/sdks/pets/README.md) * [listPets](docs/sdks/pets/README.md#listpets) - List all pets * [createPets](docs/sdks/pets/README.md#createpets) - Create a pet * [showPetById](docs/sdks/pets/README.md#showpetbyid) - Info for a specific pet + + +
@@ -123,10 +129,9 @@ To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md). Available standalone functions -- [petsCreatePets](docs/sdks/pets/README.md#createpets) -- [petsListPets](docs/sdks/pets/README.md#listpets) -- [petsShowPetById](docs/sdks/pets/README.md#showpetbyid) - +- [`petsCreatePets`](docs/sdks/pets/README.md#createpets) - Create a pet +- [`petsListPets`](docs/sdks/pets/README.md#listpets) - List all pets +- [`petsShowPetById`](docs/sdks/pets/README.md#showpetbyid) - Info for a specific pet @@ -143,21 +148,21 @@ import { RyTs } from "ryan-test-1"; const ryTs = new RyTs(); async function run() { - const result = await ryTs.pets.listPets({ - retries: { - strategy: "backoff", - backoff: { - initialInterval: 1, - maxInterval: 50, - exponent: 1.1, - maxElapsedTime: 100, - }, - retryConnectionErrors: false, - }, - }); + const result = await ryTs.pets.listPets({ + retries: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -169,23 +174,23 @@ If you'd like to override the default retry strategy for all operations that sup import { RyTs } from "ryan-test-1"; const ryTs = new RyTs({ - retryConfig: { - strategy: "backoff", - backoff: { - initialInterval: 1, - maxInterval: 50, - exponent: 1.1, - maxElapsedTime: 100, - }, - retryConnectionErrors: false, + retryConfig: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, }, + retryConnectionErrors: false, + }, }); async function run() { - const result = await ryTs.pets.listPets(); + const result = await ryTs.pets.listPets(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -196,14 +201,23 @@ run(); ## Error Handling -All SDK methods return a response object or throw an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Error type. +All SDK methods return a response object or throw an error. By default, an API error will throw a `errors.SDKError`. -| Error Object | Status Code | Content Type | -| --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +If a HTTP request fails, an operation my also throw an error from the `models/errors/httpclienterrors.ts` module: + +| HTTP Client Error | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | +| RequestAbortedError | HTTP request was aborted by the client | +| RequestTimeoutError | HTTP request timed out due to an AbortSignal signal | +| ConnectionError | HTTP client was unable to make a request to a server | +| InvalidRequestError | Any input used to create a request is invalid | +| UnexpectedClientError | Unrecognised or unexpected error | -Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The `SDKValidationError` that is thrown as a result will capture the raw value that failed validation in an attribute called `rawValue`. Additionally, a `pretty()` method is available on this error that can be used to log a nicely formatted string since validation errors can list many issues and the plain error string may be difficult read when debugging. +In addition, when custom error responses are specified for an operation, the SDK may throw their associated Error type. You can refer to respective *Errors* tables in SDK docs for more details on possible error types for each operation. For example, the `listPets` method may throw the following errors: +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4XX, 5XX | \*/\* | ```typescript import { RyTs } from "ryan-test-1"; @@ -212,31 +226,33 @@ import { SDKValidationError } from "ryan-test-1/models/errors"; const ryTs = new RyTs(); async function run() { - let result; - try { - result = await ryTs.pets.listPets(); - } catch (err) { - switch (true) { - case err instanceof SDKValidationError: { - // Validation errors can be pretty-printed - console.error(err.pretty()); - // Raw value may also be inspected - console.error(err.rawValue); - return; - } - default: { - throw err; - } - } - } + let result; + try { + result = await ryTs.pets.listPets(); // Handle the result console.log(result); + } catch (err) { + switch (true) { + case (err instanceof SDKValidationError): { + // Validation errors can be pretty-printed + console.error(err.pretty()); + // Raw value may also be inspected + console.error(err.rawValue); + return; + } + default: { + throw err; + } + } + } } run(); ``` + +Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The `SDKValidationError` that is thrown as a result will capture the raw value that failed validation in an attribute called `rawValue`. Additionally, a `pretty()` method is available on this error that can be used to log a nicely formatted string since validation errors can list many issues and the plain error string may be difficult read when debugging. @@ -254,14 +270,14 @@ You can override the default server globally by passing a server index to the `s import { RyTs } from "ryan-test-1"; const ryTs = new RyTs({ - serverIdx: 0, + serverIdx: 0, }); async function run() { - const result = await ryTs.pets.listPets(); + const result = await ryTs.pets.listPets(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -277,14 +293,14 @@ The default server can also be overridden globally by passing a URL to the `serv import { RyTs } from "ryan-test-1"; const ryTs = new RyTs({ - serverURL: "http://petstore.swagger.io/v1", + serverURL: "http://petstore.swagger.io/v1", }); async function run() { - const result = await ryTs.pets.listPets(); + const result = await ryTs.pets.listPets(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); diff --git a/ts/RELEASES.md b/ts/RELEASES.md index 0f5a1c6..aae9099 100644 --- a/ts/RELEASES.md +++ b/ts/RELEASES.md @@ -66,4 +66,14 @@ Based on: ### Generated - [typescript v0.3.0] ts ### Releases -- [NPM v0.3.0] https://www.npmjs.com/package/ryan-test-1/v/0.3.0 - ts \ No newline at end of file +- [NPM v0.3.0] https://www.npmjs.com/package/ryan-test-1/v/0.3.0 - ts + +## 2024-10-23 16:33:31 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.421.0 (2.438.15) https://github.com/speakeasy-api/speakeasy +### Generated +- [typescript v0.4.0] ts +### Releases +- [NPM v0.4.0] https://www.npmjs.com/package/ryan-test-1/v/0.4.0 - ts \ No newline at end of file diff --git a/ts/USAGE.md b/ts/USAGE.md index b8c7fde..19df8e0 100644 --- a/ts/USAGE.md +++ b/ts/USAGE.md @@ -5,10 +5,10 @@ import { RyTs } from "ryan-test-1"; const ryTs = new RyTs(); async function run() { - const result = await ryTs.pets.listPets(); + const result = await ryTs.pets.listPets(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); diff --git a/ts/docs/models/components/errort.md b/ts/docs/models/components/errort.md index 329befe..f18f471 100644 --- a/ts/docs/models/components/errort.md +++ b/ts/docs/models/components/errort.md @@ -6,8 +6,8 @@ import { ErrorT } from "ryan-test-1/models/components"; let value: ErrorT = { - code: 548814, - message: "", + code: 548814, + message: "", }; ``` diff --git a/ts/docs/models/components/httpmetadata.md b/ts/docs/models/components/httpmetadata.md index 03d2093..5cf38ab 100644 --- a/ts/docs/models/components/httpmetadata.md +++ b/ts/docs/models/components/httpmetadata.md @@ -6,10 +6,10 @@ import { HTTPMetadata } from "ryan-test-1/models/components"; let value: HTTPMetadata = { - response: new Response('{"message": "hello world"}', { - headers: { "Content-Type": "application/json" }, - }), - request: new Request("https://example.com"), + response: new Response("{\"message\": \"hello world\"}", { + headers: { "Content-Type": "application/json" }, + }), + request: new Request("https://example.com"), }; ``` diff --git a/ts/docs/models/components/pet.md b/ts/docs/models/components/pet.md index 4ab8064..f2e4b66 100644 --- a/ts/docs/models/components/pet.md +++ b/ts/docs/models/components/pet.md @@ -6,8 +6,8 @@ import { Pet } from "ryan-test-1/models/components"; let value: Pet = { - id: 592845, - name: "", + id: 715190, + name: "", }; ``` diff --git a/ts/docs/models/operations/createpetsresponse.md b/ts/docs/models/operations/createpetsresponse.md index 97acafa..25b3097 100644 --- a/ts/docs/models/operations/createpetsresponse.md +++ b/ts/docs/models/operations/createpetsresponse.md @@ -6,12 +6,12 @@ import { CreatePetsResponse } from "ryan-test-1/models/operations"; let value: CreatePetsResponse = { - httpMeta: { - response: new Response('{"message": "hello world"}', { - headers: { "Content-Type": "application/json" }, - }), - request: new Request("https://example.com"), - }, + httpMeta: { + response: new Response("{\"message\": \"hello world\"}", { + headers: { "Content-Type": "application/json" }, + }), + request: new Request("https://example.com"), + }, }; ``` diff --git a/ts/docs/models/operations/listpetsresponse.md b/ts/docs/models/operations/listpetsresponse.md index 63a8779..94018df 100644 --- a/ts/docs/models/operations/listpetsresponse.md +++ b/ts/docs/models/operations/listpetsresponse.md @@ -6,15 +6,17 @@ import { ListPetsResponse } from "ryan-test-1/models/operations"; let value: ListPetsResponse = { - httpMeta: { - response: new Response('{"message": "hello world"}', { - headers: { "Content-Type": "application/json" }, - }), - request: new Request("https://example.com"), - }, - headers: { - key: [""], - }, + httpMeta: { + response: new Response("{\"message\": \"hello world\"}", { + headers: { "Content-Type": "application/json" }, + }), + request: new Request("https://example.com"), + }, + headers: { + "key": [ + "", + ], + }, }; ``` diff --git a/ts/docs/models/operations/showpetbyidrequest.md b/ts/docs/models/operations/showpetbyidrequest.md index 95ae9ff..0c4427e 100644 --- a/ts/docs/models/operations/showpetbyidrequest.md +++ b/ts/docs/models/operations/showpetbyidrequest.md @@ -6,7 +6,7 @@ import { ShowPetByIdRequest } from "ryan-test-1/models/operations"; let value: ShowPetByIdRequest = { - petId: "", + petId: "", }; ``` diff --git a/ts/docs/models/operations/showpetbyidresponse.md b/ts/docs/models/operations/showpetbyidresponse.md index 8eac2e0..b55e69c 100644 --- a/ts/docs/models/operations/showpetbyidresponse.md +++ b/ts/docs/models/operations/showpetbyidresponse.md @@ -6,12 +6,12 @@ import { ShowPetByIdResponse } from "ryan-test-1/models/operations"; let value: ShowPetByIdResponse = { - httpMeta: { - response: new Response('{"message": "hello world"}', { - headers: { "Content-Type": "application/json" }, - }), - request: new Request("https://example.com"), - }, + httpMeta: { + response: new Response("{\"message\": \"hello world\"}", { + headers: { "Content-Type": "application/json" }, + }), + request: new Request("https://example.com"), + }, }; ``` diff --git a/ts/docs/sdks/pets/README.md b/ts/docs/sdks/pets/README.md index 3b3adef..b7cfc35 100644 --- a/ts/docs/sdks/pets/README.md +++ b/ts/docs/sdks/pets/README.md @@ -24,7 +24,7 @@ async function run() { const result = await ryTs.pets.listPets(); // Handle the result - console.log(result) + console.log(result); } run(); @@ -52,7 +52,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -73,10 +73,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## createPets @@ -96,7 +95,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -116,7 +115,7 @@ const ryTs = new RyTsCore(); async function run() { const res = await petsCreatePets(ryTs, { - id: 589113, + id: 596804, name: "", }); @@ -127,7 +126,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -148,10 +147,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## showPetById @@ -165,10 +163,10 @@ import { RyTs } from "ryan-test-1"; const ryTs = new RyTs(); async function run() { - const result = await ryTs.pets.showPetById(""); + const result = await ryTs.pets.showPetById(""); // Handle the result - console.log(result) + console.log(result); } run(); @@ -187,7 +185,7 @@ import { petsShowPetById } from "ryan-test-1/funcs/petsShowPetById.js"; const ryTs = new RyTsCore(); async function run() { - const res = await petsShowPetById(ryTs, ""); + const res = await petsShowPetById(ryTs, ""); if (!res.ok) { throw res.error; @@ -196,7 +194,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -217,6 +215,6 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/ts/jsr.json b/ts/jsr.json index 140a488..f8b6d8b 100644 --- a/ts/jsr.json +++ b/ts/jsr.json @@ -2,7 +2,7 @@ { "name": "ryan-test-1", - "version": "0.3.0", + "version": "0.4.0", "exports": { ".": "./src/index.ts", "./models/errors": "./src/models/errors/index.ts", diff --git a/ts/package-lock.json b/ts/package-lock.json index f7c6be3..6e38d98 100644 --- a/ts/package-lock.json +++ b/ts/package-lock.json @@ -1,14 +1,13 @@ { "name": "ryan-test-1", - "version": "0.3.0", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ryan-test-1", - "version": "0.3.0", + "version": "0.4.0", "devDependencies": { - "@types/node": "^18.19.3", "@typescript-eslint/eslint-plugin": "^7.7.1", "@typescript-eslint/parser": "^7.7.1", "eslint": "^8.57.0", @@ -201,16 +200,6 @@ "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", "dev": true }, - "node_modules/@types/node": { - "version": "18.19.48", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.48.tgz", - "integrity": "sha512-7WevbG4ekUcRQSZzOwxWgi5dZmTak7FaxXDoW7xVxPBmKx1rTzfmRLkeCgJzcbBnOV2dkhAPc8cCeT6agocpjg==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~5.26.4" - } - }, "node_modules/@types/semver": { "version": "7.5.8", "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", @@ -2994,13 +2983,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", - "dev": true, - "license": "MIT" - }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", diff --git a/ts/package.json b/ts/package.json index da3f5a1..b25ecc5 100644 --- a/ts/package.json +++ b/ts/package.json @@ -1,6 +1,6 @@ { "name": "ryan-test-1", - "version": "0.3.0", + "version": "0.4.0", "author": "ryantimalbert", "main": "./index.js", "sideEffects": false, @@ -12,13 +12,12 @@ "scripts": { "lint": "eslint --max-warnings=0 src", "build": "tsc", - "prepare": "npm run build" + "prepublishOnly": "npm run build" }, "peerDependencies": { "zod": ">= 3" }, "devDependencies": { - "@types/node": "^18.19.3", "@typescript-eslint/eslint-plugin": "^7.7.1", "@typescript-eslint/parser": "^7.7.1", "eslint": "^8.57.0", diff --git a/ts/src/funcs/petsCreatePets.ts b/ts/src/funcs/petsCreatePets.ts index 202bde1..034c018 100644 --- a/ts/src/funcs/petsCreatePets.ts +++ b/ts/src/funcs/petsCreatePets.ts @@ -3,18 +3,18 @@ */ import { RyTsCore } from "../core.js"; -import { encodeJSON as encodeJSON$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; @@ -25,91 +25,92 @@ import { Result } from "../types/fp.js"; * Create a pet */ export async function petsCreatePets( - client$: RyTsCore, - request: components.Pet, - options?: RequestOptions + client: RyTsCore, + request: components.Pet, + options?: RequestOptions, ): Promise< - Result< - operations.CreatePetsResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + operations.CreatePetsResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => components.Pet$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload, { explode: true }); - const parsed$ = schemas$.safeParse( - input$, - (value$) => components.Pet$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = encodeJSON$("body", payload$, { explode: true }); + const path = pathToFunc("/pets")(); - const path$ = pathToFunc("/pets")(); + const headers = new Headers({ + "Content-Type": "application/json", + Accept: "application/json", + }); - const headers$ = new Headers({ - "Content-Type": "application/json", - Accept: "application/json", - }); + const context = { + operationID: "createPets", + oAuth2Scopes: [], + securitySource: null, + }; - const context = { operationID: "createPets", oAuth2Scopes: [], securitySource: null }; + const requestRes = client._createRequest(context, { + method: "POST", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - method: "POST", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + operations.CreatePetsResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(201, operations.CreatePetsResponse$inboundSchema), + M.fail(["4XX", "5XX"]), + M.json("default", operations.CreatePetsResponse$inboundSchema, { + key: "Error", + }), + )(response, req, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - operations.CreatePetsResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.nil(201, operations.CreatePetsResponse$inboundSchema), - m$.fail(["4XX", "5XX"]), - m$.json("default", operations.CreatePetsResponse$inboundSchema, { key: "Error" }) - )(response, request$, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/ts/src/funcs/petsListPets.ts b/ts/src/funcs/petsListPets.ts index 1585638..5f82993 100644 --- a/ts/src/funcs/petsListPets.ts +++ b/ts/src/funcs/petsListPets.ts @@ -3,17 +3,17 @@ */ import { RyTsCore } from "../core.js"; -import { encodeFormQuery as encodeFormQuery$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeFormQuery } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { pathToFunc } from "../lib/url.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; @@ -24,97 +24,103 @@ import { Result } from "../types/fp.js"; * List all pets */ export async function petsListPets( - client$: RyTsCore, - limit?: number | undefined, - options?: RequestOptions + client: RyTsCore, + limit?: number | undefined, + options?: RequestOptions, ): Promise< - Result< - operations.ListPetsResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + operations.ListPetsResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$: operations.ListPetsRequest = { - limit: limit, - }; + const input: operations.ListPetsRequest = { + limit: limit, + }; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.ListPetsRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const parsed = safeParse( + input, + (value) => operations.ListPetsRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const path$ = pathToFunc("/pets")(); + const path = pathToFunc("/pets")(); - const query$ = encodeFormQuery$({ - limit: payload$.limit, - }); + const query = encodeFormQuery({ + "limit": payload.limit, + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const headers = new Headers({ + Accept: "application/json", + }); - const context = { operationID: "listPets", oAuth2Scopes: [], securitySource: null }; + const context = { + operationID: "listPets", + oAuth2Scopes: [], + securitySource: null, + }; - const requestRes = client$.createRequest$( - context, - { - method: "GET", - path: path$, - headers: headers$, - query: query$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + method: "GET", + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const [result$] = await m$.match< - operations.ListPetsResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, operations.ListPetsResponse$inboundSchema, { hdrs: true, key: "Pets" }), - m$.fail(["4XX", "5XX"]), - m$.json("default", operations.ListPetsResponse$inboundSchema, { key: "Error" }) - )(response, request$, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + operations.ListPetsResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, operations.ListPetsResponse$inboundSchema, { + hdrs: true, + key: "Pets", + }), + M.fail(["4XX", "5XX"]), + M.json("default", operations.ListPetsResponse$inboundSchema, { + key: "Error", + }), + )(response, req, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/ts/src/funcs/petsShowPetById.ts b/ts/src/funcs/petsShowPetById.ts index 41b1f60..fe43c54 100644 --- a/ts/src/funcs/petsShowPetById.ts +++ b/ts/src/funcs/petsShowPetById.ts @@ -3,17 +3,17 @@ */ import { RyTsCore } from "../core.js"; -import { encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { pathToFunc } from "../lib/url.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; @@ -24,96 +24,102 @@ import { Result } from "../types/fp.js"; * Info for a specific pet */ export async function petsShowPetById( - client$: RyTsCore, - petId: string, - options?: RequestOptions + client: RyTsCore, + petId: string, + options?: RequestOptions, ): Promise< - Result< - operations.ShowPetByIdResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + operations.ShowPetByIdResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$: operations.ShowPetByIdRequest = { - petId: petId, - }; + const input: operations.ShowPetByIdRequest = { + petId: petId, + }; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.ShowPetByIdRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const parsed = safeParse( + input, + (value) => operations.ShowPetByIdRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const pathParams$ = { - petId: encodeSimple$("petId", payload$.petId, { explode: false, charEncoding: "percent" }), - }; + const pathParams = { + petId: encodeSimple("petId", payload.petId, { + explode: false, + charEncoding: "percent", + }), + }; - const path$ = pathToFunc("/pets/{petId}")(pathParams$); + const path = pathToFunc("/pets/{petId}")(pathParams); - const headers$ = new Headers({ - Accept: "application/json", - }); + const headers = new Headers({ + Accept: "application/json", + }); - const context = { operationID: "showPetById", oAuth2Scopes: [], securitySource: null }; + const context = { + operationID: "showPetById", + oAuth2Scopes: [], + securitySource: null, + }; - const requestRes = client$.createRequest$( - context, - { - method: "GET", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + method: "GET", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const [result$] = await m$.match< - operations.ShowPetByIdResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, operations.ShowPetByIdResponse$inboundSchema, { key: "Pet" }), - m$.fail(["4XX", "5XX"]), - m$.json("default", operations.ShowPetByIdResponse$inboundSchema, { key: "Error" }) - )(response, request$, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + operations.ShowPetByIdResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, operations.ShowPetByIdResponse$inboundSchema, { key: "Pet" }), + M.fail(["4XX", "5XX"]), + M.json("default", operations.ShowPetByIdResponse$inboundSchema, { + key: "Error", + }), + )(response, req, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/ts/src/hooks/hooks.ts b/ts/src/hooks/hooks.ts index a6b6e17..d1b3396 100644 --- a/ts/src/hooks/hooks.ts +++ b/ts/src/hooks/hooks.ts @@ -4,100 +4,109 @@ import { RequestInput } from "../lib/http.js"; import { - AfterErrorContext, - AfterErrorHook, - AfterSuccessContext, - AfterSuccessHook, - BeforeRequestContext, - BeforeRequestHook, - BeforeCreateRequestHook, - BeforeCreateRequestContext, - Hooks, - SDKInitHook, - SDKInitOptions, + AfterErrorContext, + AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeCreateRequestContext, + BeforeCreateRequestHook, + BeforeRequestContext, + BeforeRequestHook, + Hooks, + SDKInitHook, + SDKInitOptions, } from "./types.js"; import { initHooks } from "./registration.js"; export class SDKHooks implements Hooks { - sdkInitHooks: SDKInitHook[] = []; - beforeCreateRequestHooks: BeforeCreateRequestHook[] = []; - beforeRequestHooks: BeforeRequestHook[] = []; - afterSuccessHooks: AfterSuccessHook[] = []; - afterErrorHooks: AfterErrorHook[] = []; - - constructor() { - initHooks(this); + sdkInitHooks: SDKInitHook[] = []; + beforeCreateRequestHooks: BeforeCreateRequestHook[] = []; + beforeRequestHooks: BeforeRequestHook[] = []; + afterSuccessHooks: AfterSuccessHook[] = []; + afterErrorHooks: AfterErrorHook[] = []; + + constructor() { + initHooks(this); + } + + registerSDKInitHook(hook: SDKInitHook) { + this.sdkInitHooks.push(hook); + } + + registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook) { + this.beforeCreateRequestHooks.push(hook); + } + + registerBeforeRequestHook(hook: BeforeRequestHook) { + this.beforeRequestHooks.push(hook); + } + + registerAfterSuccessHook(hook: AfterSuccessHook) { + this.afterSuccessHooks.push(hook); + } + + registerAfterErrorHook(hook: AfterErrorHook) { + this.afterErrorHooks.push(hook); + } + + sdkInit(opts: SDKInitOptions): SDKInitOptions { + return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); + } + + beforeCreateRequest( + hookCtx: BeforeCreateRequestContext, + input: RequestInput, + ): RequestInput { + let inp = input; + + for (const hook of this.beforeCreateRequestHooks) { + inp = hook.beforeCreateRequest(hookCtx, inp); } - registerSDKInitHook(hook: SDKInitHook) { - this.sdkInitHooks.push(hook); - } + return inp; + } - registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook) { - this.beforeCreateRequestHooks.push(hook); - } + async beforeRequest( + hookCtx: BeforeRequestContext, + request: Request, + ): Promise { + let req = request; - registerBeforeRequestHook(hook: BeforeRequestHook) { - this.beforeRequestHooks.push(hook); + for (const hook of this.beforeRequestHooks) { + req = await hook.beforeRequest(hookCtx, req); } - registerAfterSuccessHook(hook: AfterSuccessHook) { - this.afterSuccessHooks.push(hook); - } + return req; + } - registerAfterErrorHook(hook: AfterErrorHook) { - this.afterErrorHooks.push(hook); - } + async afterSuccess( + hookCtx: AfterSuccessContext, + response: Response, + ): Promise { + let res = response; - sdkInit(opts: SDKInitOptions): SDKInitOptions { - return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); + for (const hook of this.afterSuccessHooks) { + res = await hook.afterSuccess(hookCtx, res); } - beforeCreateRequest(hookCtx: BeforeCreateRequestContext, input: RequestInput): RequestInput { - let inp = input; - - for (const hook of this.beforeCreateRequestHooks) { - inp = hook.beforeCreateRequest(hookCtx, inp); - } - - return inp; + return res; + } + + async afterError( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ): Promise<{ response: Response | null; error: unknown }> { + let res = response; + let err = error; + + for (const hook of this.afterErrorHooks) { + const result = await hook.afterError(hookCtx, res, err); + res = result.response; + err = result.error; } - async beforeRequest(hookCtx: BeforeRequestContext, request: Request): Promise { - let req = request; - - for (const hook of this.beforeRequestHooks) { - req = await hook.beforeRequest(hookCtx, req); - } - - return req; - } - - async afterSuccess(hookCtx: AfterSuccessContext, response: Response): Promise { - let res = response; - - for (const hook of this.afterSuccessHooks) { - res = await hook.afterSuccess(hookCtx, res); - } - - return res; - } - - async afterError( - hookCtx: AfterErrorContext, - response: Response | null, - error: unknown - ): Promise<{ response: Response | null; error: unknown }> { - let res = response; - let err = error; - - for (const hook of this.afterErrorHooks) { - const result = await hook.afterError(hookCtx, res, err); - res = result.response; - err = result.error; - } - - return { response: res, error: err }; - } + return { response: res, error: err }; + } } diff --git a/ts/src/hooks/index.ts b/ts/src/hooks/index.ts index 8f0e4db..f60ec7a 100644 --- a/ts/src/hooks/index.ts +++ b/ts/src/hooks/index.ts @@ -2,5 +2,5 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export * from "./types.js"; export * from "./hooks.js"; +export * from "./types.js"; diff --git a/ts/src/hooks/types.ts b/ts/src/hooks/types.ts index 3a31914..656b9e3 100644 --- a/ts/src/hooks/types.ts +++ b/ts/src/hooks/types.ts @@ -5,16 +5,16 @@ import { HTTPClient, RequestInput } from "../lib/http.js"; export type HookContext = { - operationID: string; - oAuth2Scopes?: string[]; - securitySource?: any | (() => Promise); + operationID: string; + oAuth2Scopes?: string[]; + securitySource?: any | (() => Promise); }; export type Awaitable = T | Promise; export type SDKInitOptions = { - baseURL: URL | null; - client: HTTPClient; + baseURL: URL | null; + client: HTTPClient; }; export type BeforeCreateRequestContext = HookContext & {}; @@ -27,63 +27,72 @@ export type AfterErrorContext = HookContext & {}; * hook can return a new baseURL and HTTP client to be used by the SDK. */ export interface SDKInitHook { - sdkInit: (opts: SDKInitOptions) => SDKInitOptions; + sdkInit: (opts: SDKInitOptions) => SDKInitOptions; } export interface BeforeCreateRequestHook { - /** - * A hook that is called before the SDK creates a `Request` object. The hook - * can modify how a request is constructed since certain modifications, like - * changing the request URL, cannot be done on a request object directly. - */ - beforeCreateRequest: (hookCtx: BeforeCreateRequestContext, input: RequestInput) => RequestInput; + /** + * A hook that is called before the SDK creates a `Request` object. The hook + * can modify how a request is constructed since certain modifications, like + * changing the request URL, cannot be done on a request object directly. + */ + beforeCreateRequest: ( + hookCtx: BeforeCreateRequestContext, + input: RequestInput, + ) => RequestInput; } export interface BeforeRequestHook { - /** - * A hook that is called before the SDK sends a request. The hook can - * introduce instrumentation code such as logging, tracing and metrics or - * replace the request before it is sent or throw an error to stop the - * request from being sent. - */ - beforeRequest: (hookCtx: BeforeRequestContext, request: Request) => Awaitable; + /** + * A hook that is called before the SDK sends a request. The hook can + * introduce instrumentation code such as logging, tracing and metrics or + * replace the request before it is sent or throw an error to stop the + * request from being sent. + */ + beforeRequest: ( + hookCtx: BeforeRequestContext, + request: Request, + ) => Awaitable; } export interface AfterSuccessHook { - /** - * A hook that is called after the SDK receives a response. The hook can - * introduce instrumentation code such as logging, tracing and metrics or - * modify the response before it is handled or throw an error to stop the - * response from being handled. - */ - afterSuccess: (hookCtx: AfterSuccessContext, response: Response) => Awaitable; + /** + * A hook that is called after the SDK receives a response. The hook can + * introduce instrumentation code such as logging, tracing and metrics or + * modify the response before it is handled or throw an error to stop the + * response from being handled. + */ + afterSuccess: ( + hookCtx: AfterSuccessContext, + response: Response, + ) => Awaitable; } export interface AfterErrorHook { - /** - * A hook that is called after the SDK encounters an error, or a - * non-successful response. The hook can introduce instrumentation code such - * as logging, tracing and metrics or modify the response or error values. - */ - afterError: ( - hookCtx: AfterErrorContext, - response: Response | null, - error: unknown - ) => Awaitable<{ - response: Response | null; - error: unknown; - }>; + /** + * A hook that is called after the SDK encounters an error, or a + * non-successful response. The hook can introduce instrumentation code such + * as logging, tracing and metrics or modify the response or error values. + */ + afterError: ( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ) => Awaitable<{ + response: Response | null; + error: unknown; + }>; } export interface Hooks { - /** Registers a hook to be used by the SDK for initialization event. */ - registerSDKInitHook(hook: SDKInitHook): void; - /** Registers a hook to be used by the SDK for to modify `Request` construction. */ - registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook): void; - /** Registers a hook to be used by the SDK for the before request event. */ - registerBeforeRequestHook(hook: BeforeRequestHook): void; - /** Registers a hook to be used by the SDK for the after success event. */ - registerAfterSuccessHook(hook: AfterSuccessHook): void; - /** Registers a hook to be used by the SDK for the after error event. */ - registerAfterErrorHook(hook: AfterErrorHook): void; + /** Registers a hook to be used by the SDK for initialization event. */ + registerSDKInitHook(hook: SDKInitHook): void; + /** Registers a hook to be used by the SDK for to modify `Request` construction. */ + registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook): void; + /** Registers a hook to be used by the SDK for the before request event. */ + registerBeforeRequestHook(hook: BeforeRequestHook): void; + /** Registers a hook to be used by the SDK for the after success event. */ + registerAfterSuccessHook(hook: AfterSuccessHook): void; + /** Registers a hook to be used by the SDK for the after error event. */ + registerAfterErrorHook(hook: AfterErrorHook): void; } diff --git a/ts/src/index.ts b/ts/src/index.ts index c6fc7f0..5ddc765 100644 --- a/ts/src/index.ts +++ b/ts/src/index.ts @@ -2,6 +2,6 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export * from "./sdk/sdk.js"; export * from "./lib/config.js"; export * as files from "./lib/files.js"; +export * from "./sdk/sdk.js"; diff --git a/ts/src/lib/config.ts b/ts/src/lib/config.ts index 156307a..c18368b 100644 --- a/ts/src/lib/config.ts +++ b/ts/src/lib/config.ts @@ -10,47 +10,49 @@ import { Params, pathToFunc } from "./url.js"; /** * Contains the list of servers available to the SDK */ -export const ServerList = ["http://petstore.swagger.io/v1"] as const; +export const ServerList = [ + "http://petstore.swagger.io/v1", +] as const; export type SDKOptions = { - httpClient?: HTTPClient; - /** - * Allows overriding the default server used by the SDK - */ - serverIdx?: number; - /** - * Allows overriding the default server URL used by the SDK - */ - serverURL?: string; - /** - * Allows overriding the default retry config used by the SDK - */ - retryConfig?: RetryConfig; - timeoutMs?: number; - debugLogger?: Logger; + httpClient?: HTTPClient; + /** + * Allows overriding the default server used by the SDK + */ + serverIdx?: number; + /** + * Allows overriding the default server URL used by the SDK + */ + serverURL?: string; + /** + * Allows overriding the default retry config used by the SDK + */ + retryConfig?: RetryConfig; + timeoutMs?: number; + debugLogger?: Logger; }; export function serverURLFromOptions(options: SDKOptions): URL | null { - let serverURL = options.serverURL; + let serverURL = options.serverURL; - const params: Params = {}; + const params: Params = {}; - if (!serverURL) { - const serverIdx = options.serverIdx ?? 0; - if (serverIdx < 0 || serverIdx >= ServerList.length) { - throw new Error(`Invalid server index ${serverIdx}`); - } - serverURL = ServerList[serverIdx] || ""; + if (!serverURL) { + const serverIdx = options.serverIdx ?? 0; + if (serverIdx < 0 || serverIdx >= ServerList.length) { + throw new Error(`Invalid server index ${serverIdx}`); } + serverURL = ServerList[serverIdx] || ""; + } - const u = pathToFunc(serverURL)(params); - return new URL(u); + const u = pathToFunc(serverURL)(params); + return new URL(u); } export const SDK_METADATA = { - language: "typescript", - openapiDocVersion: "1.0.0", - sdkVersion: "0.3.0", - genVersion: "2.409.0", - userAgent: "speakeasy-sdk/typescript 0.3.0 2.409.0 1.0.0 ryan-test-1", + language: "typescript", + openapiDocVersion: "1.0.0", + sdkVersion: "0.4.0", + genVersion: "2.438.15", + userAgent: "speakeasy-sdk/typescript 0.4.0 2.438.15 1.0.0 ryan-test-1", } as const; diff --git a/ts/src/lib/files.ts b/ts/src/lib/files.ts index 69028c7..19e0804 100644 --- a/ts/src/lib/files.ts +++ b/ts/src/lib/files.ts @@ -2,24 +2,6 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { Readable } from "stream"; -import { createReadStream } from "fs"; -import { readFile } from "fs/promises"; - -export function toStream(filePath: string): ReadableStream { - return Readable.toWeb( - createReadStream(filePath), - ) as ReadableStream; -} - -export async function toByteArray(filePath: string): Promise { - return readFile(filePath); -} - -export async function toString(filePath: string): Promise { - return readFile(filePath, "utf8"); -} - /** * Consumes a stream and returns a concatenated array buffer. Useful in * situations where we need to read the whole file because it forms part of a diff --git a/ts/src/lib/matchers.ts b/ts/src/lib/matchers.ts index fd4672d..7bf6b59 100644 --- a/ts/src/lib/matchers.ts +++ b/ts/src/lib/matchers.ts @@ -2,264 +2,279 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { safeParse } from "./schemas.js"; -import { StatusCodePredicate, matchResponse, matchStatusCode } from "./http.js"; -import { isPlainObject } from "./is-plain-object.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import { Result } from "../types/fp.js"; +import { matchResponse, matchStatusCode, StatusCodePredicate } from "./http.js"; +import { isPlainObject } from "./is-plain-object.js"; +import { safeParse } from "./schemas.js"; -export type Encoding = "json" | "text" | "bytes" | "stream" | "sse" | "nil" | "fail"; +export type Encoding = + | "json" + | "text" + | "bytes" + | "stream" + | "sse" + | "nil" + | "fail"; const DEFAULT_CONTENT_TYPES: Record = { - json: "application/json", - text: "text/plain", - bytes: "application/octet-stream", - stream: "application/octet-stream", - sse: "text/event-stream", - nil: "*", - fail: "*", + json: "application/json", + text: "text/plain", + bytes: "application/octet-stream", + stream: "application/octet-stream", + sse: "text/event-stream", + nil: "*", + fail: "*", }; type Schema = { parse(raw: unknown): T }; -type MatchOptions = { ctype?: string; hdrs?: boolean; key?: string; sseSentinel?: string }; +type MatchOptions = { + ctype?: string; + hdrs?: boolean; + key?: string; + sseSentinel?: string; +}; export type ValueMatcher = MatchOptions & { - enc: Encoding; - codes: StatusCodePredicate; - schema: Schema; + enc: Encoding; + codes: StatusCodePredicate; + schema: Schema; }; export type ErrorMatcher = MatchOptions & { - enc: Encoding; - codes: StatusCodePredicate; - schema: Schema; - err: true; + enc: Encoding; + codes: StatusCodePredicate; + schema: Schema; + err: true; }; export type FailMatcher = { - enc: "fail"; - codes: StatusCodePredicate; + enc: "fail"; + codes: StatusCodePredicate; }; export type Matcher = ValueMatcher | ErrorMatcher | FailMatcher; export function jsonErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "json", codes, schema }; + return { ...options, err: true, enc: "json", codes, schema }; } export function json( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "json", codes, schema }; + return { ...options, enc: "json", codes, schema }; } export function textErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "text", codes, schema }; + return { ...options, err: true, enc: "text", codes, schema }; } export function text( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "text", codes, schema }; + return { ...options, enc: "text", codes, schema }; } export function bytesErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "bytes", codes, schema }; + return { ...options, err: true, enc: "bytes", codes, schema }; } export function bytes( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "bytes", codes, schema }; + return { ...options, enc: "bytes", codes, schema }; } export function streamErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "stream", codes, schema }; + return { ...options, err: true, enc: "stream", codes, schema }; } export function stream( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "stream", codes, schema }; + return { ...options, enc: "stream", codes, schema }; } export function sseErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "sse", codes, schema }; + return { ...options, err: true, enc: "sse", codes, schema }; } export function sse( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "sse", codes, schema }; + return { ...options, enc: "sse", codes, schema }; } export function nilErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "nil", codes, schema }; + return { ...options, err: true, enc: "nil", codes, schema }; } export function nil( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "nil", codes, schema }; + return { ...options, enc: "nil", codes, schema }; } export function fail(codes: StatusCodePredicate): FailMatcher { - return { enc: "fail", codes }; + return { enc: "fail", codes }; } -export type MatchedValue = Matchers extends Matcher[] ? T : never; -export type MatchedError = Matchers extends Matcher[] ? E : never; +export type MatchedValue = Matchers extends Matcher[] + ? T + : never; +export type MatchedError = Matchers extends Matcher[] + ? E + : never; export type MatchFunc = ( - response: Response, - request: Request, - - options?: { resultKey?: string; extraFields?: Record } + response: Response, + request: Request, + options?: { resultKey?: string; extraFields?: Record }, ) => Promise<[result: Result, raw: unknown]>; export function match( - ...matchers: Array> + ...matchers: Array> ): MatchFunc { - return async function matchFunc( - response: Response, - request: Request, - - options?: { resultKey?: string; extraFields?: Record } - ): Promise<[result: Result, raw: unknown]> { - let raw: unknown; - let matcher: Matcher | undefined; - for (const match of matchers) { - const { codes } = match; - const ctpattern = "ctype" in match ? match.ctype : DEFAULT_CONTENT_TYPES[match.enc]; - if (ctpattern && matchResponse(response, codes, ctpattern)) { - matcher = match; - break; - } else if (!ctpattern && matchStatusCode(response, codes)) { - matcher = match; - break; - } - } + return async function matchFunc( + response: Response, + request: Request, + options?: { resultKey?: string; extraFields?: Record }, + ): Promise< + [result: Result, raw: unknown] + > { + let raw: unknown; + let matcher: Matcher | undefined; + for (const match of matchers) { + const { codes } = match; + const ctpattern = "ctype" in match + ? match.ctype + : DEFAULT_CONTENT_TYPES[match.enc]; + if (ctpattern && matchResponse(response, codes, ctpattern)) { + matcher = match; + break; + } else if (!ctpattern && matchStatusCode(response, codes)) { + matcher = match; + break; + } + } - if (!matcher) { - await discardResponseBody(response); - return [ - { - ok: false, - error: new SDKError("Unexpected API response status or content-type", { - response, - request, - }), - }, - raw, - ]; - } + if (!matcher) { + await discardResponseBody(response); + return [{ + ok: false, + error: new SDKError("Unexpected API response status or content-type", { + response, + request, + }), + }, raw]; + } - const encoding = matcher.enc; - switch (encoding) { - case "json": - raw = await response.json(); - break; - case "bytes": - raw = await response.arrayBuffer(); - break; - case "stream": - raw = response.body; - break; - case "text": - raw = await response.text(); - break; - case "sse": - raw = response.body; - break; - case "nil": - raw = await discardResponseBody(response); - break; - case "fail": - raw = await discardResponseBody(response); - break; - default: - encoding satisfies never; - throw new Error(`Unsupported response type: ${encoding}`); - } + const encoding = matcher.enc; + switch (encoding) { + case "json": + raw = await response.json(); + break; + case "bytes": + raw = await response.arrayBuffer(); + break; + case "stream": + raw = response.body; + break; + case "text": + raw = await response.text(); + break; + case "sse": + raw = response.body; + break; + case "nil": + raw = await discardResponseBody(response); + break; + case "fail": + raw = await discardResponseBody(response); + break; + default: + encoding satisfies never; + throw new Error(`Unsupported response type: ${encoding}`); + } - if (matcher.enc === "fail") { - return [ - { ok: false, error: new SDKError("API error occurred", { response, request }) }, - raw, - ]; - } + if (matcher.enc === "fail") { + return [{ + ok: false, + error: new SDKError("API error occurred", { response, request }), + }, raw]; + } - const resultKey = matcher.key || options?.resultKey; - let data: unknown; + const resultKey = matcher.key || options?.resultKey; + let data: unknown; - if ("err" in matcher) { - data = { - ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - ...(isPlainObject(raw) ? raw : null), - }; - } else if (resultKey) { - data = { - ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - [resultKey]: raw, - }; - } else { - data = { - ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - }; - } + if ("err" in matcher) { + data = { + ...options?.extraFields, + ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + ...(isPlainObject(raw) ? raw : null), + }; + } else if (resultKey) { + data = { + ...options?.extraFields, + ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + [resultKey]: raw, + }; + } else { + data = { + ...options?.extraFields, + ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + }; + } - if ("err" in matcher) { - const result = safeParse( - data, - (v: unknown) => matcher.schema.parse(v), - "Response validation failed" - ); - return [result.ok ? { ok: false, error: result.value } : result, raw]; - } else { - return [ - safeParse( - data, - (v: unknown) => matcher.schema.parse(v), - "Response validation failed" - ), - raw, - ]; - } - }; + if ("err" in matcher) { + const result = safeParse( + data, + (v: unknown) => matcher.schema.parse(v), + "Response validation failed", + ); + return [result.ok ? { ok: false, error: result.value } : result, raw]; + } else { + return [ + safeParse( + data, + (v: unknown) => matcher.schema.parse(v), + "Response validation failed", + ), + raw, + ]; + } + }; } const headerValRE = /, */; @@ -268,13 +283,13 @@ const headerValRE = /, */; * entries. Values are represented as an array to account for repeated headers. */ export function unpackHeaders(headers: Headers): Record { - const out: Record = {}; + const out: Record = {}; - for (const [k, v] of headers.entries()) { - out[k] = v.split(headerValRE); - } + for (const [k, v] of headers.entries()) { + out[k] = v.split(headerValRE); + } - return out; + return out; } /** @@ -284,18 +299,18 @@ export function unpackHeaders(headers: Headers): Record { * https://undici.nodejs.org/#/?id=garbage-collection */ export async function discardResponseBody(res: Response) { - const reader = res.body?.getReader(); - if (reader == null) { - return; - } + const reader = res.body?.getReader(); + if (reader == null) { + return; + } - try { - let done = false; - while (!done) { - const res = await reader.read(); - done = res.done; - } - } finally { - reader.releaseLock(); + try { + let done = false; + while (!done) { + const res = await reader.read(); + done = res.done; } + } finally { + reader.releaseLock(); + } } diff --git a/ts/src/lib/schemas.ts b/ts/src/lib/schemas.ts index 37b0b13..f3856dc 100644 --- a/ts/src/lib/schemas.ts +++ b/ts/src/lib/schemas.ts @@ -2,7 +2,14 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { output, ZodEffects, ZodError, ZodObject, ZodRawShape, ZodTypeAny } from "zod"; +import { + output, + ZodEffects, + ZodError, + ZodObject, + ZodRawShape, + ZodTypeAny, +} from "zod"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import { ERR, OK, Result } from "../types/fp.js"; @@ -11,15 +18,19 @@ import { ERR, OK, Result } from "../types/fp.js"; * intercepts this error and converts it to an SDKValidationError so as to not * leak Zod implementation details to user code. */ -export function parse(rawValue: Inp, fn: (value: Inp) => Out, errorMessage: string): Out { - try { - return fn(rawValue); - } catch (err) { - if (err instanceof ZodError) { - throw new SDKValidationError(errorMessage, err, rawValue); - } - throw err; +export function parse( + rawValue: Inp, + fn: (value: Inp) => Out, + errorMessage: string, +): Out { + try { + return fn(rawValue); + } catch (err) { + if (err instanceof ZodError) { + throw new SDKValidationError(errorMessage, err, rawValue); } + throw err; + } } /** @@ -28,47 +39,48 @@ export function parse(rawValue: Inp, fn: (value: Inp) => Out, errorMes * leak Zod implementation details to user code. */ export function safeParse( - rawValue: Inp, - fn: (value: Inp) => Out, - errorMessage: string + rawValue: Inp, + fn: (value: Inp) => Out, + errorMessage: string, ): Result { - try { - return OK(fn(rawValue)); - } catch (err) { - return ERR(new SDKValidationError(errorMessage, err, rawValue)); - } + try { + return OK(fn(rawValue)); + } catch (err) { + return ERR(new SDKValidationError(errorMessage, err, rawValue)); + } } export function collectExtraKeys< - Shape extends ZodRawShape, - Catchall extends ZodTypeAny, - K extends string + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + K extends string, >( - obj: ZodObject, - extrasKey: K + obj: ZodObject, + extrasKey: K, ): ZodEffects< - typeof obj, - output> & { - [k in K]: Record>; - } + typeof obj, + & output> + & { + [k in K]: Record>; + } > { - return obj.transform((val) => { - const extras: Record> = {}; - const { shape } = obj; - for (const [key] of Object.entries(val)) { - if (key in shape) { - continue; - } + return obj.transform((val) => { + const extras: Record> = {}; + const { shape } = obj; + for (const [key] of Object.entries(val)) { + if (key in shape) { + continue; + } - const v = val[key]; - if (typeof v === "undefined") { - continue; - } + const v = val[key]; + if (typeof v === "undefined") { + continue; + } - extras[key] = v; - delete val[key]; - } + extras[key] = v; + delete val[key]; + } - return { ...val, [extrasKey]: extras }; - }); + return { ...val, [extrasKey]: extras }; + }); } diff --git a/ts/src/lib/sdks.ts b/ts/src/lib/sdks.ts index f741c47..a0f4de1 100644 --- a/ts/src/lib/sdks.ts +++ b/ts/src/lib/sdks.ts @@ -2,368 +2,383 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { - HTTPClient, - matchContentType, - matchStatusCode, - isAbortError, - isTimeoutError, - isConnectionError, -} from "./http.js"; -import { SecurityState } from "./security.js"; -import { retry, RetryConfig } from "./retries.js"; -import { Logger } from "./logger.js"; -import { encodeForm } from "./encodings.js"; -import { stringToBase64 } from "./base64.js"; -import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js"; import { SDKHooks } from "../hooks/hooks.js"; import { HookContext } from "../hooks/types.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { ERR, OK, Result } from "../types/fp.js"; +import { stringToBase64 } from "./base64.js"; +import { SDK_METADATA, SDKOptions, serverURLFromOptions } from "./config.js"; +import { encodeForm } from "./encodings.js"; +import { + HTTPClient, + isAbortError, + isConnectionError, + isTimeoutError, + matchContentType, + matchStatusCode, +} from "./http.js"; +import { Logger } from "./logger.js"; +import { retry, RetryConfig } from "./retries.js"; +import { SecurityState } from "./security.js"; export type RequestOptions = { - /** - * Sets a timeout, in milliseconds, on HTTP requests made by an SDK method. If - * `fetchOptions.signal` is set then it will take precedence over this option. - */ - timeoutMs?: number; - /** - * Set or override a retry policy on HTTP calls. - */ - retries?: RetryConfig; - /** - * Specifies the status codes which should be retried using the given retry policy. - */ - retryCodes?: string[]; - /** - * Sets various request options on the `fetch` call made by an SDK method. - * - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options|Request} - */ - fetchOptions?: Omit; + /** + * Sets a timeout, in milliseconds, on HTTP requests made by an SDK method. If + * `fetchOptions.signal` is set then it will take precedence over this option. + */ + timeoutMs?: number; + /** + * Set or override a retry policy on HTTP calls. + */ + retries?: RetryConfig; + /** + * Specifies the status codes which should be retried using the given retry policy. + */ + retryCodes?: string[]; + /** + * Sets various request options on the `fetch` call made by an SDK method. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options|Request} + */ + fetchOptions?: Omit; }; type RequestConfig = { - method: string; - path: string; - baseURL?: string | URL; - query?: string; - body?: RequestInit["body"]; - headers?: HeadersInit; - security?: SecurityState | null; - uaHeader?: string; - timeoutMs?: number; + method: string; + path: string; + baseURL?: string | URL; + query?: string; + body?: RequestInit["body"]; + headers?: HeadersInit; + security?: SecurityState | null; + uaHeader?: string; + timeoutMs?: number; }; const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; -const webWorkerLike = - typeof gt === "object" && - gt != null && - "importScripts" in gt && - typeof gt["importScripts"] === "function"; -const isBrowserLike = - webWorkerLike || - (typeof navigator !== "undefined" && "serviceWorker" in navigator) || - (typeof window === "object" && typeof window.document !== "undefined"); +const webWorkerLike = typeof gt === "object" + && gt != null + && "importScripts" in gt + && typeof gt["importScripts"] === "function"; +const isBrowserLike = webWorkerLike + || (typeof navigator !== "undefined" && "serviceWorker" in navigator) + || (typeof window === "object" && typeof window.document !== "undefined"); export class ClientSDK { - private readonly httpClient: HTTPClient; - protected readonly baseURL: URL | null; - protected readonly hooks$: SDKHooks; - protected readonly logger?: Logger | undefined; - public readonly options$: SDKOptions & { hooks?: SDKHooks }; - - constructor(options: SDKOptions = {}) { - const opt = options as unknown; - if ( - typeof opt === "object" && - opt != null && - "hooks" in opt && - opt.hooks instanceof SDKHooks - ) { - this.hooks$ = opt.hooks; - } else { - this.hooks$ = new SDKHooks(); - } - this.options$ = { ...options, hooks: this.hooks$ }; + readonly #httpClient: HTTPClient; + readonly #hooks: SDKHooks; + readonly #logger?: Logger | undefined; + protected readonly _baseURL: URL | null; + public readonly _options: SDKOptions & { hooks?: SDKHooks }; + + constructor(options: SDKOptions = {}) { + const opt = options as unknown; + if ( + typeof opt === "object" + && opt != null + && "hooks" in opt + && opt.hooks instanceof SDKHooks + ) { + this.#hooks = opt.hooks; + } else { + this.#hooks = new SDKHooks(); + } + this._options = { ...options, hooks: this.#hooks }; - const url = serverURLFromOptions(options); - if (url) { - url.pathname = url.pathname.replace(/\/+$/, "") + "/"; - } - const { baseURL, client } = this.hooks$.sdkInit({ - baseURL: url, - client: options.httpClient || new HTTPClient(), - }); - this.baseURL = baseURL; - this.httpClient = client; - this.logger = options.debugLogger; + const url = serverURLFromOptions(options); + if (url) { + url.pathname = url.pathname.replace(/\/+$/, "") + "/"; } + const { baseURL, client } = this.#hooks.sdkInit({ + baseURL: url, + client: options.httpClient || new HTTPClient(), + }); + this._baseURL = baseURL; + this.#httpClient = client; + this.#logger = options.debugLogger; + } + + public _createRequest( + context: HookContext, + conf: RequestConfig, + options?: RequestOptions, + ): Result { + const { method, path, query, headers: opHeaders, security } = conf; + + const base = conf.baseURL ?? this._baseURL; + if (!base) { + return ERR(new InvalidRequestError("No base URL provided for operation")); + } + const reqURL = new URL(base); + const inputURL = new URL(path, reqURL); - public createRequest$( - context: HookContext, - conf: RequestConfig, - options?: RequestOptions - ): Result { - const { method, path, query, headers: opHeaders, security } = conf; + if (path) { + reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); + } - const base = conf.baseURL ?? this.baseURL; - if (!base) { - return ERR(new InvalidRequestError("No base URL provided for operation")); - } - const reqURL = new URL(base); - const inputURL = new URL(path, reqURL); + let finalQuery = query || ""; - if (path) { - reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); - } + const secQuery: string[] = []; + for (const [k, v] of Object.entries(security?.queryParams || {})) { + secQuery.push(encodeForm(k, v, { charEncoding: "percent" })); + } + if (secQuery.length) { + finalQuery += `&${secQuery.join("&")}`; + } - let finalQuery = query || ""; + if (finalQuery) { + const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; + reqURL.search = `?${q}`; + } - const secQuery: string[] = []; - for (const [k, v] of Object.entries(security?.queryParams || {})) { - secQuery.push(encodeForm(k, v, { charEncoding: "percent" })); - } - if (secQuery.length) { - finalQuery += `&${secQuery.join("&")}`; - } + const headers = new Headers(opHeaders); - if (finalQuery) { - const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; - reqURL.search = `?${q}`; - } + const username = security?.basic.username; + const password = security?.basic.password; + if (username != null || password != null) { + const encoded = stringToBase64( + [username || "", password || ""].join(":"), + ); + headers.set("Authorization", `Basic ${encoded}`); + } - const headers = new Headers(opHeaders); + const securityHeaders = new Headers(security?.headers || {}); + for (const [k, v] of securityHeaders) { + headers.set(k, v); + } - const username = security?.basic.username; - const password = security?.basic.password; - if (username != null || password != null) { - const encoded = stringToBase64([username || "", password || ""].join(":")); - headers.set("Authorization", `Basic ${encoded}`); - } + let cookie = headers.get("cookie") || ""; + for (const [k, v] of Object.entries(security?.cookies || {})) { + cookie += `; ${k}=${v}`; + } + cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; + headers.set("cookie", cookie); - const securityHeaders = new Headers(security?.headers || {}); - for (const [k, v] of securityHeaders) { - headers.set(k, v); - } + const userHeaders = new Headers(options?.fetchOptions?.headers); + for (const [k, v] of userHeaders) { + headers.set(k, v); + } - let cookie = headers.get("cookie") || ""; - for (const [k, v] of Object.entries(security?.cookies || {})) { - cookie += `; ${k}=${v}`; - } - cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; - headers.set("cookie", cookie); + // Only set user agent header in non-browser-like environments since CORS + // policy disallows setting it in browsers e.g. Chrome throws an error. + if (!isBrowserLike) { + headers.set(conf.uaHeader ?? "user-agent", SDK_METADATA.userAgent); + } - const userHeaders = new Headers(options?.fetchOptions?.headers); - for (const [k, v] of userHeaders) { - headers.set(k, v); - } + let fetchOptions = options?.fetchOptions; + if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) { + const timeoutSignal = AbortSignal.timeout(conf.timeoutMs); + if (!fetchOptions) { + fetchOptions = { signal: timeoutSignal }; + } else { + fetchOptions.signal = timeoutSignal; + } + } - // Only set user agent header in non-browser-like environments since CORS - // policy disallows setting it in browsers e.g. Chrome throws an error. - if (!isBrowserLike) { - headers.set(conf.uaHeader ?? "user-agent", SDK_METADATA.userAgent); - } + if (conf.body instanceof ReadableStream) { + if (!fetchOptions) { + fetchOptions = { + // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 + duplex: "half", + }; + } else { + // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 + fetchOptions.duplex = "half"; + } + } - let fetchOptions = options?.fetchOptions; - if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) { - const timeoutSignal = AbortSignal.timeout(conf.timeoutMs); - if (!fetchOptions) { - fetchOptions = { signal: timeoutSignal }; - } else { - fetchOptions.signal = timeoutSignal; - } - } + let input; + try { + input = this.#hooks.beforeCreateRequest(context, { + url: reqURL, + options: { + ...fetchOptions, + body: conf.body ?? null, + headers, + method, + }, + }); + } catch (err: unknown) { + return ERR( + new UnexpectedClientError("Create request hook failed to execute", { + cause: err, + }), + ); + } + + return OK(new Request(input.url, input.options)); + } + + public async _do( + request: Request, + options: { + context: HookContext; + errorCodes: number | string | (number | string)[]; + retryConfig?: RetryConfig | undefined; + retryCodes?: string[] | undefined; + }, + ): Promise< + Result< + Response, + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + | UnexpectedClientError + > + > { + const { context, errorCodes } = options; + const retryConfig = options.retryConfig || { strategy: "none" }; + const retryCodes = options.retryCodes || []; + + return retry( + async () => { + const req = await this.#hooks.beforeRequest(context, request.clone()); + await logRequest(this.#logger, req).catch((e) => + this.#logger?.log("Failed to log request:", e) + ); - if (conf.body instanceof ReadableStream) { - if (!fetchOptions) { - fetchOptions = { - // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 - duplex: "half", - }; - } else { - // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 - fetchOptions.duplex = "half"; - } + let response = await this.#httpClient.request(req); + + if (matchStatusCode(response, errorCodes)) { + const result = await this.#hooks.afterError(context, response, null); + if (result.error) { + throw result.error; + } + response = result.response || response; + } else { + response = await this.#hooks.afterSuccess(context, response); } - let input; - try { - input = this.hooks$.beforeCreateRequest(context, { - url: reqURL, - options: { - ...fetchOptions, - body: conf.body ?? null, - headers, - method, - }, - }); - } catch (err: unknown) { + await logResponse(this.#logger, response, req) + .catch(e => this.#logger?.log("Failed to log response:", e)); + + return response; + }, + { config: retryConfig, statusCodes: retryCodes }, + ).then( + (r) => OK(r), + (err) => { + switch (true) { + case isAbortError(err): return ERR( - new UnexpectedClientError("Create request hook failed to execute", { cause: err }) + new RequestAbortedError("Request aborted by client", { + cause: err, + }), + ); + case isTimeoutError(err): + return ERR( + new RequestTimeoutError("Request timed out", { cause: err }), + ); + case isConnectionError(err): + return ERR( + new ConnectionError("Unable to make request", { cause: err }), + ); + default: + return ERR( + new UnexpectedClientError("Unexpected HTTP client error", { + cause: err, + }), ); } - - return OK(new Request(input.url, input.options)); - } - - public async do$( - request: Request, - options: { - context: HookContext; - errorCodes: number | string | (number | string)[]; - retryConfig?: RetryConfig | undefined; - retryCodes?: string[] | undefined; - } - ): Promise< - Result< - Response, - RequestAbortedError | RequestTimeoutError | ConnectionError | UnexpectedClientError - > - > { - const { context, errorCodes } = options; - const retryConfig = options.retryConfig || { strategy: "none" }; - const retryCodes = options.retryCodes || []; - - return retry( - async () => { - const req = await this.hooks$.beforeRequest(context, request.clone()); - await logRequest(this.logger, req).catch((e) => - this.logger?.log("Failed to log request:", e) - ); - - let response = await this.httpClient.request(req); - - if (matchStatusCode(response, errorCodes)) { - const result = await this.hooks$.afterError(context, response, null); - if (result.error) { - throw result.error; - } - response = result.response || response; - } else { - response = await this.hooks$.afterSuccess(context, response); - } - - await logResponse(this.logger, response, req).catch((e) => - this.logger?.log("Failed to log response:", e) - ); - - return response; - }, - { config: retryConfig, statusCodes: retryCodes } - ).then( - (r) => OK(r), - (err) => { - switch (true) { - case isAbortError(err): - return ERR( - new RequestAbortedError("Request aborted by client", { cause: err }) - ); - case isTimeoutError(err): - return ERR(new RequestTimeoutError("Request timed out", { cause: err })); - case isConnectionError(err): - return ERR(new ConnectionError("Unable to make request", { cause: err })); - default: - return ERR( - new UnexpectedClientError("Unexpected HTTP client error", { - cause: err, - }) - ); - } - } - ); - } + }, + ); + } } const jsonLikeContentTypeRE = /^application\/(?:.{0,100}\+)?json/; async function logRequest(logger: Logger | undefined, req: Request) { - if (!logger) { - return; - } - - const contentType = req.headers.get("content-type"); - const ct = contentType?.split(";")[0] || ""; - - logger.group(`> Request: ${req.method} ${req.url}`); - - logger.group("Headers:"); - for (const [k, v] of req.headers.entries()) { - logger.log(`${k}: ${v}`); - } - logger.groupEnd(); - - logger.group("Body:"); - switch (true) { - case jsonLikeContentTypeRE.test(ct): - logger.log(await req.clone().json()); - break; - case ct.startsWith("text/"): - logger.log(await req.clone().text()); - break; - case ct === "multipart/form-data": { - const body = await req.clone().formData(); - for (const [k, v] of body) { - const vlabel = v instanceof Blob ? "" : v; - logger.log(`${k}: ${vlabel}`); - } - break; - } - default: - logger.log(`<${contentType}>`); - break; + if (!logger) { + return; + } + + const contentType = req.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + + logger.group(`> Request: ${req.method} ${req.url}`); + + logger.group("Headers:"); + for (const [k, v] of req.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + + logger.group("Body:"); + switch (true) { + case jsonLikeContentTypeRE.test(ct): + logger.log(await req.clone().json()); + break; + case ct.startsWith("text/"): + logger.log(await req.clone().text()); + break; + case ct === "multipart/form-data": { + const body = await req.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; } - logger.groupEnd(); + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); - logger.groupEnd(); + logger.groupEnd(); } -async function logResponse(logger: Logger | undefined, res: Response, req: Request) { - if (!logger) { - return; - } - - const contentType = res.headers.get("content-type"); - const ct = contentType?.split(";")[0] || ""; - - logger.group(`< Response: ${req.method} ${req.url}`); - logger.log("Status Code:", res.status, res.statusText); - - logger.group("Headers:"); - for (const [k, v] of res.headers.entries()) { - logger.log(`${k}: ${v}`); - } - logger.groupEnd(); - - logger.group("Body:"); - switch (true) { - case matchContentType(res, "application/json") || jsonLikeContentTypeRE.test(ct): - logger.log(await res.clone().json()); - break; - case matchContentType(res, "text/event-stream"): - logger.log(`<${contentType}>`); - break; - case matchContentType(res, "text/*"): - logger.log(await res.clone().text()); - break; - case matchContentType(res, "multipart/form-data"): { - const body = await res.clone().formData(); - for (const [k, v] of body) { - const vlabel = v instanceof Blob ? "" : v; - logger.log(`${k}: ${vlabel}`); - } - break; - } - default: - logger.log(`<${contentType}>`); - break; +async function logResponse( + logger: Logger | undefined, + res: Response, + req: Request, +) { + if (!logger) { + return; + } + + const contentType = res.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + + logger.group(`< Response: ${req.method} ${req.url}`); + logger.log("Status Code:", res.status, res.statusText); + + logger.group("Headers:"); + for (const [k, v] of res.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + + logger.group("Body:"); + switch (true) { + case matchContentType(res, "application/json") + || jsonLikeContentTypeRE.test(ct): + logger.log(await res.clone().json()); + break; + case matchContentType(res, "text/event-stream"): + logger.log(`<${contentType}>`); + break; + case matchContentType(res, "text/*"): + logger.log(await res.clone().text()); + break; + case matchContentType(res, "multipart/form-data"): { + const body = await res.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; } - logger.groupEnd(); + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); - logger.groupEnd(); + logger.groupEnd(); } diff --git a/ts/src/lib/security.ts b/ts/src/lib/security.ts index d529ec7..0e75079 100644 --- a/ts/src/lib/security.ts +++ b/ts/src/lib/security.ts @@ -3,179 +3,194 @@ */ export enum SecurityErrorCode { - Incomplete = "incomplete", - UnrecognisedSecurityType = "unrecognized_security_type", + Incomplete = "incomplete", + UnrecognisedSecurityType = "unrecognized_security_type", } export class SecurityError extends Error { - constructor(public code: SecurityErrorCode, message: string) { - super(message); - this.name = "SecurityError"; - } - - static incomplete(): SecurityError { - return new SecurityError( - SecurityErrorCode.Incomplete, - "Security requirements not met in order to perform the operation" - ); - } - static unrecognizedType(type: string): SecurityError { - return new SecurityError( - SecurityErrorCode.UnrecognisedSecurityType, - `Unrecognised security type: ${type}` - ); - } + constructor( + public code: SecurityErrorCode, + message: string, + ) { + super(message); + this.name = "SecurityError"; + } + + static incomplete(): SecurityError { + return new SecurityError( + SecurityErrorCode.Incomplete, + "Security requirements not met in order to perform the operation", + ); + } + static unrecognizedType(type: string): SecurityError { + return new SecurityError( + SecurityErrorCode.UnrecognisedSecurityType, + `Unrecognised security type: ${type}`, + ); + } } export type SecurityState = { - basic: { username?: string | undefined; password?: string | undefined }; - headers: Record; - queryParams: Record; - cookies: Record; + basic: { username?: string | undefined; password?: string | undefined }; + headers: Record; + queryParams: Record; + cookies: Record; }; type SecurityInputBasic = { - type: "http:basic"; - value: { username?: string | undefined; password?: string | undefined } | null | undefined; + type: "http:basic"; + value: + | { username?: string | undefined; password?: string | undefined } + | null + | undefined; }; type SecurityInputBearer = { - type: "http:bearer"; - value: string | null | undefined; - fieldName: string; + type: "http:bearer"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputAPIKey = { - type: "apiKey:header" | "apiKey:query" | "apiKey:cookie"; - value: string | null | undefined; - fieldName: string; + type: "apiKey:header" | "apiKey:query" | "apiKey:cookie"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOIDC = { - type: "openIdConnect"; - value: string | null | undefined; - fieldName: string; + type: "openIdConnect"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOAuth2 = { - type: "oauth2"; - value: string | null | undefined; - fieldName: string; + type: "oauth2"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOAuth2ClientCredentials = { - type: "oauth2:client_credentials"; - value: { clientID?: string | undefined; clientSecret?: string | undefined } | null | undefined; + type: "oauth2:client_credentials"; + value: + | { clientID?: string | undefined; clientSecret?: string | undefined } + | null + | undefined; }; type SecurityInputCustom = { - type: "http:custom"; - value: any | null | undefined; - fieldName: string; + type: "http:custom"; + value: any | null | undefined; + fieldName: string; }; export type SecurityInput = - | SecurityInputBasic - | SecurityInputBearer - | SecurityInputAPIKey - | SecurityInputOAuth2 - | SecurityInputOAuth2ClientCredentials - | SecurityInputOIDC - | SecurityInputCustom; - -export function resolveSecurity(...options: SecurityInput[][]): SecurityState | null { - const state: SecurityState = { - basic: { username: "", password: "" }, - headers: {}, - queryParams: {}, - cookies: {}, - }; - - const option = options.find((opts) => { - return opts.every((o) => { - if (o.value == null) { - return false; - } else if (o.type === "http:basic") { - return o.value.username != null || o.value.password != null; - } else if (o.type === "http:custom") { - return null; - } else if (o.type === "oauth2:client_credentials") { - return o.value.clientID != null || o.value.clientSecret != null; - } else if (typeof o.value === "string") { - return !!o.value; - } else { - throw new Error( - `Unrecognized security type: ${o.type} (value type: ${typeof o.value})` - ); - } - }); - }); - if (option == null) { + | SecurityInputBasic + | SecurityInputBearer + | SecurityInputAPIKey + | SecurityInputOAuth2 + | SecurityInputOAuth2ClientCredentials + | SecurityInputOIDC + | SecurityInputCustom; + +export function resolveSecurity( + ...options: SecurityInput[][] +): SecurityState | null { + const state: SecurityState = { + basic: { username: "", password: "" }, + headers: {}, + queryParams: {}, + cookies: {}, + }; + + const option = options.find((opts) => { + return opts.every((o) => { + if (o.value == null) { + return false; + } else if (o.type === "http:basic") { + return o.value.username != null || o.value.password != null; + } else if (o.type === "http:custom") { return null; + } else if (o.type === "oauth2:client_credentials") { + return o.value.clientID != null || o.value.clientSecret != null; + } else if (typeof o.value === "string") { + return !!o.value; + } else { + throw new Error( + `Unrecognized security type: ${o.type} (value type: ${typeof o + .value})`, + ); + } + }); + }); + if (option == null) { + return null; + } + + option.forEach((spec) => { + if (spec.value == null) { + return; } - option.forEach((spec) => { - if (spec.value == null) { - return; - } - - const { type } = spec; - - switch (type) { - case "apiKey:header": - state.headers[spec.fieldName] = spec.value; - break; - case "apiKey:query": - state.queryParams[spec.fieldName] = spec.value; - break; - case "apiKey:cookie": - state.cookies[spec.fieldName] = spec.value; - break; - case "http:basic": - applyBasic(state, spec); - break; - case "http:custom": - break; - case "http:bearer": - applyBearer(state, spec); - break; - case "oauth2": - applyBearer(state, spec); - break; - case "oauth2:client_credentials": - break; - case "openIdConnect": - applyBearer(state, spec); - break; - default: - spec satisfies never; - throw SecurityError.unrecognizedType(type); - } - }); + const { type } = spec; + + switch (type) { + case "apiKey:header": + state.headers[spec.fieldName] = spec.value; + break; + case "apiKey:query": + state.queryParams[spec.fieldName] = spec.value; + break; + case "apiKey:cookie": + state.cookies[spec.fieldName] = spec.value; + break; + case "http:basic": + applyBasic(state, spec); + break; + case "http:custom": + break; + case "http:bearer": + applyBearer(state, spec); + break; + case "oauth2": + applyBearer(state, spec); + break; + case "oauth2:client_credentials": + break; + case "openIdConnect": + applyBearer(state, spec); + break; + default: + spec satisfies never; + throw SecurityError.unrecognizedType(type); + } + }); - return state; + return state; } -function applyBasic(state: SecurityState, spec: SecurityInputBasic) { - if (spec.value == null) { - return; - } +function applyBasic( + state: SecurityState, + spec: SecurityInputBasic, +) { + if (spec.value == null) { + return; + } - state.basic = spec.value; + state.basic = spec.value; } function applyBearer( - state: SecurityState, - spec: SecurityInputBearer | SecurityInputOAuth2 | SecurityInputOIDC + state: SecurityState, + spec: SecurityInputBearer | SecurityInputOAuth2 | SecurityInputOIDC, ) { - if (spec.value == null) { - return; - } + if (spec.value == null) { + return; + } - let value = spec.value; - if (value.slice(0, 7).toLowerCase() !== "bearer ") { - value = `Bearer ${value}`; - } + let value = spec.value; + if (value.slice(0, 7).toLowerCase() !== "bearer ") { + value = `Bearer ${value}`; + } - state.headers[spec.fieldName] = value; + state.headers[spec.fieldName] = value; } diff --git a/ts/src/models/components/error.ts b/ts/src/models/components/error.ts index 8caa141..9936eb0 100644 --- a/ts/src/models/components/error.ts +++ b/ts/src/models/components/error.ts @@ -5,26 +5,31 @@ import * as z from "zod"; export type ErrorT = { - code: number; - message: string; + code: number; + message: string; }; /** @internal */ -export const ErrorT$inboundSchema: z.ZodType = z.object({ +export const ErrorT$inboundSchema: z.ZodType = z + .object({ code: z.number().int(), message: z.string(), -}); + }); /** @internal */ export type ErrorT$Outbound = { - code: number; - message: string; + code: number; + message: string; }; /** @internal */ -export const ErrorT$outboundSchema: z.ZodType = z.object({ - code: z.number().int(), - message: z.string(), +export const ErrorT$outboundSchema: z.ZodType< + ErrorT$Outbound, + z.ZodTypeDef, + ErrorT +> = z.object({ + code: z.number().int(), + message: z.string(), }); /** @@ -32,10 +37,10 @@ export const ErrorT$outboundSchema: z.ZodType = z - .object({ - Response: z.instanceof(Response), - Request: z.instanceof(Request), - }) - .transform((v) => { - return remap$(v, { - Response: "response", - Request: "request", - }); - }); +export const HTTPMetadata$inboundSchema: z.ZodType< + HTTPMetadata, + z.ZodTypeDef, + unknown +> = z.object({ + Response: z.instanceof(Response), + Request: z.instanceof(Request), +}).transform((v) => { + return remap$(v, { + "Response": "response", + "Request": "request", + }); +}); /** @internal */ export type HTTPMetadata$Outbound = { - Response: never; - Request: never; + Response: never; + Request: never; }; /** @internal */ export const HTTPMetadata$outboundSchema: z.ZodType< - HTTPMetadata$Outbound, - z.ZodTypeDef, - HTTPMetadata -> = z - .object({ - response: z.instanceof(Response).transform(() => { - throw new Error("Response cannot be serialized"); - }), - request: z.instanceof(Request).transform(() => { - throw new Error("Response cannot be serialized"); - }), - }) - .transform((v) => { - return remap$(v, { - response: "Response", - request: "Request", - }); - }); + HTTPMetadata$Outbound, + z.ZodTypeDef, + HTTPMetadata +> = z.object({ + response: z.instanceof(Response).transform(() => { + throw new Error("Response cannot be serialized"); + }), + request: z.instanceof(Request).transform(() => { + throw new Error("Response cannot be serialized"); + }), +}).transform((v) => { + return remap$(v, { + response: "Response", + request: "Request", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace HTTPMetadata$ { - /** @deprecated use `HTTPMetadata$inboundSchema` instead. */ - export const inboundSchema = HTTPMetadata$inboundSchema; - /** @deprecated use `HTTPMetadata$outboundSchema` instead. */ - export const outboundSchema = HTTPMetadata$outboundSchema; - /** @deprecated use `HTTPMetadata$Outbound` instead. */ - export type Outbound = HTTPMetadata$Outbound; + /** @deprecated use `HTTPMetadata$inboundSchema` instead. */ + export const inboundSchema = HTTPMetadata$inboundSchema; + /** @deprecated use `HTTPMetadata$outboundSchema` instead. */ + export const outboundSchema = HTTPMetadata$outboundSchema; + /** @deprecated use `HTTPMetadata$Outbound` instead. */ + export type Outbound = HTTPMetadata$Outbound; } diff --git a/ts/src/models/components/pet.ts b/ts/src/models/components/pet.ts index 333a92d..14eed1a 100644 --- a/ts/src/models/components/pet.ts +++ b/ts/src/models/components/pet.ts @@ -5,41 +5,43 @@ import * as z from "zod"; export type Pet = { - id: number; - name: string; - tag?: string | undefined; + id: number; + name: string; + tag?: string | undefined; }; /** @internal */ -export const Pet$inboundSchema: z.ZodType = z.object({ +export const Pet$inboundSchema: z.ZodType = z + .object({ id: z.number().int(), name: z.string(), tag: z.string().optional(), -}); + }); /** @internal */ export type Pet$Outbound = { - id: number; - name: string; - tag?: string | undefined; + id: number; + name: string; + tag?: string | undefined; }; /** @internal */ -export const Pet$outboundSchema: z.ZodType = z.object({ +export const Pet$outboundSchema: z.ZodType = z + .object({ id: z.number().int(), name: z.string(), tag: z.string().optional(), -}); + }); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace Pet$ { - /** @deprecated use `Pet$inboundSchema` instead. */ - export const inboundSchema = Pet$inboundSchema; - /** @deprecated use `Pet$outboundSchema` instead. */ - export const outboundSchema = Pet$outboundSchema; - /** @deprecated use `Pet$Outbound` instead. */ - export type Outbound = Pet$Outbound; + /** @deprecated use `Pet$inboundSchema` instead. */ + export const inboundSchema = Pet$inboundSchema; + /** @deprecated use `Pet$outboundSchema` instead. */ + export const outboundSchema = Pet$outboundSchema; + /** @deprecated use `Pet$Outbound` instead. */ + export type Outbound = Pet$Outbound; } diff --git a/ts/src/models/errors/httpclienterrors.ts b/ts/src/models/errors/httpclienterrors.ts index cdb2995..b34f612 100644 --- a/ts/src/models/errors/httpclienterrors.ts +++ b/ts/src/models/errors/httpclienterrors.ts @@ -6,43 +6,43 @@ * Base class for all HTTP errors. */ export class HTTPClientError extends Error { - /** The underlying cause of the error. */ - override readonly cause: unknown; - override name = "HTTPClientError"; - constructor(message: string, opts?: { cause?: unknown }) { - let msg = message; - if (opts?.cause) { - msg += `: ${opts.cause}`; - } + /** The underlying cause of the error. */ + override readonly cause: unknown; + override name = "HTTPClientError"; + constructor(message: string, opts?: { cause?: unknown }) { + let msg = message; + if (opts?.cause) { + msg += `: ${opts.cause}`; + } - super(msg, opts); - // In older runtimes, the cause field would not have been assigned through - // the super() call. - if (typeof this.cause === "undefined") { - this.cause = opts?.cause; - } + super(msg, opts); + // In older runtimes, the cause field would not have been assigned through + // the super() call. + if (typeof this.cause === "undefined") { + this.cause = opts?.cause; } + } } /** * An error to capture unrecognised or unexpected errors when making HTTP calls. */ export class UnexpectedClientError extends HTTPClientError { - override name = "UnexpectedClientError"; + override name = "UnexpectedClientError"; } /** * An error that is raised when any inputs used to create a request are invalid. */ export class InvalidRequestError extends HTTPClientError { - override name = "InvalidRequestError"; + override name = "InvalidRequestError"; } /** * An error that is raised when a HTTP request was aborted by the client error. */ export class RequestAbortedError extends HTTPClientError { - override readonly name = "RequestAbortedError"; + override readonly name = "RequestAbortedError"; } /** @@ -50,7 +50,7 @@ export class RequestAbortedError extends HTTPClientError { * signal timeout. */ export class RequestTimeoutError extends HTTPClientError { - override readonly name = "RequestTimeoutError"; + override readonly name = "RequestTimeoutError"; } /** @@ -58,5 +58,5 @@ export class RequestTimeoutError extends HTTPClientError { * a server. */ export class ConnectionError extends HTTPClientError { - override readonly name = "ConnectionError"; + override readonly name = "ConnectionError"; } diff --git a/ts/src/models/errors/sdkerror.ts b/ts/src/models/errors/sdkerror.ts index f4a15bc..1c2adb2 100644 --- a/ts/src/models/errors/sdkerror.ts +++ b/ts/src/models/errors/sdkerror.ts @@ -3,19 +3,19 @@ */ export class SDKError extends Error { - constructor( - message: string, - public readonly httpMeta: { - response: Response; - request: Request; - } - ) { - super( - `${message}: Status ${httpMeta.response.status} Content-Type ${ - httpMeta.response.headers.get("content-type") || "" - }` - ); + constructor( + message: string, + public readonly httpMeta: { + response: Response; + request: Request; + }, + ) { + super( + `${message}: Status ${httpMeta.response.status} Content-Type ${ + httpMeta.response.headers.get("content-type") || "" + }`, + ); - this.name = "SDKError"; - } + this.name = "SDKError"; + } } diff --git a/ts/src/models/operations/createpets.ts b/ts/src/models/operations/createpets.ts index 15814fa..258def8 100644 --- a/ts/src/models/operations/createpets.ts +++ b/ts/src/models/operations/createpets.ts @@ -2,67 +2,63 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { remap as remap$ } from "../../lib/primitives.js"; import * as components from "../components/index.js"; -import * as z from "zod"; export type CreatePetsResponse = { - httpMeta: components.HTTPMetadata; - /** - * unexpected error - */ - error?: components.ErrorT | undefined; + httpMeta: components.HTTPMetadata; + /** + * unexpected error + */ + error?: components.ErrorT | undefined; }; /** @internal */ export const CreatePetsResponse$inboundSchema: z.ZodType< - CreatePetsResponse, - z.ZodTypeDef, - unknown -> = z - .object({ - HttpMeta: components.HTTPMetadata$inboundSchema, - Error: components.ErrorT$inboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - HttpMeta: "httpMeta", - Error: "error", - }); - }); + CreatePetsResponse, + z.ZodTypeDef, + unknown +> = z.object({ + HttpMeta: components.HTTPMetadata$inboundSchema, + Error: components.ErrorT$inboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + "HttpMeta": "httpMeta", + "Error": "error", + }); +}); /** @internal */ export type CreatePetsResponse$Outbound = { - HttpMeta: components.HTTPMetadata$Outbound; - Error?: components.ErrorT$Outbound | undefined; + HttpMeta: components.HTTPMetadata$Outbound; + Error?: components.ErrorT$Outbound | undefined; }; /** @internal */ export const CreatePetsResponse$outboundSchema: z.ZodType< - CreatePetsResponse$Outbound, - z.ZodTypeDef, - CreatePetsResponse -> = z - .object({ - httpMeta: components.HTTPMetadata$outboundSchema, - error: components.ErrorT$outboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - httpMeta: "HttpMeta", - error: "Error", - }); - }); + CreatePetsResponse$Outbound, + z.ZodTypeDef, + CreatePetsResponse +> = z.object({ + httpMeta: components.HTTPMetadata$outboundSchema, + error: components.ErrorT$outboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + httpMeta: "HttpMeta", + error: "Error", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace CreatePetsResponse$ { - /** @deprecated use `CreatePetsResponse$inboundSchema` instead. */ - export const inboundSchema = CreatePetsResponse$inboundSchema; - /** @deprecated use `CreatePetsResponse$outboundSchema` instead. */ - export const outboundSchema = CreatePetsResponse$outboundSchema; - /** @deprecated use `CreatePetsResponse$Outbound` instead. */ - export type Outbound = CreatePetsResponse$Outbound; + /** @deprecated use `CreatePetsResponse$inboundSchema` instead. */ + export const inboundSchema = CreatePetsResponse$inboundSchema; + /** @deprecated use `CreatePetsResponse$outboundSchema` instead. */ + export const outboundSchema = CreatePetsResponse$outboundSchema; + /** @deprecated use `CreatePetsResponse$Outbound` instead. */ + export type Outbound = CreatePetsResponse$Outbound; } diff --git a/ts/src/models/operations/listpets.ts b/ts/src/models/operations/listpets.ts index dbd1199..e7807a1 100644 --- a/ts/src/models/operations/listpets.ts +++ b/ts/src/models/operations/listpets.ts @@ -2,48 +2,51 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { remap as remap$ } from "../../lib/primitives.js"; import * as components from "../components/index.js"; -import * as z from "zod"; export type ListPetsRequest = { - /** - * How many items to return at one time (max 100) - */ - limit?: number | undefined; + /** + * How many items to return at one time (max 100) + */ + limit?: number | undefined; }; export type ListPetsResponse = { - httpMeta: components.HTTPMetadata; - /** - * A paged array of pets - */ - pets?: Array | undefined; - /** - * unexpected error - */ - error?: components.ErrorT | undefined; - headers: { [k: string]: Array }; + httpMeta: components.HTTPMetadata; + /** + * A paged array of pets + */ + pets?: Array | undefined; + /** + * unexpected error + */ + error?: components.ErrorT | undefined; + headers: { [k: string]: Array }; }; /** @internal */ -export const ListPetsRequest$inboundSchema: z.ZodType = - z.object({ - limit: z.number().int().optional(), - }); +export const ListPetsRequest$inboundSchema: z.ZodType< + ListPetsRequest, + z.ZodTypeDef, + unknown +> = z.object({ + limit: z.number().int().optional(), +}); /** @internal */ export type ListPetsRequest$Outbound = { - limit?: number | undefined; + limit?: number | undefined; }; /** @internal */ export const ListPetsRequest$outboundSchema: z.ZodType< - ListPetsRequest$Outbound, - z.ZodTypeDef, - ListPetsRequest + ListPetsRequest$Outbound, + z.ZodTypeDef, + ListPetsRequest > = z.object({ - limit: z.number().int().optional(), + limit: z.number().int().optional(), }); /** @@ -51,69 +54,69 @@ export const ListPetsRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ListPetsRequest$ { - /** @deprecated use `ListPetsRequest$inboundSchema` instead. */ - export const inboundSchema = ListPetsRequest$inboundSchema; - /** @deprecated use `ListPetsRequest$outboundSchema` instead. */ - export const outboundSchema = ListPetsRequest$outboundSchema; - /** @deprecated use `ListPetsRequest$Outbound` instead. */ - export type Outbound = ListPetsRequest$Outbound; + /** @deprecated use `ListPetsRequest$inboundSchema` instead. */ + export const inboundSchema = ListPetsRequest$inboundSchema; + /** @deprecated use `ListPetsRequest$outboundSchema` instead. */ + export const outboundSchema = ListPetsRequest$outboundSchema; + /** @deprecated use `ListPetsRequest$Outbound` instead. */ + export type Outbound = ListPetsRequest$Outbound; } /** @internal */ -export const ListPetsResponse$inboundSchema: z.ZodType = z - .object({ - HttpMeta: components.HTTPMetadata$inboundSchema, - Pets: z.array(components.Pet$inboundSchema).optional(), - Error: components.ErrorT$inboundSchema.optional(), - Headers: z.record(z.array(z.string())), - }) - .transform((v) => { - return remap$(v, { - HttpMeta: "httpMeta", - Pets: "pets", - Error: "error", - Headers: "headers", - }); - }); +export const ListPetsResponse$inboundSchema: z.ZodType< + ListPetsResponse, + z.ZodTypeDef, + unknown +> = z.object({ + HttpMeta: components.HTTPMetadata$inboundSchema, + Pets: z.array(components.Pet$inboundSchema).optional(), + Error: components.ErrorT$inboundSchema.optional(), + Headers: z.record(z.array(z.string())), +}).transform((v) => { + return remap$(v, { + "HttpMeta": "httpMeta", + "Pets": "pets", + "Error": "error", + "Headers": "headers", + }); +}); /** @internal */ export type ListPetsResponse$Outbound = { - HttpMeta: components.HTTPMetadata$Outbound; - Pets?: Array | undefined; - Error?: components.ErrorT$Outbound | undefined; - Headers: { [k: string]: Array }; + HttpMeta: components.HTTPMetadata$Outbound; + Pets?: Array | undefined; + Error?: components.ErrorT$Outbound | undefined; + Headers: { [k: string]: Array }; }; /** @internal */ export const ListPetsResponse$outboundSchema: z.ZodType< - ListPetsResponse$Outbound, - z.ZodTypeDef, - ListPetsResponse -> = z - .object({ - httpMeta: components.HTTPMetadata$outboundSchema, - pets: z.array(components.Pet$outboundSchema).optional(), - error: components.ErrorT$outboundSchema.optional(), - headers: z.record(z.array(z.string())), - }) - .transform((v) => { - return remap$(v, { - httpMeta: "HttpMeta", - pets: "Pets", - error: "Error", - headers: "Headers", - }); - }); + ListPetsResponse$Outbound, + z.ZodTypeDef, + ListPetsResponse +> = z.object({ + httpMeta: components.HTTPMetadata$outboundSchema, + pets: z.array(components.Pet$outboundSchema).optional(), + error: components.ErrorT$outboundSchema.optional(), + headers: z.record(z.array(z.string())), +}).transform((v) => { + return remap$(v, { + httpMeta: "HttpMeta", + pets: "Pets", + error: "Error", + headers: "Headers", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ListPetsResponse$ { - /** @deprecated use `ListPetsResponse$inboundSchema` instead. */ - export const inboundSchema = ListPetsResponse$inboundSchema; - /** @deprecated use `ListPetsResponse$outboundSchema` instead. */ - export const outboundSchema = ListPetsResponse$outboundSchema; - /** @deprecated use `ListPetsResponse$Outbound` instead. */ - export type Outbound = ListPetsResponse$Outbound; + /** @deprecated use `ListPetsResponse$inboundSchema` instead. */ + export const inboundSchema = ListPetsResponse$inboundSchema; + /** @deprecated use `ListPetsResponse$outboundSchema` instead. */ + export const outboundSchema = ListPetsResponse$outboundSchema; + /** @deprecated use `ListPetsResponse$Outbound` instead. */ + export type Outbound = ListPetsResponse$Outbound; } diff --git a/ts/src/models/operations/showpetbyid.ts b/ts/src/models/operations/showpetbyid.ts index 6cc5c40..0785213 100644 --- a/ts/src/models/operations/showpetbyid.ts +++ b/ts/src/models/operations/showpetbyid.ts @@ -2,50 +2,50 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { remap as remap$ } from "../../lib/primitives.js"; import * as components from "../components/index.js"; -import * as z from "zod"; export type ShowPetByIdRequest = { - /** - * The id of the pet to retrieve - */ - petId: string; + /** + * The id of the pet to retrieve + */ + petId: string; }; export type ShowPetByIdResponse = { - httpMeta: components.HTTPMetadata; - /** - * Expected response to a valid request - */ - pet?: components.Pet | undefined; - /** - * unexpected error - */ - error?: components.ErrorT | undefined; + httpMeta: components.HTTPMetadata; + /** + * Expected response to a valid request + */ + pet?: components.Pet | undefined; + /** + * unexpected error + */ + error?: components.ErrorT | undefined; }; /** @internal */ export const ShowPetByIdRequest$inboundSchema: z.ZodType< - ShowPetByIdRequest, - z.ZodTypeDef, - unknown + ShowPetByIdRequest, + z.ZodTypeDef, + unknown > = z.object({ - petId: z.string(), + petId: z.string(), }); /** @internal */ export type ShowPetByIdRequest$Outbound = { - petId: string; + petId: string; }; /** @internal */ export const ShowPetByIdRequest$outboundSchema: z.ZodType< - ShowPetByIdRequest$Outbound, - z.ZodTypeDef, - ShowPetByIdRequest + ShowPetByIdRequest$Outbound, + z.ZodTypeDef, + ShowPetByIdRequest > = z.object({ - petId: z.string(), + petId: z.string(), }); /** @@ -53,68 +53,64 @@ export const ShowPetByIdRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ShowPetByIdRequest$ { - /** @deprecated use `ShowPetByIdRequest$inboundSchema` instead. */ - export const inboundSchema = ShowPetByIdRequest$inboundSchema; - /** @deprecated use `ShowPetByIdRequest$outboundSchema` instead. */ - export const outboundSchema = ShowPetByIdRequest$outboundSchema; - /** @deprecated use `ShowPetByIdRequest$Outbound` instead. */ - export type Outbound = ShowPetByIdRequest$Outbound; + /** @deprecated use `ShowPetByIdRequest$inboundSchema` instead. */ + export const inboundSchema = ShowPetByIdRequest$inboundSchema; + /** @deprecated use `ShowPetByIdRequest$outboundSchema` instead. */ + export const outboundSchema = ShowPetByIdRequest$outboundSchema; + /** @deprecated use `ShowPetByIdRequest$Outbound` instead. */ + export type Outbound = ShowPetByIdRequest$Outbound; } /** @internal */ export const ShowPetByIdResponse$inboundSchema: z.ZodType< - ShowPetByIdResponse, - z.ZodTypeDef, - unknown -> = z - .object({ - HttpMeta: components.HTTPMetadata$inboundSchema, - Pet: components.Pet$inboundSchema.optional(), - Error: components.ErrorT$inboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - HttpMeta: "httpMeta", - Pet: "pet", - Error: "error", - }); - }); + ShowPetByIdResponse, + z.ZodTypeDef, + unknown +> = z.object({ + HttpMeta: components.HTTPMetadata$inboundSchema, + Pet: components.Pet$inboundSchema.optional(), + Error: components.ErrorT$inboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + "HttpMeta": "httpMeta", + "Pet": "pet", + "Error": "error", + }); +}); /** @internal */ export type ShowPetByIdResponse$Outbound = { - HttpMeta: components.HTTPMetadata$Outbound; - Pet?: components.Pet$Outbound | undefined; - Error?: components.ErrorT$Outbound | undefined; + HttpMeta: components.HTTPMetadata$Outbound; + Pet?: components.Pet$Outbound | undefined; + Error?: components.ErrorT$Outbound | undefined; }; /** @internal */ export const ShowPetByIdResponse$outboundSchema: z.ZodType< - ShowPetByIdResponse$Outbound, - z.ZodTypeDef, - ShowPetByIdResponse -> = z - .object({ - httpMeta: components.HTTPMetadata$outboundSchema, - pet: components.Pet$outboundSchema.optional(), - error: components.ErrorT$outboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - httpMeta: "HttpMeta", - pet: "Pet", - error: "Error", - }); - }); + ShowPetByIdResponse$Outbound, + z.ZodTypeDef, + ShowPetByIdResponse +> = z.object({ + httpMeta: components.HTTPMetadata$outboundSchema, + pet: components.Pet$outboundSchema.optional(), + error: components.ErrorT$outboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + httpMeta: "HttpMeta", + pet: "Pet", + error: "Error", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ShowPetByIdResponse$ { - /** @deprecated use `ShowPetByIdResponse$inboundSchema` instead. */ - export const inboundSchema = ShowPetByIdResponse$inboundSchema; - /** @deprecated use `ShowPetByIdResponse$outboundSchema` instead. */ - export const outboundSchema = ShowPetByIdResponse$outboundSchema; - /** @deprecated use `ShowPetByIdResponse$Outbound` instead. */ - export type Outbound = ShowPetByIdResponse$Outbound; + /** @deprecated use `ShowPetByIdResponse$inboundSchema` instead. */ + export const inboundSchema = ShowPetByIdResponse$inboundSchema; + /** @deprecated use `ShowPetByIdResponse$outboundSchema` instead. */ + export const outboundSchema = ShowPetByIdResponse$outboundSchema; + /** @deprecated use `ShowPetByIdResponse$Outbound` instead. */ + export type Outbound = ShowPetByIdResponse$Outbound; } diff --git a/ts/src/sdk/pets.ts b/ts/src/sdk/pets.ts index 27dcb8c..f528797 100644 --- a/ts/src/sdk/pets.ts +++ b/ts/src/sdk/pets.ts @@ -11,33 +11,45 @@ import * as operations from "../models/operations/index.js"; import { unwrapAsync } from "../types/fp.js"; export class Pets extends ClientSDK { - /** - * List all pets - */ - async listPets( - limit?: number | undefined, - options?: RequestOptions - ): Promise { - return unwrapAsync(petsListPets(this, limit, options)); - } + /** + * List all pets + */ + async listPets( + limit?: number | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petsListPets( + this, + limit, + options, + )); + } - /** - * Create a pet - */ - async createPets( - request: components.Pet, - options?: RequestOptions - ): Promise { - return unwrapAsync(petsCreatePets(this, request, options)); - } + /** + * Create a pet + */ + async createPets( + request: components.Pet, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petsCreatePets( + this, + request, + options, + )); + } - /** - * Info for a specific pet - */ - async showPetById( - petId: string, - options?: RequestOptions - ): Promise { - return unwrapAsync(petsShowPetById(this, petId, options)); - } + /** + * Info for a specific pet + */ + async showPetById( + petId: string, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petsShowPetById( + this, + petId, + options, + )); + } } diff --git a/ts/src/sdk/sdk.ts b/ts/src/sdk/sdk.ts index d3eae7d..2b33371 100644 --- a/ts/src/sdk/sdk.ts +++ b/ts/src/sdk/sdk.ts @@ -6,8 +6,8 @@ import { ClientSDK } from "../lib/sdks.js"; import { Pets } from "./pets.js"; export class RyTs extends ClientSDK { - private _pets?: Pets; - get pets(): Pets { - return (this._pets ??= new Pets(this.options$)); - } + private _pets?: Pets; + get pets(): Pets { + return (this._pets ??= new Pets(this._options)); + } } diff --git a/ts/src/types/index.ts b/ts/src/types/index.ts index dbaa5e6..e124e81 100644 --- a/ts/src/types/index.ts +++ b/ts/src/types/index.ts @@ -2,10 +2,10 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export { RFCDate } from "./rfcdate.js"; export { blobLikeSchema, isBlobLike } from "./blobs.js"; -export type { Paginator, PageIterator } from "./operations.js"; -export { createPageIterator } from "./operations.js"; export { catchUnrecognizedEnum } from "./enums.js"; -export type { OpenEnum, ClosedEnum, Unrecognized } from "./enums.js"; +export type { ClosedEnum, OpenEnum, Unrecognized } from "./enums.js"; export type { Result } from "./fp.js"; +export type { PageIterator, Paginator } from "./operations.js"; +export { createPageIterator } from "./operations.js"; +export { RFCDate } from "./rfcdate.js";