├── .fernignore ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .npmignore ├── .prettierrc.yml ├── README.md ├── jest.config.mjs ├── package.json ├── reference.md ├── scripts └── rename-to-esm-files.js ├── src ├── Client.ts ├── api │ ├── index.ts │ └── resources │ │ ├── apiStatus │ │ ├── client │ │ │ ├── Client.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ └── types │ │ │ ├── ApiInfo.ts │ │ │ └── index.ts │ │ ├── auth │ │ ├── client │ │ │ ├── Client.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ └── types │ │ │ ├── TokenGrant.ts │ │ │ ├── TokenRequest.ts │ │ │ ├── TokenResponse.ts │ │ │ └── index.ts │ │ ├── embedding │ │ ├── index.ts │ │ └── types │ │ │ ├── Embedding.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ ├── infill │ │ ├── client │ │ │ ├── Client.ts │ │ │ ├── index.ts │ │ │ └── requests │ │ │ │ ├── InfillBytesRequest.ts │ │ │ │ └── index.ts │ │ └── index.ts │ │ ├── tts │ │ ├── client │ │ │ ├── Client.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ └── types │ │ │ ├── CancelContextRequest.ts │ │ │ ├── ContextId.ts │ │ │ ├── Controls.ts │ │ │ ├── Emotion.ts │ │ │ ├── FlushId.ts │ │ │ ├── GenerationRequest.ts │ │ │ ├── ModelSpeed.ts │ │ │ ├── Mp3OutputFormat.ts │ │ │ ├── NaturalSpecifier.ts │ │ │ ├── NumericalSpecifier.ts │ │ │ ├── OutputFormat.ts │ │ │ ├── PhonemeTimestamps.ts │ │ │ ├── RawEncoding.ts │ │ │ ├── RawOutputFormat.ts │ │ │ ├── Speed.ts │ │ │ ├── SupportedLanguage.ts │ │ │ ├── TtsRequest.ts │ │ │ ├── TtsRequestEmbeddingSpecifier.ts │ │ │ ├── TtsRequestIdSpecifier.ts │ │ │ ├── TtsRequestVoiceSpecifier.ts │ │ │ ├── WavOutputFormat.ts │ │ │ ├── WebSocketBaseResponse.ts │ │ │ ├── WebSocketChunkResponse.ts │ │ │ ├── WebSocketDoneResponse.ts │ │ │ ├── WebSocketErrorResponse.ts │ │ │ ├── WebSocketFlushDoneResponse.ts │ │ │ ├── WebSocketPhonemeTimestampsResponse.ts │ │ │ ├── WebSocketRawOutputFormat.ts │ │ │ ├── WebSocketRequest.ts │ │ │ ├── WebSocketResponse.ts │ │ │ ├── WebSocketStreamOptions.ts │ │ │ ├── WebSocketTimestampsResponse.ts │ │ │ ├── WebSocketTtsOutput.ts │ │ │ ├── WebSocketTtsRequest.ts │ │ │ ├── WordTimestamps.ts │ │ │ └── index.ts │ │ ├── voiceChanger │ │ ├── client │ │ │ ├── Client.ts │ │ │ ├── index.ts │ │ │ └── requests │ │ │ │ ├── VoiceChangerBytesRequest.ts │ │ │ │ ├── VoiceChangerSseRequest.ts │ │ │ │ └── index.ts │ │ ├── index.ts │ │ └── types │ │ │ ├── OutputFormatContainer.ts │ │ │ ├── StreamingResponse.ts │ │ │ └── index.ts │ │ └── voices │ │ ├── client │ │ ├── Client.ts │ │ ├── index.ts │ │ └── requests │ │ │ ├── CloneVoiceRequest.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ └── types │ │ ├── BaseVoiceId.ts │ │ ├── CloneMode.ts │ │ ├── CreateVoiceRequest.ts │ │ ├── EmbeddingResponse.ts │ │ ├── EmbeddingSpecifier.ts │ │ ├── Gender.ts │ │ ├── IdSpecifier.ts │ │ ├── LocalizeDialect.ts │ │ ├── LocalizeEnglishDialect.ts │ │ ├── LocalizeFrenchDialect.ts │ │ ├── LocalizePortugueseDialect.ts │ │ ├── LocalizeSpanishDialect.ts │ │ ├── LocalizeTargetLanguage.ts │ │ ├── LocalizeVoiceRequest.ts │ │ ├── MixVoiceSpecifier.ts │ │ ├── MixVoicesRequest.ts │ │ ├── UpdateVoiceRequest.ts │ │ ├── Voice.ts │ │ ├── VoiceId.ts │ │ ├── VoiceMetadata.ts │ │ ├── Weight.ts │ │ └── index.ts ├── core │ ├── fetcher │ │ ├── APIResponse.ts │ │ ├── Fetcher.ts │ │ ├── Supplier.ts │ │ ├── createRequestUrl.ts │ │ ├── getFetchFn.ts │ │ ├── getHeader.ts │ │ ├── getRequestBody.ts │ │ ├── getResponseBody.ts │ │ ├── index.ts │ │ ├── makeRequest.ts │ │ ├── requestWithRetries.ts │ │ ├── signals.ts │ │ └── stream-wrappers │ │ │ ├── Node18UniversalStreamWrapper.ts │ │ │ ├── NodePre18StreamWrapper.ts │ │ │ ├── UndiciStreamWrapper.ts │ │ │ └── chooseStreamWrapper.ts │ ├── form-data-utils │ │ ├── FormDataWrapper.ts │ │ └── index.ts │ ├── index.ts │ ├── json.ts │ ├── runtime │ │ ├── index.ts │ │ └── runtime.ts │ ├── schemas │ │ ├── Schema.ts │ │ ├── builders │ │ │ ├── bigint │ │ │ │ ├── bigint.ts │ │ │ │ └── index.ts │ │ │ ├── date │ │ │ │ ├── date.ts │ │ │ │ └── index.ts │ │ │ ├── enum │ │ │ │ ├── enum.ts │ │ │ │ └── index.ts │ │ │ ├── index.ts │ │ │ ├── lazy │ │ │ │ ├── index.ts │ │ │ │ ├── lazy.ts │ │ │ │ └── lazyObject.ts │ │ │ ├── list │ │ │ │ ├── index.ts │ │ │ │ └── list.ts │ │ │ ├── literals │ │ │ │ ├── booleanLiteral.ts │ │ │ │ ├── index.ts │ │ │ │ └── stringLiteral.ts │ │ │ ├── object-like │ │ │ │ ├── getObjectLikeUtils.ts │ │ │ │ ├── index.ts │ │ │ │ └── types.ts │ │ │ ├── object │ │ │ │ ├── index.ts │ │ │ │ ├── object.ts │ │ │ │ ├── objectWithoutOptionalProperties.ts │ │ │ │ ├── property.ts │ │ │ │ └── types.ts │ │ │ ├── primitives │ │ │ │ ├── any.ts │ │ │ │ ├── boolean.ts │ │ │ │ ├── index.ts │ │ │ │ ├── number.ts │ │ │ │ ├── string.ts │ │ │ │ └── unknown.ts │ │ │ ├── record │ │ │ │ ├── index.ts │ │ │ │ ├── record.ts │ │ │ │ └── types.ts │ │ │ ├── schema-utils │ │ │ │ ├── JsonError.ts │ │ │ │ ├── ParseError.ts │ │ │ │ ├── getSchemaUtils.ts │ │ │ │ ├── index.ts │ │ │ │ └── stringifyValidationErrors.ts │ │ │ ├── set │ │ │ │ ├── index.ts │ │ │ │ └── set.ts │ │ │ ├── undiscriminated-union │ │ │ │ ├── index.ts │ │ │ │ ├── types.ts │ │ │ │ └── undiscriminatedUnion.ts │ │ │ └── union │ │ │ │ ├── discriminant.ts │ │ │ │ ├── index.ts │ │ │ │ ├── types.ts │ │ │ │ └── union.ts │ │ ├── index.ts │ │ └── utils │ │ │ ├── MaybePromise.ts │ │ │ ├── addQuestionMarksToNullableProperties.ts │ │ │ ├── createIdentitySchemaCreator.ts │ │ │ ├── entries.ts │ │ │ ├── filterObject.ts │ │ │ ├── getErrorMessageForIncorrectType.ts │ │ │ ├── isPlainObject.ts │ │ │ ├── keys.ts │ │ │ ├── maybeSkipValidation.ts │ │ │ └── partition.ts │ ├── streaming-fetcher │ │ ├── Stream.ts │ │ └── index.ts │ └── websocket │ │ ├── events.ts │ │ ├── index.ts │ │ └── ws.ts ├── environments.ts ├── errors │ ├── CartesiaError.ts │ ├── CartesiaTimeoutError.ts │ └── index.ts ├── index.ts ├── serialization │ ├── index.ts │ └── resources │ │ ├── apiStatus │ │ ├── index.ts │ │ └── types │ │ │ ├── ApiInfo.ts │ │ │ └── index.ts │ │ ├── auth │ │ ├── index.ts │ │ └── types │ │ │ ├── TokenGrant.ts │ │ │ ├── TokenRequest.ts │ │ │ ├── TokenResponse.ts │ │ │ └── index.ts │ │ ├── embedding │ │ ├── index.ts │ │ └── types │ │ │ ├── Embedding.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ ├── tts │ │ ├── index.ts │ │ └── types │ │ │ ├── CancelContextRequest.ts │ │ │ ├── ContextId.ts │ │ │ ├── Controls.ts │ │ │ ├── Emotion.ts │ │ │ ├── FlushId.ts │ │ │ ├── GenerationRequest.ts │ │ │ ├── ModelSpeed.ts │ │ │ ├── Mp3OutputFormat.ts │ │ │ ├── NaturalSpecifier.ts │ │ │ ├── NumericalSpecifier.ts │ │ │ ├── OutputFormat.ts │ │ │ ├── PhonemeTimestamps.ts │ │ │ ├── RawEncoding.ts │ │ │ ├── RawOutputFormat.ts │ │ │ ├── Speed.ts │ │ │ ├── SupportedLanguage.ts │ │ │ ├── TtsRequest.ts │ │ │ ├── TtsRequestEmbeddingSpecifier.ts │ │ │ ├── TtsRequestIdSpecifier.ts │ │ │ ├── TtsRequestVoiceSpecifier.ts │ │ │ ├── WavOutputFormat.ts │ │ │ ├── WebSocketBaseResponse.ts │ │ │ ├── WebSocketChunkResponse.ts │ │ │ ├── WebSocketDoneResponse.ts │ │ │ ├── WebSocketErrorResponse.ts │ │ │ ├── WebSocketFlushDoneResponse.ts │ │ │ ├── WebSocketPhonemeTimestampsResponse.ts │ │ │ ├── WebSocketRawOutputFormat.ts │ │ │ ├── WebSocketRequest.ts │ │ │ ├── WebSocketResponse.ts │ │ │ ├── WebSocketStreamOptions.ts │ │ │ ├── WebSocketTimestampsResponse.ts │ │ │ ├── WebSocketTtsOutput.ts │ │ │ ├── WebSocketTtsRequest.ts │ │ │ ├── WordTimestamps.ts │ │ │ └── index.ts │ │ ├── voiceChanger │ │ ├── index.ts │ │ └── types │ │ │ ├── OutputFormatContainer.ts │ │ │ ├── StreamingResponse.ts │ │ │ └── index.ts │ │ └── voices │ │ ├── client │ │ ├── index.ts │ │ └── list.ts │ │ ├── index.ts │ │ └── types │ │ ├── BaseVoiceId.ts │ │ ├── CloneMode.ts │ │ ├── CreateVoiceRequest.ts │ │ ├── EmbeddingResponse.ts │ │ ├── EmbeddingSpecifier.ts │ │ ├── Gender.ts │ │ ├── IdSpecifier.ts │ │ ├── LocalizeDialect.ts │ │ ├── LocalizeEnglishDialect.ts │ │ ├── LocalizeFrenchDialect.ts │ │ ├── LocalizePortugueseDialect.ts │ │ ├── LocalizeSpanishDialect.ts │ │ ├── LocalizeTargetLanguage.ts │ │ ├── LocalizeVoiceRequest.ts │ │ ├── MixVoiceSpecifier.ts │ │ ├── MixVoicesRequest.ts │ │ ├── UpdateVoiceRequest.ts │ │ ├── Voice.ts │ │ ├── VoiceId.ts │ │ ├── VoiceMetadata.ts │ │ ├── Weight.ts │ │ └── index.ts ├── version.ts └── wrapper │ ├── Client.ts │ ├── StreamingTTSClient.ts │ ├── WebPlayer.ts │ ├── Websocket.ts │ ├── source.ts │ └── utils.ts ├── tests ├── custom.test.ts └── unit │ ├── fetcher │ ├── Fetcher.test.ts │ ├── createRequestUrl.test.ts │ ├── getFetchFn.test.ts │ ├── getRequestBody.test.ts │ ├── getResponseBody.test.ts │ ├── makeRequest.test.ts │ ├── requestWithRetries.test.ts │ ├── signals.test.ts │ ├── stream-wrappers │ │ ├── Node18UniversalStreamWrapper.test.ts │ │ ├── NodePre18StreamWrapper.test.ts │ │ ├── UndiciStreamWrapper.test.ts │ │ ├── chooseStreamWrapper.test.ts │ │ └── webpack.test.ts │ └── test-file.txt │ ├── form-data-utils │ └── formDataWrapper.test.ts │ └── zurg │ ├── bigint │ └── bigint.test.ts │ ├── date │ └── date.test.ts │ ├── enum │ └── enum.test.ts │ ├── lazy │ ├── lazy.test.ts │ ├── lazyObject.test.ts │ └── recursive │ │ ├── a.ts │ │ └── b.ts │ ├── list │ └── list.test.ts │ ├── literals │ └── stringLiteral.test.ts │ ├── object-like │ └── withParsedProperties.test.ts │ ├── object │ ├── extend.test.ts │ ├── object.test.ts │ ├── objectWithoutOptionalProperties.test.ts │ └── passthrough.test.ts │ ├── primitives │ ├── any.test.ts │ ├── boolean.test.ts │ ├── number.test.ts │ ├── string.test.ts │ └── unknown.test.ts │ ├── record │ └── record.test.ts │ ├── schema-utils │ └── getSchemaUtils.test.ts │ ├── schema.test.ts │ ├── set │ └── set.test.ts │ ├── skipValidation.test.ts │ ├── undiscriminated-union │ └── undiscriminatedUnion.test.ts │ ├── union │ └── union.test.ts │ └── utils │ ├── itSchema.ts │ └── itValidate.ts ├── tsconfig.json └── yarn.lock /.fernignore: -------------------------------------------------------------------------------- 1 | # Specify files that shouldn't be modified by Fern 2 | 3 | README.md 4 | 5 | src/wrapper 6 | src/index.ts 7 | 8 | src/core/websocket 9 | src/serialization/resources/tts/types/OutputFormat.ts 10 | 11 | # arraybuffer 12 | src/api/resources/tts/client/Client.ts 13 | src/api/resources/voiceChanger/client/Client.ts 14 | src/core/fetcher/Fetcher.ts 15 | src/core/fetcher/getResponseBody.ts 16 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: [push] 4 | 5 | jobs: 6 | compile: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - name: Checkout repo 11 | uses: actions/checkout@v3 12 | 13 | - name: Set up node 14 | uses: actions/setup-node@v3 15 | 16 | - name: Compile 17 | run: yarn && yarn build 18 | 19 | test: 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - name: Checkout repo 24 | uses: actions/checkout@v3 25 | 26 | - name: Set up node 27 | uses: actions/setup-node@v3 28 | 29 | - name: Compile 30 | run: yarn && yarn test 31 | 32 | publish: 33 | needs: [ compile, test ] 34 | if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') 35 | runs-on: ubuntu-latest 36 | steps: 37 | - name: Checkout repo 38 | uses: actions/checkout@v3 39 | - name: Set up node 40 | uses: actions/setup-node@v3 41 | - name: Install dependencies 42 | run: yarn install 43 | - name: Build 44 | run: yarn build 45 | 46 | - name: Publish to npm 47 | run: | 48 | npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN} 49 | if [[ ${GITHUB_REF} == *alpha* ]]; then 50 | npm publish --access public --tag alpha 51 | elif [[ ${GITHUB_REF} == *beta* ]]; then 52 | npm publish --access public --tag beta 53 | else 54 | npm publish --access public 55 | fi 56 | env: 57 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | /dist -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | src 3 | tests 4 | .gitignore 5 | .github 6 | .fernignore 7 | .prettierrc.yml 8 | tsconfig.json 9 | yarn.lock -------------------------------------------------------------------------------- /.prettierrc.yml: -------------------------------------------------------------------------------- 1 | tabWidth: 4 2 | printWidth: 120 3 | -------------------------------------------------------------------------------- /jest.config.mjs: -------------------------------------------------------------------------------- 1 | /** @type {import('jest').Config} */ 2 | export default { 3 | preset: "ts-jest", 4 | testEnvironment: "node", 5 | moduleNameMapper: { 6 | "(.+)\.js$": "$1", 7 | }, 8 | }; 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@cartesia/cartesia-js", 3 | "version": "2.2.3", 4 | "private": false, 5 | "repository": "https://github.com/cartesia-ai/cartesia-js", 6 | "main": "./index.js", 7 | "types": "./index.d.ts", 8 | "scripts": { 9 | "format": "prettier . --write --ignore-unknown", 10 | "build": "tsc", 11 | "prepack": "cp -rv dist/. .", 12 | "test": "jest" 13 | }, 14 | "dependencies": { 15 | "url-join": "4.0.1", 16 | "form-data": "^4.0.0", 17 | "formdata-node": "^6.0.3", 18 | "node-fetch": "^2.7.0", 19 | "qs": "^6.13.1", 20 | "readable-stream": "^4.5.2", 21 | "form-data-encoder": "^4.0.2", 22 | "emittery": "^0.13.1", 23 | "human-id": "^4.1.1", 24 | "ws": "^8.15.13" 25 | }, 26 | "devDependencies": { 27 | "@types/url-join": "4.0.1", 28 | "@types/qs": "^6.9.17", 29 | "@types/node-fetch": "^2.6.12", 30 | "@types/readable-stream": "^4.0.18", 31 | "webpack": "^5.97.1", 32 | "ts-loader": "^9.5.1", 33 | "jest": "^29.7.0", 34 | "@types/jest": "^29.5.14", 35 | "ts-jest": "^29.1.1", 36 | "jest-environment-jsdom": "^29.7.0", 37 | "@types/node": "^18.19.70", 38 | "prettier": "^3.4.2", 39 | "typescript": "~5.7.2", 40 | "@types/ws": "^8.5.13" 41 | }, 42 | "browser": { 43 | "fs": false, 44 | "os": false, 45 | "path": false 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/api/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./resources"; 2 | -------------------------------------------------------------------------------- /src/api/resources/apiStatus/client/index.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /src/api/resources/apiStatus/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | export * from "./client"; 3 | -------------------------------------------------------------------------------- /src/api/resources/apiStatus/types/ApiInfo.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface ApiInfo { 6 | ok: boolean; 7 | version: string; 8 | } 9 | -------------------------------------------------------------------------------- /src/api/resources/apiStatus/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./ApiInfo"; 2 | -------------------------------------------------------------------------------- /src/api/resources/auth/client/index.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /src/api/resources/auth/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | export * from "./client"; 3 | -------------------------------------------------------------------------------- /src/api/resources/auth/types/TokenGrant.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface TokenGrant { 6 | /** The `tts` grant allows the token to be used to access any TTS endpoint. */ 7 | tts: boolean; 8 | } 9 | -------------------------------------------------------------------------------- /src/api/resources/auth/types/TokenRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface TokenRequest { 8 | /** The permissions to be granted via the token. */ 9 | grants: Cartesia.TokenGrant; 10 | /** The number of seconds the token will be valid for since the time of generation. The maximum is 1 hour (3600 seconds). */ 11 | expiresIn?: number; 12 | } 13 | -------------------------------------------------------------------------------- /src/api/resources/auth/types/TokenResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface TokenResponse { 6 | /** The generated Access Token. */ 7 | token: string; 8 | } 9 | -------------------------------------------------------------------------------- /src/api/resources/auth/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./TokenGrant"; 2 | export * from "./TokenRequest"; 3 | export * from "./TokenResponse"; 4 | -------------------------------------------------------------------------------- /src/api/resources/embedding/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | -------------------------------------------------------------------------------- /src/api/resources/embedding/types/Embedding.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * A 192-dimensional vector (i.e. a list of 192 numbers) that represents the voice. 7 | * 8 | * @example 9 | * [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 10 | */ 11 | export type Embedding = number[]; 12 | -------------------------------------------------------------------------------- /src/api/resources/embedding/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./Embedding"; 2 | -------------------------------------------------------------------------------- /src/api/resources/index.ts: -------------------------------------------------------------------------------- 1 | export * as apiStatus from "./apiStatus"; 2 | export * from "./apiStatus/types"; 3 | export * as auth from "./auth"; 4 | export * from "./auth/types"; 5 | export * as embedding from "./embedding"; 6 | export * from "./embedding/types"; 7 | export * as tts from "./tts"; 8 | export * from "./tts/types"; 9 | export * as voiceChanger from "./voiceChanger"; 10 | export * from "./voiceChanger/types"; 11 | export * as voices from "./voices"; 12 | export * from "./voices/types"; 13 | export * as infill from "./infill"; 14 | export * from "./infill/client/requests"; 15 | export * from "./voiceChanger/client/requests"; 16 | export * from "./voices/client/requests"; 17 | -------------------------------------------------------------------------------- /src/api/resources/infill/client/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./requests"; 2 | -------------------------------------------------------------------------------- /src/api/resources/infill/client/requests/index.ts: -------------------------------------------------------------------------------- 1 | export { type InfillBytesRequest } from "./InfillBytesRequest"; 2 | -------------------------------------------------------------------------------- /src/api/resources/infill/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./client"; 2 | -------------------------------------------------------------------------------- /src/api/resources/tts/client/index.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /src/api/resources/tts/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | export * from "./client"; 3 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/CancelContextRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface CancelContextRequest { 8 | /** The ID of the context to cancel. */ 9 | contextId: Cartesia.ContextId; 10 | /** Whether to cancel the context, so that no more messages are generated for that context. */ 11 | cancel: true; 12 | } 13 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/ContextId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * A unique identifier for the context. You can use any unique identifier, like a UUID or human ID. 7 | * 8 | * Some customers use unique identifiers from their own systems (such as conversation IDs) as context IDs. 9 | */ 10 | export type ContextId = string; 11 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/Controls.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface Controls { 8 | speed: Cartesia.Speed; 9 | emotion: Cartesia.Emotion[]; 10 | } 11 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/Emotion.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * An array of emotion:level tags. 7 | * 8 | * Supported emotions are: anger, positivity, surprise, sadness, and curiosity. 9 | * 10 | * Supported levels are: lowest, low, (omit), high, highest. 11 | */ 12 | export type Emotion = 13 | | "anger:lowest" 14 | | "anger:low" 15 | | "anger" 16 | | "anger:high" 17 | | "anger:highest" 18 | | "positivity:lowest" 19 | | "positivity:low" 20 | | "positivity" 21 | | "positivity:high" 22 | | "positivity:highest" 23 | | "surprise:lowest" 24 | | "surprise:low" 25 | | "surprise" 26 | | "surprise:high" 27 | | "surprise:highest" 28 | | "sadness:lowest" 29 | | "sadness:low" 30 | | "sadness" 31 | | "sadness:high" 32 | | "sadness:highest" 33 | | "curiosity:lowest" 34 | | "curiosity:low" 35 | | "curiosity" 36 | | "curiosity:high" 37 | | "curiosity:highest"; 38 | export const Emotion = { 39 | AngerLowest: "anger:lowest", 40 | AngerLow: "anger:low", 41 | Anger: "anger", 42 | AngerHigh: "anger:high", 43 | AngerHighest: "anger:highest", 44 | PositivityLowest: "positivity:lowest", 45 | PositivityLow: "positivity:low", 46 | Positivity: "positivity", 47 | PositivityHigh: "positivity:high", 48 | PositivityHighest: "positivity:highest", 49 | SurpriseLowest: "surprise:lowest", 50 | SurpriseLow: "surprise:low", 51 | Surprise: "surprise", 52 | SurpriseHigh: "surprise:high", 53 | SurpriseHighest: "surprise:highest", 54 | SadnessLowest: "sadness:lowest", 55 | SadnessLow: "sadness:low", 56 | Sadness: "sadness", 57 | SadnessHigh: "sadness:high", 58 | SadnessHighest: "sadness:highest", 59 | CuriosityLowest: "curiosity:lowest", 60 | CuriosityLow: "curiosity:low", 61 | Curiosity: "curiosity", 62 | CuriosityHigh: "curiosity:high", 63 | CuriosityHighest: "curiosity:highest", 64 | } as const; 65 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/FlushId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * An identifier corresponding to the number of flush commands that have been sent for this context. Starts at 1. 7 | * 8 | * This can be used to map chunks of audio to certain transcript submissions. 9 | */ 10 | export type FlushId = number; 11 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/GenerationRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface GenerationRequest { 8 | /** The ID of the model to use for the generation. See [Models](/build-with-cartesia/models) for available models. */ 9 | modelId: string; 10 | /** The transcript to generate speech for. This can be a string or an iterator over strings. */ 11 | transcript?: unknown; 12 | voice: Cartesia.TtsRequestVoiceSpecifier; 13 | language?: Cartesia.SupportedLanguage; 14 | outputFormat: Cartesia.WebSocketRawOutputFormat; 15 | /** 16 | * The maximum duration of the audio in seconds. You do not usually need to specify this. 17 | * If the duration is not appropriate for the length of the transcript, the output audio may be truncated. 18 | */ 19 | duration?: number; 20 | speed?: Cartesia.ModelSpeed; 21 | contextId?: Cartesia.ContextId; 22 | /** 23 | * Whether this input may be followed by more inputs. 24 | * If not specified, this defaults to `false`. 25 | */ 26 | continue?: boolean; 27 | /** 28 | * The maximum time in milliseconds to buffer text before starting generation. Values between [0, 1000]ms are supported. Defaults to 0 (no buffering). 29 | * 30 | * When set, the model will buffer incoming text chunks until it's confident it has enough context to generate high-quality speech, or the buffer delay elapses, whichever comes first. Without this option set, the model will kick off generations immediately, ceding control of buffering to the user. 31 | * 32 | * Use this to balance responsiveness with higher quality speech generation, which often benefits from having more context. 33 | */ 34 | maxBufferDelayMs?: number; 35 | /** Whether to flush the context. */ 36 | flush?: boolean; 37 | /** Whether to return word-level timestamps. */ 38 | addTimestamps?: boolean; 39 | /** Whether to return phoneme-level timestamps. */ 40 | addPhonemeTimestamps?: boolean; 41 | /** Whether to use the original transcript for timestamps. */ 42 | useOriginalTimestamps?: boolean; 43 | } 44 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/ModelSpeed.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * > This feature is experimental and may not work for all voices. 7 | * 8 | * Speed setting for the model. Defaults to `normal`. 9 | * 10 | * Influences the speed of the generated speech. Faster speeds may reduce hallucination rate. 11 | */ 12 | export type ModelSpeed = "slow" | "normal" | "fast"; 13 | export const ModelSpeed = { 14 | Slow: "slow", 15 | Normal: "normal", 16 | Fast: "fast", 17 | } as const; 18 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/Mp3OutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface Mp3OutputFormat { 6 | sampleRate: number; 7 | /** The bit rate of the audio in bits per second. Supported bit rates are 32000, 64000, 96000, 128000, 192000. */ 8 | bitRate: number; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/NaturalSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type NaturalSpecifier = "slowest" | "slow" | "normal" | "fast" | "fastest"; 6 | export const NaturalSpecifier = { 7 | Slowest: "slowest", 8 | Slow: "slow", 9 | Normal: "normal", 10 | Fast: "fast", 11 | Fastest: "fastest", 12 | } as const; 13 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/NumericalSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type NumericalSpecifier = number; 6 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/OutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export type OutputFormat = Cartesia.OutputFormat.Raw | Cartesia.OutputFormat.Wav | Cartesia.OutputFormat.Mp3; 8 | 9 | export namespace OutputFormat { 10 | export interface Raw extends Cartesia.RawOutputFormat { 11 | container: "raw"; 12 | } 13 | 14 | export interface Wav extends Cartesia.WavOutputFormat { 15 | container: "wav"; 16 | } 17 | 18 | export interface Mp3 extends Cartesia.Mp3OutputFormat { 19 | container: "mp3"; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/PhonemeTimestamps.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface PhonemeTimestamps { 6 | phonemes: string[]; 7 | start: number[]; 8 | end: number[]; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/RawEncoding.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type RawEncoding = "pcm_f32le" | "pcm_s16le" | "pcm_mulaw" | "pcm_alaw"; 6 | export const RawEncoding = { 7 | PcmF32Le: "pcm_f32le", 8 | PcmS16Le: "pcm_s16le", 9 | PcmMulaw: "pcm_mulaw", 10 | PcmAlaw: "pcm_alaw", 11 | } as const; 12 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/RawOutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface RawOutputFormat { 8 | encoding: Cartesia.RawEncoding; 9 | sampleRate: number; 10 | bitRate?: number; 11 | } 12 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/Speed.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | /** 8 | * Either a number between -1.0 and 1.0 or a natural language description of speed. 9 | * 10 | * If you specify a number, 0.0 is the default speed, -1.0 is the slowest speed, and 1.0 is the fastest speed. 11 | */ 12 | export type Speed = Cartesia.NumericalSpecifier | Cartesia.NaturalSpecifier; 13 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/SupportedLanguage.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * The language that the given voice should speak the transcript in. 7 | * 8 | * Options: English (en), French (fr), German (de), Spanish (es), Portuguese (pt), Chinese (zh), Japanese (ja), Hindi (hi), Italian (it), Korean (ko), Dutch (nl), Polish (pl), Russian (ru), Swedish (sv), Turkish (tr). 9 | */ 10 | export type SupportedLanguage = 11 | | "en" 12 | | "fr" 13 | | "de" 14 | | "es" 15 | | "pt" 16 | | "zh" 17 | | "ja" 18 | | "hi" 19 | | "it" 20 | | "ko" 21 | | "nl" 22 | | "pl" 23 | | "ru" 24 | | "sv" 25 | | "tr"; 26 | export const SupportedLanguage = { 27 | En: "en", 28 | Fr: "fr", 29 | De: "de", 30 | Es: "es", 31 | Pt: "pt", 32 | Zh: "zh", 33 | Ja: "ja", 34 | Hi: "hi", 35 | It: "it", 36 | Ko: "ko", 37 | Nl: "nl", 38 | Pl: "pl", 39 | Ru: "ru", 40 | Sv: "sv", 41 | Tr: "tr", 42 | } as const; 43 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/TtsRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface TtsRequest { 8 | /** The ID of the model to use for the generation. See [Models](/build-with-cartesia/models) for available models. */ 9 | modelId: string; 10 | transcript: string; 11 | voice: Cartesia.TtsRequestVoiceSpecifier; 12 | language?: Cartesia.SupportedLanguage; 13 | outputFormat: Cartesia.OutputFormat; 14 | /** 15 | * The maximum duration of the audio in seconds. You do not usually need to specify this. 16 | * If the duration is not appropriate for the length of the transcript, the output audio may be truncated. 17 | */ 18 | duration?: number; 19 | speed?: Cartesia.ModelSpeed; 20 | } 21 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/TtsRequestEmbeddingSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface TtsRequestEmbeddingSpecifier { 8 | mode: "embedding"; 9 | embedding: Cartesia.Embedding; 10 | experimentalControls?: Cartesia.Controls; 11 | } 12 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/TtsRequestIdSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface TtsRequestIdSpecifier { 8 | mode: "id"; 9 | id: Cartesia.VoiceId; 10 | experimentalControls?: Cartesia.Controls; 11 | } 12 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/TtsRequestVoiceSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export type TtsRequestVoiceSpecifier = Cartesia.TtsRequestIdSpecifier | Cartesia.TtsRequestEmbeddingSpecifier; 8 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WavOutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WavOutputFormat extends Cartesia.RawOutputFormat {} 8 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketBaseResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketBaseResponse { 8 | contextId?: Cartesia.ContextId; 9 | statusCode: number; 10 | done: boolean; 11 | } 12 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketChunkResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketChunkResponse extends Cartesia.WebSocketBaseResponse { 8 | data: string; 9 | stepTime: number; 10 | } 11 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketDoneResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketDoneResponse extends Cartesia.WebSocketBaseResponse {} 8 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketErrorResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketErrorResponse extends Cartesia.WebSocketBaseResponse { 8 | error: string; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketFlushDoneResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketFlushDoneResponse extends Cartesia.WebSocketBaseResponse { 8 | flushId: Cartesia.FlushId; 9 | flushDone: boolean; 10 | } 11 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketPhonemeTimestampsResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketPhonemeTimestampsResponse extends Cartesia.WebSocketBaseResponse { 8 | phonemeTimestamps?: Cartesia.PhonemeTimestamps; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketRawOutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketRawOutputFormat { 8 | container: "raw"; 9 | encoding: Cartesia.RawEncoding; 10 | sampleRate: number; 11 | } 12 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export type WebSocketRequest = 8 | /** 9 | * Use this to generate speech for a transcript. 10 | * */ 11 | | Cartesia.GenerationRequest 12 | /** 13 | * Use this to cancel a context, so that no more messages are generated for that context. 14 | * */ 15 | | Cartesia.CancelContextRequest; 16 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export type WebSocketResponse = 8 | | Cartesia.WebSocketResponse.Chunk 9 | | Cartesia.WebSocketResponse.FlushDone 10 | | Cartesia.WebSocketResponse.Done 11 | | Cartesia.WebSocketResponse.Timestamps 12 | | Cartesia.WebSocketResponse.Error_ 13 | | Cartesia.WebSocketResponse.PhonemeTimestamps; 14 | 15 | export namespace WebSocketResponse { 16 | export interface Chunk extends Cartesia.WebSocketChunkResponse { 17 | type: "chunk"; 18 | } 19 | 20 | export interface FlushDone extends Cartesia.WebSocketFlushDoneResponse { 21 | type: "flush_done"; 22 | } 23 | 24 | export interface Done extends Cartesia.WebSocketDoneResponse { 25 | type: "done"; 26 | } 27 | 28 | export interface Timestamps extends Cartesia.WebSocketTimestampsResponse { 29 | type: "timestamps"; 30 | } 31 | 32 | export interface Error_ extends Cartesia.WebSocketErrorResponse { 33 | type: "error"; 34 | } 35 | 36 | export interface PhonemeTimestamps extends Cartesia.WebSocketPhonemeTimestampsResponse { 37 | type: "phoneme_timestamps"; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketStreamOptions.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface WebSocketStreamOptions { 6 | timeout?: number; 7 | } 8 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketTimestampsResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketTimestampsResponse extends Cartesia.WebSocketBaseResponse { 8 | wordTimestamps?: Cartesia.WordTimestamps; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketTtsOutput.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketTtsOutput { 8 | wordTimestamps?: Cartesia.WordTimestamps; 9 | phonemeTimestamps?: Cartesia.PhonemeTimestamps; 10 | audio?: unknown; 11 | contextId?: Cartesia.ContextId; 12 | flushId?: Cartesia.FlushId; 13 | flushDone?: boolean; 14 | } 15 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WebSocketTtsRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface WebSocketTtsRequest { 8 | /** The ID of the model to use for the generation. See [Models](/build-with-cartesia/models) for available models. */ 9 | modelId: string; 10 | outputFormat?: Cartesia.OutputFormat; 11 | transcript?: string; 12 | voice: Cartesia.TtsRequestVoiceSpecifier; 13 | duration?: number; 14 | language?: string; 15 | addTimestamps?: boolean; 16 | addPhonemeTimestamps?: boolean; 17 | useOriginalTimestamps?: boolean; 18 | continue?: boolean; 19 | contextId?: string; 20 | maxBufferDelayMs?: number; 21 | speed?: Cartesia.ModelSpeed; 22 | } 23 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/WordTimestamps.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface WordTimestamps { 6 | words: string[]; 7 | start: number[]; 8 | end: number[]; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/tts/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./ContextId"; 2 | export * from "./FlushId"; 3 | export * from "./ModelSpeed"; 4 | export * from "./WebSocketBaseResponse"; 5 | export * from "./WebSocketResponse"; 6 | export * from "./WebSocketErrorResponse"; 7 | export * from "./WebSocketChunkResponse"; 8 | export * from "./WebSocketTimestampsResponse"; 9 | export * from "./WebSocketPhonemeTimestampsResponse"; 10 | export * from "./WebSocketTtsOutput"; 11 | export * from "./WebSocketStreamOptions"; 12 | export * from "./WordTimestamps"; 13 | export * from "./PhonemeTimestamps"; 14 | export * from "./WebSocketDoneResponse"; 15 | export * from "./WebSocketFlushDoneResponse"; 16 | export * from "./CancelContextRequest"; 17 | export * from "./GenerationRequest"; 18 | export * from "./WebSocketRawOutputFormat"; 19 | export * from "./WebSocketRequest"; 20 | export * from "./WebSocketTtsRequest"; 21 | export * from "./TtsRequest"; 22 | export * from "./SupportedLanguage"; 23 | export * from "./OutputFormat"; 24 | export * from "./RawOutputFormat"; 25 | export * from "./RawEncoding"; 26 | export * from "./WavOutputFormat"; 27 | export * from "./Mp3OutputFormat"; 28 | export * from "./TtsRequestVoiceSpecifier"; 29 | export * from "./TtsRequestIdSpecifier"; 30 | export * from "./TtsRequestEmbeddingSpecifier"; 31 | export * from "./Controls"; 32 | export * from "./Speed"; 33 | export * from "./NumericalSpecifier"; 34 | export * from "./NaturalSpecifier"; 35 | export * from "./Emotion"; 36 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/client/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./requests"; 2 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/client/requests/VoiceChangerBytesRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../../index"; 6 | 7 | /** 8 | * @example 9 | * { 10 | * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", 11 | * outputFormatContainer: "mp3", 12 | * outputFormatSampleRate: 44100, 13 | * outputFormatBitRate: 128000 14 | * } 15 | * 16 | * @example 17 | * { 18 | * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", 19 | * outputFormatContainer: "wav", 20 | * outputFormatSampleRate: 44100, 21 | * outputFormatEncoding: "pcm_f32le" 22 | * } 23 | * 24 | * @example 25 | * { 26 | * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", 27 | * outputFormatContainer: "raw", 28 | * outputFormatSampleRate: 44100, 29 | * outputFormatEncoding: "pcm_f32le" 30 | * } 31 | */ 32 | export interface VoiceChangerBytesRequest { 33 | voiceId: string; 34 | outputFormatContainer: Cartesia.OutputFormatContainer; 35 | outputFormatSampleRate: number; 36 | /** 37 | * Required for `raw` and `wav` containers. 38 | * 39 | */ 40 | outputFormatEncoding?: Cartesia.RawEncoding; 41 | /** 42 | * Required for `mp3` containers. 43 | * 44 | */ 45 | outputFormatBitRate?: number; 46 | } 47 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/client/requests/VoiceChangerSseRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../../index"; 6 | 7 | /** 8 | * @example 9 | * { 10 | * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", 11 | * outputFormatContainer: "mp3", 12 | * outputFormatSampleRate: 44100, 13 | * outputFormatBitRate: 128000 14 | * } 15 | * 16 | * @example 17 | * { 18 | * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", 19 | * outputFormatContainer: "wav", 20 | * outputFormatSampleRate: 44100, 21 | * outputFormatEncoding: "pcm_f32le" 22 | * } 23 | * 24 | * @example 25 | * { 26 | * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", 27 | * outputFormatContainer: "raw", 28 | * outputFormatSampleRate: 44100, 29 | * outputFormatEncoding: "pcm_f32le" 30 | * } 31 | */ 32 | export interface VoiceChangerSseRequest { 33 | voiceId: string; 34 | outputFormatContainer: Cartesia.OutputFormatContainer; 35 | outputFormatSampleRate: number; 36 | /** 37 | * Required for `raw` and `wav` containers. 38 | * 39 | */ 40 | outputFormatEncoding?: Cartesia.RawEncoding; 41 | /** 42 | * Required for `mp3` containers. 43 | * 44 | */ 45 | outputFormatBitRate?: number; 46 | } 47 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/client/requests/index.ts: -------------------------------------------------------------------------------- 1 | export { type VoiceChangerBytesRequest } from "./VoiceChangerBytesRequest"; 2 | export { type VoiceChangerSseRequest } from "./VoiceChangerSseRequest"; 3 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | export * from "./client"; 3 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/types/OutputFormatContainer.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type OutputFormatContainer = "raw" | "wav" | "mp3"; 6 | export const OutputFormatContainer = { 7 | Raw: "raw", 8 | Wav: "wav", 9 | Mp3: "mp3", 10 | } as const; 11 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/types/StreamingResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export type StreamingResponse = 8 | | Cartesia.StreamingResponse.Chunk 9 | | Cartesia.StreamingResponse.Done 10 | | Cartesia.StreamingResponse.Error_; 11 | 12 | export namespace StreamingResponse { 13 | export interface Chunk extends Cartesia.WebSocketChunkResponse { 14 | type: "chunk"; 15 | } 16 | 17 | export interface Done extends Cartesia.WebSocketDoneResponse { 18 | type: "done"; 19 | } 20 | 21 | export interface Error_ extends Cartesia.WebSocketErrorResponse { 22 | type: "error"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/api/resources/voiceChanger/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./OutputFormatContainer"; 2 | export * from "./StreamingResponse"; 3 | -------------------------------------------------------------------------------- /src/api/resources/voices/client/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./requests"; 2 | -------------------------------------------------------------------------------- /src/api/resources/voices/client/requests/CloneVoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../../index"; 6 | 7 | /** 8 | * @example 9 | * { 10 | * name: "A high-stability cloned voice", 11 | * description: "Copied from Cartesia docs", 12 | * mode: "stability", 13 | * language: "en" 14 | * } 15 | * 16 | * @example 17 | * { 18 | * name: "A high-similarity cloned voice", 19 | * description: "Copied from Cartesia docs", 20 | * mode: "similarity", 21 | * language: "en" 22 | * } 23 | */ 24 | export interface CloneVoiceRequest { 25 | /** 26 | * The name of the voice. 27 | * 28 | */ 29 | name: string; 30 | /** 31 | * A description for the voice. 32 | * 33 | */ 34 | description?: string; 35 | /** 36 | * The language of the voice. 37 | * 38 | */ 39 | language: Cartesia.SupportedLanguage; 40 | /** 41 | * Tradeoff between similarity and stability. Similarity clones sound more like the source clip, but may reproduce background noise. Stability clones always sound like a studio recording, but may not sound as similar to the source clip. 42 | * 43 | */ 44 | mode: Cartesia.CloneMode; 45 | /** 46 | * Whether to apply AI enhancements to the clip to reduce background noise. This leads to cleaner generated speech at the cost of reduced similarity to the source clip. 47 | * 48 | */ 49 | enhance?: boolean; 50 | /** 51 | * Optional base voice ID that the cloned voice is derived from. 52 | * 53 | */ 54 | baseVoiceId?: Cartesia.VoiceId; 55 | } 56 | -------------------------------------------------------------------------------- /src/api/resources/voices/client/requests/index.ts: -------------------------------------------------------------------------------- 1 | export { type CloneVoiceRequest } from "./CloneVoiceRequest"; 2 | -------------------------------------------------------------------------------- /src/api/resources/voices/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | export * from "./client"; 3 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/BaseVoiceId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | /** 8 | * Pull in features from a base voice, used for features like voice mixing. 9 | */ 10 | export type BaseVoiceId = Cartesia.VoiceId; 11 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/CloneMode.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type CloneMode = "similarity" | "stability"; 6 | export const CloneMode = { 7 | Similarity: "similarity", 8 | Stability: "stability", 9 | } as const; 10 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/CreateVoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface CreateVoiceRequest { 8 | /** The name of the voice. */ 9 | name: string; 10 | /** The description of the voice. */ 11 | description: string; 12 | embedding: Cartesia.Embedding; 13 | language?: Cartesia.SupportedLanguage; 14 | baseVoiceId?: Cartesia.BaseVoiceId; 15 | } 16 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/EmbeddingResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface EmbeddingResponse { 8 | embedding: Cartesia.Embedding; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/EmbeddingSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface EmbeddingSpecifier { 8 | embedding: Cartesia.Embedding; 9 | weight: Cartesia.Weight; 10 | } 11 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/Gender.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type Gender = "male" | "female"; 6 | export const Gender = { 7 | Male: "male", 8 | Female: "female", 9 | } as const; 10 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/IdSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface IdSpecifier { 8 | id: Cartesia.VoiceId; 9 | weight: Cartesia.Weight; 10 | } 11 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/LocalizeDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | /** 8 | * The dialect to localize to. Only supported for English (`en`), Spanish (`es`), Portuguese (`pt`), and French (`fr`). 9 | */ 10 | export type LocalizeDialect = 11 | /** 12 | * Only available when language is set to English (`en`). Options: Australian (`au`), Indian (`in`), Southern (`so`), British (`uk`), or American (`us`). 13 | * */ 14 | | Cartesia.LocalizeEnglishDialect 15 | /** 16 | * Only available when language is set to Spanish (`es`). Options: Latin American (`mx`) and Peninsular (`pe`). 17 | * */ 18 | | Cartesia.LocalizeSpanishDialect 19 | /** 20 | * Only available when language is set to Portuguese (`pt`). Options: Brazilian (`br`) and European Portuguese (`eu`). 21 | * */ 22 | | Cartesia.LocalizePortugueseDialect 23 | /** 24 | * Only available when language is set to French (`fr`). Options: Standard Parisian/Metropolitan (`eu`) and Canadian (`ca`). 25 | * */ 26 | | Cartesia.LocalizeFrenchDialect; 27 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/LocalizeEnglishDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type LocalizeEnglishDialect = "au" | "in" | "so" | "uk" | "us"; 6 | export const LocalizeEnglishDialect = { 7 | Au: "au", 8 | In: "in", 9 | So: "so", 10 | Uk: "uk", 11 | Us: "us", 12 | } as const; 13 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/LocalizeFrenchDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type LocalizeFrenchDialect = "eu" | "ca"; 6 | export const LocalizeFrenchDialect = { 7 | Eu: "eu", 8 | Ca: "ca", 9 | } as const; 10 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/LocalizePortugueseDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type LocalizePortugueseDialect = "br" | "eu"; 6 | export const LocalizePortugueseDialect = { 7 | Br: "br", 8 | Eu: "eu", 9 | } as const; 10 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/LocalizeSpanishDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export type LocalizeSpanishDialect = "mx" | "pe"; 6 | export const LocalizeSpanishDialect = { 7 | Mx: "mx", 8 | Pe: "pe", 9 | } as const; 10 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/LocalizeTargetLanguage.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * Target language to localize the voice to. 7 | * 8 | * Options: English (en), German (de), Spanish (es), French (fr), Japanese (ja), Portuguese (pt), Chinese (zh), Hindi (hi), Italian (it), Korean (ko), Dutch (nl), Polish (pl), Russian (ru), Swedish (sv), Turkish (tr). 9 | */ 10 | export type LocalizeTargetLanguage = 11 | | "en" 12 | | "de" 13 | | "es" 14 | | "fr" 15 | | "ja" 16 | | "pt" 17 | | "zh" 18 | | "hi" 19 | | "it" 20 | | "ko" 21 | | "nl" 22 | | "pl" 23 | | "ru" 24 | | "sv" 25 | | "tr"; 26 | export const LocalizeTargetLanguage = { 27 | En: "en", 28 | De: "de", 29 | Es: "es", 30 | Fr: "fr", 31 | Ja: "ja", 32 | Pt: "pt", 33 | Zh: "zh", 34 | Hi: "hi", 35 | It: "it", 36 | Ko: "ko", 37 | Nl: "nl", 38 | Pl: "pl", 39 | Ru: "ru", 40 | Sv: "sv", 41 | Tr: "tr", 42 | } as const; 43 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/LocalizeVoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface LocalizeVoiceRequest { 8 | /** The ID of the voice to localize. */ 9 | voiceId: string; 10 | /** The name of the new localized voice. */ 11 | name: string; 12 | /** The description of the new localized voice. */ 13 | description: string; 14 | language: Cartesia.LocalizeTargetLanguage; 15 | originalSpeakerGender: Cartesia.Gender; 16 | dialect?: Cartesia.LocalizeDialect; 17 | } 18 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/MixVoiceSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export type MixVoiceSpecifier = Cartesia.IdSpecifier | Cartesia.EmbeddingSpecifier; 8 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/MixVoicesRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface MixVoicesRequest { 8 | voices: Cartesia.MixVoiceSpecifier[]; 9 | } 10 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/UpdateVoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export interface UpdateVoiceRequest { 6 | /** The name of the voice. */ 7 | name: string; 8 | /** The description of the voice. */ 9 | description: string; 10 | } 11 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/Voice.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface Voice { 8 | id: Cartesia.VoiceId; 9 | /** The ID of the user who owns the voice. */ 10 | userId?: string; 11 | /** Whether the voice is publicly accessible. */ 12 | isPublic: boolean; 13 | /** The name of the voice. */ 14 | name: string; 15 | /** The description of the voice. */ 16 | description: string; 17 | /** The date and time the voice was created. */ 18 | createdAt: Date; 19 | embedding: Cartesia.Embedding; 20 | language: Cartesia.SupportedLanguage; 21 | } 22 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/VoiceId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * The ID of the voice. 7 | */ 8 | export type VoiceId = string; 9 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/VoiceMetadata.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as Cartesia from "../../../index"; 6 | 7 | export interface VoiceMetadata { 8 | id: Cartesia.VoiceId; 9 | /** The ID of the user who owns the voice. */ 10 | userId: string; 11 | /** Whether the voice is publicly accessible. */ 12 | isPublic: boolean; 13 | /** The name of the voice. */ 14 | name: string; 15 | /** The description of the voice. */ 16 | description: string; 17 | /** The date and time the voice was created. */ 18 | createdAt: Date; 19 | language: Cartesia.SupportedLanguage; 20 | } 21 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/Weight.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | /** 6 | * The weight of the voice or embedding in the mix. If weights do not sum to 1, they will be normalized. 7 | */ 8 | export type Weight = number; 9 | -------------------------------------------------------------------------------- /src/api/resources/voices/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./VoiceId"; 2 | export * from "./BaseVoiceId"; 3 | export * from "./Voice"; 4 | export * from "./VoiceMetadata"; 5 | export * from "./CreateVoiceRequest"; 6 | export * from "./UpdateVoiceRequest"; 7 | export * from "./LocalizeTargetLanguage"; 8 | export * from "./LocalizeEnglishDialect"; 9 | export * from "./LocalizeFrenchDialect"; 10 | export * from "./LocalizeSpanishDialect"; 11 | export * from "./LocalizePortugueseDialect"; 12 | export * from "./LocalizeDialect"; 13 | export * from "./Gender"; 14 | export * from "./LocalizeVoiceRequest"; 15 | export * from "./EmbeddingResponse"; 16 | export * from "./MixVoicesRequest"; 17 | export * from "./Weight"; 18 | export * from "./IdSpecifier"; 19 | export * from "./EmbeddingSpecifier"; 20 | export * from "./MixVoiceSpecifier"; 21 | export * from "./CloneMode"; 22 | -------------------------------------------------------------------------------- /src/core/fetcher/APIResponse.ts: -------------------------------------------------------------------------------- 1 | export type APIResponse = SuccessfulResponse | FailedResponse; 2 | 3 | export interface SuccessfulResponse { 4 | ok: true; 5 | body: T; 6 | headers?: Record; 7 | } 8 | 9 | export interface FailedResponse { 10 | ok: false; 11 | error: T; 12 | } 13 | -------------------------------------------------------------------------------- /src/core/fetcher/Supplier.ts: -------------------------------------------------------------------------------- 1 | export type Supplier = T | Promise | (() => T | Promise); 2 | 3 | export const Supplier = { 4 | get: async (supplier: Supplier): Promise => { 5 | if (typeof supplier === "function") { 6 | return (supplier as () => T)(); 7 | } else { 8 | return supplier; 9 | } 10 | }, 11 | }; 12 | -------------------------------------------------------------------------------- /src/core/fetcher/createRequestUrl.ts: -------------------------------------------------------------------------------- 1 | import qs from "qs"; 2 | 3 | export function createRequestUrl( 4 | baseUrl: string, 5 | queryParameters?: Record, 6 | ): string { 7 | return Object.keys(queryParameters ?? {}).length > 0 8 | ? `${baseUrl}?${qs.stringify(queryParameters, { arrayFormat: "repeat" })}` 9 | : baseUrl; 10 | } 11 | -------------------------------------------------------------------------------- /src/core/fetcher/getFetchFn.ts: -------------------------------------------------------------------------------- 1 | import { RUNTIME } from "../runtime"; 2 | 3 | /** 4 | * Returns a fetch function based on the runtime 5 | */ 6 | export async function getFetchFn(): Promise { 7 | // In Node.js 18+ environments, use native fetch 8 | if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) { 9 | return fetch; 10 | } 11 | 12 | // In Node.js 18 or lower environments, the SDK always uses`node-fetch`. 13 | if (RUNTIME.type === "node") { 14 | return (await import("node-fetch")).default as any; 15 | } 16 | 17 | // Otherwise the SDK uses global fetch if available, 18 | // and falls back to node-fetch. 19 | if (typeof fetch == "function") { 20 | return fetch; 21 | } 22 | 23 | // Defaults to node `node-fetch` if global fetch isn't available 24 | return (await import("node-fetch")).default as any; 25 | } 26 | -------------------------------------------------------------------------------- /src/core/fetcher/getHeader.ts: -------------------------------------------------------------------------------- 1 | export function getHeader(headers: Record, header: string): string | undefined { 2 | for (const [headerKey, headerValue] of Object.entries(headers)) { 3 | if (headerKey.toLowerCase() === header.toLowerCase()) { 4 | return headerValue; 5 | } 6 | } 7 | return undefined; 8 | } 9 | -------------------------------------------------------------------------------- /src/core/fetcher/getRequestBody.ts: -------------------------------------------------------------------------------- 1 | import { toJson } from "../json"; 2 | 3 | export declare namespace GetRequestBody { 4 | interface Args { 5 | body: unknown; 6 | type: "json" | "file" | "bytes" | "other"; 7 | } 8 | } 9 | 10 | export async function getRequestBody({ body, type }: GetRequestBody.Args): Promise { 11 | if (type.includes("json")) { 12 | return toJson(body); 13 | } else { 14 | return body as BodyInit; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/core/fetcher/getResponseBody.ts: -------------------------------------------------------------------------------- 1 | import { chooseStreamWrapper } from "./stream-wrappers/chooseStreamWrapper"; 2 | 3 | export async function getResponseBody(response: Response, responseType?: string): Promise { 4 | if (response.body != null && responseType === "blob") { 5 | return await response.blob(); 6 | } else if (response.body != null && responseType === "sse") { 7 | return response.body; 8 | } else if (response.body != null && responseType === "streaming") { 9 | return chooseStreamWrapper(response.body); 10 | } else if (response.body != null && responseType === "arraybuffer") { 11 | return await response.arrayBuffer(); 12 | } else if (response.body != null && responseType === "text") { 13 | return await response.text(); 14 | } else { 15 | const text = await response.text(); 16 | if (text.length > 0) { 17 | try { 18 | let responseBody = JSON.parse(text); 19 | return responseBody; 20 | } catch (err) { 21 | return { 22 | ok: false, 23 | error: { 24 | reason: "non-json", 25 | statusCode: response.status, 26 | rawBody: text, 27 | }, 28 | }; 29 | } 30 | } else { 31 | return undefined; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/core/fetcher/index.ts: -------------------------------------------------------------------------------- 1 | export type { APIResponse } from "./APIResponse"; 2 | export { fetcher } from "./Fetcher"; 3 | export type { Fetcher, FetchFunction } from "./Fetcher"; 4 | export { getHeader } from "./getHeader"; 5 | export { Supplier } from "./Supplier"; 6 | -------------------------------------------------------------------------------- /src/core/fetcher/makeRequest.ts: -------------------------------------------------------------------------------- 1 | import { anySignal, getTimeoutSignal } from "./signals"; 2 | 3 | export const makeRequest = async ( 4 | fetchFn: (url: string, init: RequestInit) => Promise, 5 | url: string, 6 | method: string, 7 | headers: Record, 8 | requestBody: BodyInit | undefined, 9 | timeoutMs?: number, 10 | abortSignal?: AbortSignal, 11 | withCredentials?: boolean, 12 | duplex?: "half", 13 | ): Promise => { 14 | const signals: AbortSignal[] = []; 15 | 16 | // Add timeout signal 17 | let timeoutAbortId: NodeJS.Timeout | undefined = undefined; 18 | if (timeoutMs != null) { 19 | const { signal, abortId } = getTimeoutSignal(timeoutMs); 20 | timeoutAbortId = abortId; 21 | signals.push(signal); 22 | } 23 | 24 | // Add arbitrary signal 25 | if (abortSignal != null) { 26 | signals.push(abortSignal); 27 | } 28 | let newSignals = anySignal(signals); 29 | const response = await fetchFn(url, { 30 | method: method, 31 | headers, 32 | body: requestBody, 33 | signal: newSignals, 34 | credentials: withCredentials ? "include" : undefined, 35 | // @ts-ignore 36 | duplex, 37 | }); 38 | 39 | if (timeoutAbortId != null) { 40 | clearTimeout(timeoutAbortId); 41 | } 42 | 43 | return response; 44 | }; 45 | -------------------------------------------------------------------------------- /src/core/fetcher/requestWithRetries.ts: -------------------------------------------------------------------------------- 1 | const INITIAL_RETRY_DELAY = 1000; // in milliseconds 2 | const MAX_RETRY_DELAY = 60000; // in milliseconds 3 | const DEFAULT_MAX_RETRIES = 2; 4 | const JITTER_FACTOR = 0.2; // 20% random jitter 5 | 6 | function addJitter(delay: number): number { 7 | // Generate a random value between -JITTER_FACTOR and +JITTER_FACTOR 8 | const jitterMultiplier = 1 + (Math.random() * 2 - 1) * JITTER_FACTOR; 9 | return delay * jitterMultiplier; 10 | } 11 | 12 | export async function requestWithRetries( 13 | requestFn: () => Promise, 14 | maxRetries: number = DEFAULT_MAX_RETRIES, 15 | ): Promise { 16 | let response: Response = await requestFn(); 17 | 18 | for (let i = 0; i < maxRetries; ++i) { 19 | if ([408, 429].includes(response.status) || response.status >= 500) { 20 | // Calculate base delay using exponential backoff (in milliseconds) 21 | const baseDelay = Math.min(INITIAL_RETRY_DELAY * Math.pow(2, i), MAX_RETRY_DELAY); 22 | 23 | // Add jitter to the delay 24 | const delayWithJitter = addJitter(baseDelay); 25 | 26 | await new Promise((resolve) => setTimeout(resolve, delayWithJitter)); 27 | response = await requestFn(); 28 | } else { 29 | break; 30 | } 31 | } 32 | return response!; 33 | } 34 | -------------------------------------------------------------------------------- /src/core/fetcher/signals.ts: -------------------------------------------------------------------------------- 1 | const TIMEOUT = "timeout"; 2 | 3 | export function getTimeoutSignal(timeoutMs: number): { signal: AbortSignal; abortId: NodeJS.Timeout } { 4 | const controller = new AbortController(); 5 | const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs); 6 | return { signal: controller.signal, abortId }; 7 | } 8 | 9 | /** 10 | * Returns an abort signal that is getting aborted when 11 | * at least one of the specified abort signals is aborted. 12 | * 13 | * Requires at least node.js 18. 14 | */ 15 | export function anySignal(...args: AbortSignal[] | [AbortSignal[]]): AbortSignal { 16 | // Allowing signals to be passed either as array 17 | // of signals or as multiple arguments. 18 | const signals = (args.length === 1 && Array.isArray(args[0]) ? args[0] : args) as AbortSignal[]; 19 | 20 | const controller = new AbortController(); 21 | 22 | for (const signal of signals) { 23 | if (signal.aborted) { 24 | // Exiting early if one of the signals 25 | // is already aborted. 26 | controller.abort((signal as any)?.reason); 27 | break; 28 | } 29 | 30 | // Listening for signals and removing the listeners 31 | // when at least one symbol is aborted. 32 | signal.addEventListener("abort", () => controller.abort((signal as any)?.reason), { 33 | signal: controller.signal, 34 | }); 35 | } 36 | 37 | return controller.signal; 38 | } 39 | -------------------------------------------------------------------------------- /src/core/fetcher/stream-wrappers/chooseStreamWrapper.ts: -------------------------------------------------------------------------------- 1 | import type { Readable } from "readable-stream"; 2 | 3 | import { RUNTIME } from "../../runtime"; 4 | 5 | export type EventCallback = (data?: any) => void; 6 | 7 | export interface StreamWrapper { 8 | setEncoding(encoding?: string): void; 9 | on(event: string, callback: EventCallback): void; 10 | off(event: string, callback: EventCallback): void; 11 | pipe(dest: WritableStream): WritableStream; 12 | pipeTo(dest: WritableStream): WritableStream; 13 | unpipe(dest?: WritableStream): void; 14 | destroy(error?: Error): void; 15 | pause(): void; 16 | resume(): void; 17 | get isPaused(): boolean; 18 | read(): Promise; 19 | text(): Promise; 20 | json(): Promise; 21 | [Symbol.asyncIterator](): AsyncIterableIterator; 22 | } 23 | 24 | export async function chooseStreamWrapper(responseBody: any): Promise>> { 25 | if (RUNTIME.type === "node" && RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) { 26 | return new (await import("./Node18UniversalStreamWrapper")).Node18UniversalStreamWrapper( 27 | responseBody as ReadableStream, 28 | ); 29 | } else if (RUNTIME.type !== "node" && typeof fetch === "function") { 30 | return new (await import("./UndiciStreamWrapper")).UndiciStreamWrapper(responseBody as ReadableStream); 31 | } else { 32 | return new (await import("./NodePre18StreamWrapper")).NodePre18StreamWrapper(responseBody as Readable); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/core/form-data-utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./FormDataWrapper"; 2 | -------------------------------------------------------------------------------- /src/core/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./fetcher"; 2 | export * from "./runtime"; 3 | export * from "./form-data-utils"; 4 | export * from "./streaming-fetcher"; 5 | export * as serialization from "./schemas"; 6 | -------------------------------------------------------------------------------- /src/core/json.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Serialize a value to JSON 3 | * @param value A JavaScript value, usually an object or array, to be converted. 4 | * @param replacer A function that transforms the results. 5 | * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. 6 | * @returns JSON string 7 | */ 8 | export const toJson = ( 9 | value: unknown, 10 | replacer?: (this: unknown, key: string, value: unknown) => unknown, 11 | space?: string | number, 12 | ): string => { 13 | return JSON.stringify(value, replacer, space); 14 | }; 15 | 16 | /** 17 | * Parse JSON string to object, array, or other type 18 | * @param text A valid JSON string. 19 | * @param reviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is. 20 | * @returns Parsed object, array, or other type 21 | */ 22 | export function fromJson( 23 | text: string, 24 | reviver?: (this: unknown, key: string, value: unknown) => unknown, 25 | ): T { 26 | return JSON.parse(text, reviver); 27 | } 28 | -------------------------------------------------------------------------------- /src/core/runtime/index.ts: -------------------------------------------------------------------------------- 1 | export { RUNTIME } from "./runtime"; 2 | -------------------------------------------------------------------------------- /src/core/schemas/builders/bigint/bigint.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema, Schema, SchemaType } from "../../Schema"; 2 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 3 | import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; 4 | import { getSchemaUtils } from "../schema-utils"; 5 | 6 | export function bigint(): Schema { 7 | const baseSchema: BaseSchema = { 8 | parse: (raw, { breadcrumbsPrefix = [] } = {}) => { 9 | if (typeof raw === "bigint") { 10 | return { 11 | ok: true, 12 | value: raw, 13 | }; 14 | } 15 | if (typeof raw === "number") { 16 | return { 17 | ok: true, 18 | value: BigInt(raw), 19 | }; 20 | } 21 | return { 22 | ok: false, 23 | errors: [ 24 | { 25 | path: breadcrumbsPrefix, 26 | message: getErrorMessageForIncorrectType(raw, "bigint | number"), 27 | }, 28 | ], 29 | }; 30 | }, 31 | json: (bigint, { breadcrumbsPrefix = [] } = {}) => { 32 | if (typeof bigint !== "bigint") { 33 | return { 34 | ok: false, 35 | errors: [ 36 | { 37 | path: breadcrumbsPrefix, 38 | message: getErrorMessageForIncorrectType(bigint, "bigint"), 39 | }, 40 | ], 41 | }; 42 | } 43 | return { 44 | ok: true, 45 | value: bigint, 46 | }; 47 | }, 48 | getType: () => SchemaType.BIGINT, 49 | }; 50 | 51 | return { 52 | ...maybeSkipValidation(baseSchema), 53 | ...getSchemaUtils(baseSchema), 54 | }; 55 | } 56 | -------------------------------------------------------------------------------- /src/core/schemas/builders/bigint/index.ts: -------------------------------------------------------------------------------- 1 | export { bigint } from "./bigint"; 2 | -------------------------------------------------------------------------------- /src/core/schemas/builders/date/index.ts: -------------------------------------------------------------------------------- 1 | export { date } from "./date"; 2 | -------------------------------------------------------------------------------- /src/core/schemas/builders/enum/enum.ts: -------------------------------------------------------------------------------- 1 | import { Schema, SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 4 | 5 | export function enum_(values: E): Schema { 6 | const validValues = new Set(values); 7 | 8 | const schemaCreator = createIdentitySchemaCreator( 9 | SchemaType.ENUM, 10 | (value, { allowUnrecognizedEnumValues, breadcrumbsPrefix = [] } = {}) => { 11 | if (typeof value !== "string") { 12 | return { 13 | ok: false, 14 | errors: [ 15 | { 16 | path: breadcrumbsPrefix, 17 | message: getErrorMessageForIncorrectType(value, "string"), 18 | }, 19 | ], 20 | }; 21 | } 22 | 23 | if (!validValues.has(value) && !allowUnrecognizedEnumValues) { 24 | return { 25 | ok: false, 26 | errors: [ 27 | { 28 | path: breadcrumbsPrefix, 29 | message: getErrorMessageForIncorrectType(value, "enum"), 30 | }, 31 | ], 32 | }; 33 | } 34 | 35 | return { 36 | ok: true, 37 | value: value as U, 38 | }; 39 | }, 40 | ); 41 | 42 | return schemaCreator(); 43 | } 44 | -------------------------------------------------------------------------------- /src/core/schemas/builders/enum/index.ts: -------------------------------------------------------------------------------- 1 | export { enum_ } from "./enum"; 2 | -------------------------------------------------------------------------------- /src/core/schemas/builders/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./bigint"; 2 | export * from "./date"; 3 | export * from "./enum"; 4 | export * from "./lazy"; 5 | export * from "./list"; 6 | export * from "./literals"; 7 | export * from "./object"; 8 | export * from "./object-like"; 9 | export * from "./primitives"; 10 | export * from "./record"; 11 | export * from "./schema-utils"; 12 | export * from "./set"; 13 | export * from "./undiscriminated-union"; 14 | export * from "./union"; 15 | -------------------------------------------------------------------------------- /src/core/schemas/builders/lazy/index.ts: -------------------------------------------------------------------------------- 1 | export { lazy } from "./lazy"; 2 | export type { SchemaGetter } from "./lazy"; 3 | export { lazyObject } from "./lazyObject"; 4 | -------------------------------------------------------------------------------- /src/core/schemas/builders/lazy/lazy.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema, Schema } from "../../Schema"; 2 | import { getSchemaUtils } from "../schema-utils"; 3 | 4 | export type SchemaGetter> = () => SchemaType; 5 | 6 | export function lazy(getter: SchemaGetter>): Schema { 7 | const baseSchema = constructLazyBaseSchema(getter); 8 | return { 9 | ...baseSchema, 10 | ...getSchemaUtils(baseSchema), 11 | }; 12 | } 13 | 14 | export function constructLazyBaseSchema( 15 | getter: SchemaGetter>, 16 | ): BaseSchema { 17 | return { 18 | parse: (raw, opts) => getMemoizedSchema(getter).parse(raw, opts), 19 | json: (parsed, opts) => getMemoizedSchema(getter).json(parsed, opts), 20 | getType: () => getMemoizedSchema(getter).getType(), 21 | }; 22 | } 23 | 24 | type MemoizedGetter> = SchemaGetter & { __zurg_memoized?: SchemaType }; 25 | 26 | export function getMemoizedSchema>(getter: SchemaGetter): SchemaType { 27 | const castedGetter = getter as MemoizedGetter; 28 | if (castedGetter.__zurg_memoized == null) { 29 | castedGetter.__zurg_memoized = getter(); 30 | } 31 | return castedGetter.__zurg_memoized; 32 | } 33 | -------------------------------------------------------------------------------- /src/core/schemas/builders/lazy/lazyObject.ts: -------------------------------------------------------------------------------- 1 | import { getObjectUtils } from "../object"; 2 | import { getObjectLikeUtils } from "../object-like"; 3 | import { BaseObjectSchema, ObjectSchema } from "../object/types"; 4 | import { getSchemaUtils } from "../schema-utils"; 5 | import { SchemaGetter, constructLazyBaseSchema, getMemoizedSchema } from "./lazy"; 6 | 7 | export function lazyObject(getter: SchemaGetter>): ObjectSchema { 8 | const baseSchema: BaseObjectSchema = { 9 | ...constructLazyBaseSchema(getter), 10 | _getRawProperties: () => getMemoizedSchema(getter)._getRawProperties(), 11 | _getParsedProperties: () => getMemoizedSchema(getter)._getParsedProperties(), 12 | }; 13 | 14 | return { 15 | ...baseSchema, 16 | ...getSchemaUtils(baseSchema), 17 | ...getObjectLikeUtils(baseSchema), 18 | ...getObjectUtils(baseSchema), 19 | }; 20 | } 21 | -------------------------------------------------------------------------------- /src/core/schemas/builders/list/index.ts: -------------------------------------------------------------------------------- 1 | export { list } from "./list"; 2 | -------------------------------------------------------------------------------- /src/core/schemas/builders/literals/booleanLiteral.ts: -------------------------------------------------------------------------------- 1 | import { Schema, SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 4 | 5 | export function booleanLiteral(literal: V): Schema { 6 | const schemaCreator = createIdentitySchemaCreator( 7 | SchemaType.BOOLEAN_LITERAL, 8 | (value, { breadcrumbsPrefix = [] } = {}) => { 9 | if (value === literal) { 10 | return { 11 | ok: true, 12 | value: literal, 13 | }; 14 | } else { 15 | return { 16 | ok: false, 17 | errors: [ 18 | { 19 | path: breadcrumbsPrefix, 20 | message: getErrorMessageForIncorrectType(value, `${literal.toString()}`), 21 | }, 22 | ], 23 | }; 24 | } 25 | }, 26 | ); 27 | 28 | return schemaCreator(); 29 | } 30 | -------------------------------------------------------------------------------- /src/core/schemas/builders/literals/index.ts: -------------------------------------------------------------------------------- 1 | export { stringLiteral } from "./stringLiteral"; 2 | export { booleanLiteral } from "./booleanLiteral"; 3 | -------------------------------------------------------------------------------- /src/core/schemas/builders/literals/stringLiteral.ts: -------------------------------------------------------------------------------- 1 | import { Schema, SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 4 | 5 | export function stringLiteral(literal: V): Schema { 6 | const schemaCreator = createIdentitySchemaCreator( 7 | SchemaType.STRING_LITERAL, 8 | (value, { breadcrumbsPrefix = [] } = {}) => { 9 | if (value === literal) { 10 | return { 11 | ok: true, 12 | value: literal, 13 | }; 14 | } else { 15 | return { 16 | ok: false, 17 | errors: [ 18 | { 19 | path: breadcrumbsPrefix, 20 | message: getErrorMessageForIncorrectType(value, `"${literal}"`), 21 | }, 22 | ], 23 | }; 24 | } 25 | }, 26 | ); 27 | 28 | return schemaCreator(); 29 | } 30 | -------------------------------------------------------------------------------- /src/core/schemas/builders/object-like/index.ts: -------------------------------------------------------------------------------- 1 | export { getObjectLikeUtils, withParsedProperties } from "./getObjectLikeUtils"; 2 | export type { ObjectLikeSchema, ObjectLikeUtils } from "./types"; 3 | -------------------------------------------------------------------------------- /src/core/schemas/builders/object-like/types.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema, Schema } from "../../Schema"; 2 | 3 | export type ObjectLikeSchema = Schema & 4 | BaseSchema & 5 | ObjectLikeUtils; 6 | 7 | export interface ObjectLikeUtils { 8 | withParsedProperties: >(properties: { 9 | [K in keyof T]: T[K] | ((parsed: Parsed) => T[K]); 10 | }) => ObjectLikeSchema; 11 | } 12 | -------------------------------------------------------------------------------- /src/core/schemas/builders/object/index.ts: -------------------------------------------------------------------------------- 1 | export { getObjectUtils, object } from "./object"; 2 | export { objectWithoutOptionalProperties } from "./objectWithoutOptionalProperties"; 3 | export type { 4 | inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas, 5 | inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas, 6 | } from "./objectWithoutOptionalProperties"; 7 | export { isProperty, property } from "./property"; 8 | export type { Property } from "./property"; 9 | export type { 10 | BaseObjectSchema, 11 | inferObjectSchemaFromPropertySchemas, 12 | inferParsedObject, 13 | inferParsedObjectFromPropertySchemas, 14 | inferParsedPropertySchema, 15 | inferRawKey, 16 | inferRawObject, 17 | inferRawObjectFromPropertySchemas, 18 | inferRawPropertySchema, 19 | ObjectSchema, 20 | ObjectUtils, 21 | PropertySchemas, 22 | } from "./types"; 23 | -------------------------------------------------------------------------------- /src/core/schemas/builders/object/objectWithoutOptionalProperties.ts: -------------------------------------------------------------------------------- 1 | import { object } from "./object"; 2 | import { ObjectSchema, PropertySchemas, inferParsedPropertySchema, inferRawObjectFromPropertySchemas } from "./types"; 3 | 4 | export function objectWithoutOptionalProperties>( 5 | schemas: T, 6 | ): inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas { 7 | return object(schemas) as unknown as inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas; 8 | } 9 | 10 | export type inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas> = 11 | ObjectSchema< 12 | inferRawObjectFromPropertySchemas, 13 | inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas 14 | >; 15 | 16 | export type inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas> = { 17 | [K in keyof T]: inferParsedPropertySchema; 18 | }; 19 | -------------------------------------------------------------------------------- /src/core/schemas/builders/object/property.ts: -------------------------------------------------------------------------------- 1 | import { Schema } from "../../Schema"; 2 | 3 | export function property( 4 | rawKey: RawKey, 5 | valueSchema: Schema, 6 | ): Property { 7 | return { 8 | rawKey, 9 | valueSchema, 10 | isProperty: true, 11 | }; 12 | } 13 | 14 | export interface Property { 15 | rawKey: RawKey; 16 | valueSchema: Schema; 17 | isProperty: true; 18 | } 19 | 20 | export function isProperty>(maybeProperty: unknown): maybeProperty is O { 21 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition 22 | return (maybeProperty as O).isProperty; 23 | } 24 | -------------------------------------------------------------------------------- /src/core/schemas/builders/primitives/any.ts: -------------------------------------------------------------------------------- 1 | import { SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | 4 | export const any = createIdentitySchemaCreator(SchemaType.ANY, (value) => ({ ok: true, value })); 5 | -------------------------------------------------------------------------------- /src/core/schemas/builders/primitives/boolean.ts: -------------------------------------------------------------------------------- 1 | import { SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 4 | 5 | export const boolean = createIdentitySchemaCreator( 6 | SchemaType.BOOLEAN, 7 | (value, { breadcrumbsPrefix = [] } = {}) => { 8 | if (typeof value === "boolean") { 9 | return { 10 | ok: true, 11 | value, 12 | }; 13 | } else { 14 | return { 15 | ok: false, 16 | errors: [ 17 | { 18 | path: breadcrumbsPrefix, 19 | message: getErrorMessageForIncorrectType(value, "boolean"), 20 | }, 21 | ], 22 | }; 23 | } 24 | }, 25 | ); 26 | -------------------------------------------------------------------------------- /src/core/schemas/builders/primitives/index.ts: -------------------------------------------------------------------------------- 1 | export { any } from "./any"; 2 | export { boolean } from "./boolean"; 3 | export { number } from "./number"; 4 | export { string } from "./string"; 5 | export { unknown } from "./unknown"; 6 | -------------------------------------------------------------------------------- /src/core/schemas/builders/primitives/number.ts: -------------------------------------------------------------------------------- 1 | import { SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 4 | 5 | export const number = createIdentitySchemaCreator( 6 | SchemaType.NUMBER, 7 | (value, { breadcrumbsPrefix = [] } = {}) => { 8 | if (typeof value === "number") { 9 | return { 10 | ok: true, 11 | value, 12 | }; 13 | } else { 14 | return { 15 | ok: false, 16 | errors: [ 17 | { 18 | path: breadcrumbsPrefix, 19 | message: getErrorMessageForIncorrectType(value, "number"), 20 | }, 21 | ], 22 | }; 23 | } 24 | }, 25 | ); 26 | -------------------------------------------------------------------------------- /src/core/schemas/builders/primitives/string.ts: -------------------------------------------------------------------------------- 1 | import { SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 4 | 5 | export const string = createIdentitySchemaCreator( 6 | SchemaType.STRING, 7 | (value, { breadcrumbsPrefix = [] } = {}) => { 8 | if (typeof value === "string") { 9 | return { 10 | ok: true, 11 | value, 12 | }; 13 | } else { 14 | return { 15 | ok: false, 16 | errors: [ 17 | { 18 | path: breadcrumbsPrefix, 19 | message: getErrorMessageForIncorrectType(value, "string"), 20 | }, 21 | ], 22 | }; 23 | } 24 | }, 25 | ); 26 | -------------------------------------------------------------------------------- /src/core/schemas/builders/primitives/unknown.ts: -------------------------------------------------------------------------------- 1 | import { SchemaType } from "../../Schema"; 2 | import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; 3 | 4 | export const unknown = createIdentitySchemaCreator(SchemaType.UNKNOWN, (value) => ({ ok: true, value })); 5 | -------------------------------------------------------------------------------- /src/core/schemas/builders/record/index.ts: -------------------------------------------------------------------------------- 1 | export { record } from "./record"; 2 | export type { BaseRecordSchema, RecordSchema } from "./types"; 3 | -------------------------------------------------------------------------------- /src/core/schemas/builders/record/types.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema } from "../../Schema"; 2 | import { SchemaUtils } from "../schema-utils"; 3 | 4 | export type RecordSchema< 5 | RawKey extends string | number, 6 | RawValue, 7 | ParsedKey extends string | number, 8 | ParsedValue, 9 | > = BaseRecordSchema & 10 | SchemaUtils, Record>; 11 | 12 | export type BaseRecordSchema< 13 | RawKey extends string | number, 14 | RawValue, 15 | ParsedKey extends string | number, 16 | ParsedValue, 17 | > = BaseSchema, Record>; 18 | -------------------------------------------------------------------------------- /src/core/schemas/builders/schema-utils/JsonError.ts: -------------------------------------------------------------------------------- 1 | import { ValidationError } from "../../Schema"; 2 | import { stringifyValidationError } from "./stringifyValidationErrors"; 3 | 4 | export class JsonError extends Error { 5 | constructor(public readonly errors: ValidationError[]) { 6 | super(errors.map(stringifyValidationError).join("; ")); 7 | Object.setPrototypeOf(this, JsonError.prototype); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/core/schemas/builders/schema-utils/ParseError.ts: -------------------------------------------------------------------------------- 1 | import { ValidationError } from "../../Schema"; 2 | import { stringifyValidationError } from "./stringifyValidationErrors"; 3 | 4 | export class ParseError extends Error { 5 | constructor(public readonly errors: ValidationError[]) { 6 | super(errors.map(stringifyValidationError).join("; ")); 7 | Object.setPrototypeOf(this, ParseError.prototype); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/core/schemas/builders/schema-utils/index.ts: -------------------------------------------------------------------------------- 1 | export { getSchemaUtils, optional, transform } from "./getSchemaUtils"; 2 | export type { SchemaUtils } from "./getSchemaUtils"; 3 | export { JsonError } from "./JsonError"; 4 | export { ParseError } from "./ParseError"; 5 | -------------------------------------------------------------------------------- /src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts: -------------------------------------------------------------------------------- 1 | import { ValidationError } from "../../Schema"; 2 | 3 | export function stringifyValidationError(error: ValidationError): string { 4 | if (error.path.length === 0) { 5 | return error.message; 6 | } 7 | return `${error.path.join(" -> ")}: ${error.message}`; 8 | } 9 | -------------------------------------------------------------------------------- /src/core/schemas/builders/set/index.ts: -------------------------------------------------------------------------------- 1 | export { set } from "./set"; 2 | -------------------------------------------------------------------------------- /src/core/schemas/builders/set/set.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema, Schema, SchemaType } from "../../Schema"; 2 | import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; 3 | import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; 4 | import { list } from "../list"; 5 | import { getSchemaUtils } from "../schema-utils"; 6 | 7 | export function set(schema: Schema): Schema> { 8 | const listSchema = list(schema); 9 | const baseSchema: BaseSchema> = { 10 | parse: (raw, opts) => { 11 | const parsedList = listSchema.parse(raw, opts); 12 | if (parsedList.ok) { 13 | return { 14 | ok: true, 15 | value: new Set(parsedList.value), 16 | }; 17 | } else { 18 | return parsedList; 19 | } 20 | }, 21 | json: (parsed, opts) => { 22 | if (!(parsed instanceof Set)) { 23 | return { 24 | ok: false, 25 | errors: [ 26 | { 27 | path: opts?.breadcrumbsPrefix ?? [], 28 | message: getErrorMessageForIncorrectType(parsed, "Set"), 29 | }, 30 | ], 31 | }; 32 | } 33 | const jsonList = listSchema.json([...parsed], opts); 34 | return jsonList; 35 | }, 36 | getType: () => SchemaType.SET, 37 | }; 38 | 39 | return { 40 | ...maybeSkipValidation(baseSchema), 41 | ...getSchemaUtils(baseSchema), 42 | }; 43 | } 44 | -------------------------------------------------------------------------------- /src/core/schemas/builders/undiscriminated-union/index.ts: -------------------------------------------------------------------------------- 1 | export type { 2 | inferParsedUnidiscriminatedUnionSchema, 3 | inferRawUnidiscriminatedUnionSchema, 4 | UndiscriminatedUnionSchema, 5 | } from "./types"; 6 | export { undiscriminatedUnion } from "./undiscriminatedUnion"; 7 | -------------------------------------------------------------------------------- /src/core/schemas/builders/undiscriminated-union/types.ts: -------------------------------------------------------------------------------- 1 | import { Schema, inferParsed, inferRaw } from "../../Schema"; 2 | 3 | export type UndiscriminatedUnionSchema = Schema< 4 | inferRawUnidiscriminatedUnionSchema, 5 | inferParsedUnidiscriminatedUnionSchema 6 | >; 7 | 8 | export type inferRawUnidiscriminatedUnionSchema = inferRaw; 9 | 10 | export type inferParsedUnidiscriminatedUnionSchema = inferParsed; 11 | -------------------------------------------------------------------------------- /src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema, MaybeValid, Schema, SchemaOptions, SchemaType, ValidationError } from "../../Schema"; 2 | import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; 3 | import { getSchemaUtils } from "../schema-utils"; 4 | import { inferParsedUnidiscriminatedUnionSchema, inferRawUnidiscriminatedUnionSchema } from "./types"; 5 | 6 | export function undiscriminatedUnion, ...Schema[]]>( 7 | schemas: Schemas, 8 | ): Schema, inferParsedUnidiscriminatedUnionSchema> { 9 | const baseSchema: BaseSchema< 10 | inferRawUnidiscriminatedUnionSchema, 11 | inferParsedUnidiscriminatedUnionSchema 12 | > = { 13 | parse: (raw, opts) => { 14 | return validateAndTransformUndiscriminatedUnion>( 15 | (schema, opts) => schema.parse(raw, opts), 16 | schemas, 17 | opts, 18 | ); 19 | }, 20 | json: (parsed, opts) => { 21 | return validateAndTransformUndiscriminatedUnion>( 22 | (schema, opts) => schema.json(parsed, opts), 23 | schemas, 24 | opts, 25 | ); 26 | }, 27 | getType: () => SchemaType.UNDISCRIMINATED_UNION, 28 | }; 29 | 30 | return { 31 | ...maybeSkipValidation(baseSchema), 32 | ...getSchemaUtils(baseSchema), 33 | }; 34 | } 35 | 36 | function validateAndTransformUndiscriminatedUnion( 37 | transform: (schema: Schema, opts: SchemaOptions) => MaybeValid, 38 | schemas: Schema[], 39 | opts: SchemaOptions | undefined, 40 | ): MaybeValid { 41 | const errors: ValidationError[] = []; 42 | for (const [index, schema] of schemas.entries()) { 43 | const transformed = transform(schema, { ...opts, skipValidation: false }); 44 | if (transformed.ok) { 45 | return transformed; 46 | } else { 47 | for (const error of transformed.errors) { 48 | errors.push({ 49 | path: error.path, 50 | message: `[Variant ${index}] ${error.message}`, 51 | }); 52 | } 53 | } 54 | } 55 | 56 | return { 57 | ok: false, 58 | errors, 59 | }; 60 | } 61 | -------------------------------------------------------------------------------- /src/core/schemas/builders/union/discriminant.ts: -------------------------------------------------------------------------------- 1 | export function discriminant( 2 | parsedDiscriminant: ParsedDiscriminant, 3 | rawDiscriminant: RawDiscriminant, 4 | ): Discriminant { 5 | return { 6 | parsedDiscriminant, 7 | rawDiscriminant, 8 | }; 9 | } 10 | 11 | export interface Discriminant { 12 | parsedDiscriminant: ParsedDiscriminant; 13 | rawDiscriminant: RawDiscriminant; 14 | } 15 | -------------------------------------------------------------------------------- /src/core/schemas/builders/union/index.ts: -------------------------------------------------------------------------------- 1 | export { discriminant } from "./discriminant"; 2 | export type { Discriminant } from "./discriminant"; 3 | export type { 4 | inferParsedDiscriminant, 5 | inferParsedUnion, 6 | inferRawDiscriminant, 7 | inferRawUnion, 8 | UnionSubtypes, 9 | } from "./types"; 10 | export { union } from "./union"; 11 | -------------------------------------------------------------------------------- /src/core/schemas/builders/union/types.ts: -------------------------------------------------------------------------------- 1 | import { ObjectSchema, inferParsedObject, inferRawObject } from "../object"; 2 | import { Discriminant } from "./discriminant"; 3 | 4 | export type UnionSubtypes = { 5 | [K in DiscriminantValues]: ObjectSchema; 6 | }; 7 | 8 | export type inferRawUnion, U extends UnionSubtypes> = { 9 | [K in keyof U]: Record, K> & inferRawObject; 10 | }[keyof U]; 11 | 12 | export type inferParsedUnion, U extends UnionSubtypes> = { 13 | [K in keyof U]: Record, K> & inferParsedObject; 14 | }[keyof U]; 15 | 16 | export type inferRawDiscriminant> = D extends string 17 | ? D 18 | : D extends Discriminant 19 | ? Raw 20 | : never; 21 | 22 | export type inferParsedDiscriminant> = D extends string 23 | ? D 24 | : D extends Discriminant 25 | ? Parsed 26 | : never; 27 | -------------------------------------------------------------------------------- /src/core/schemas/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./builders"; 2 | export type { inferParsed, inferRaw, Schema, SchemaOptions } from "./Schema"; 3 | -------------------------------------------------------------------------------- /src/core/schemas/utils/MaybePromise.ts: -------------------------------------------------------------------------------- 1 | export type MaybePromise = T | Promise; 2 | -------------------------------------------------------------------------------- /src/core/schemas/utils/addQuestionMarksToNullableProperties.ts: -------------------------------------------------------------------------------- 1 | export type addQuestionMarksToNullableProperties = { 2 | [K in OptionalKeys]?: T[K]; 3 | } & Pick>; 4 | 5 | export type OptionalKeys = { 6 | [K in keyof T]-?: undefined extends T[K] ? K : never; 7 | }[keyof T]; 8 | 9 | export type RequiredKeys = Exclude>; 10 | -------------------------------------------------------------------------------- /src/core/schemas/utils/createIdentitySchemaCreator.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema, MaybeValid, Schema, SchemaOptions, SchemaType } from "../Schema"; 2 | import { getSchemaUtils } from "../builders/schema-utils"; 3 | import { maybeSkipValidation } from "./maybeSkipValidation"; 4 | 5 | export function createIdentitySchemaCreator( 6 | schemaType: SchemaType, 7 | validate: (value: unknown, opts?: SchemaOptions) => MaybeValid, 8 | ): () => Schema { 9 | return () => { 10 | const baseSchema: BaseSchema = { 11 | parse: validate, 12 | json: validate, 13 | getType: () => schemaType, 14 | }; 15 | 16 | return { 17 | ...maybeSkipValidation(baseSchema), 18 | ...getSchemaUtils(baseSchema), 19 | }; 20 | }; 21 | } 22 | -------------------------------------------------------------------------------- /src/core/schemas/utils/entries.ts: -------------------------------------------------------------------------------- 1 | export function entries(object: T): [keyof T, T[keyof T]][] { 2 | return Object.entries(object) as [keyof T, T[keyof T]][]; 3 | } 4 | -------------------------------------------------------------------------------- /src/core/schemas/utils/filterObject.ts: -------------------------------------------------------------------------------- 1 | export function filterObject(obj: T, keysToInclude: K[]): Pick { 2 | const keysToIncludeSet = new Set(keysToInclude); 3 | return Object.entries(obj).reduce( 4 | (acc, [key, value]) => { 5 | if (keysToIncludeSet.has(key as K)) { 6 | acc[key as K] = value as T[K]; 7 | } 8 | return acc; 9 | // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter 10 | }, 11 | {} as Pick, 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /src/core/schemas/utils/getErrorMessageForIncorrectType.ts: -------------------------------------------------------------------------------- 1 | export function getErrorMessageForIncorrectType(value: unknown, expectedType: string): string { 2 | return `Expected ${expectedType}. Received ${getTypeAsString(value)}.`; 3 | } 4 | 5 | function getTypeAsString(value: unknown): string { 6 | if (Array.isArray(value)) { 7 | return "list"; 8 | } 9 | if (value === null) { 10 | return "null"; 11 | } 12 | if (value instanceof BigInt) { 13 | return "BigInt"; 14 | } 15 | switch (typeof value) { 16 | case "string": 17 | return `"${value}"`; 18 | case "bigint": 19 | case "number": 20 | case "boolean": 21 | case "undefined": 22 | return `${value}`; 23 | } 24 | return typeof value; 25 | } 26 | -------------------------------------------------------------------------------- /src/core/schemas/utils/isPlainObject.ts: -------------------------------------------------------------------------------- 1 | // borrowed from https://github.com/lodash/lodash/blob/master/isPlainObject.js 2 | export function isPlainObject(value: unknown): value is Record { 3 | if (typeof value !== "object" || value === null) { 4 | return false; 5 | } 6 | 7 | if (Object.getPrototypeOf(value) === null) { 8 | return true; 9 | } 10 | 11 | let proto = value; 12 | while (Object.getPrototypeOf(proto) !== null) { 13 | proto = Object.getPrototypeOf(proto); 14 | } 15 | 16 | return Object.getPrototypeOf(value) === proto; 17 | } 18 | -------------------------------------------------------------------------------- /src/core/schemas/utils/keys.ts: -------------------------------------------------------------------------------- 1 | export function keys(object: T): (keyof T)[] { 2 | return Object.keys(object) as (keyof T)[]; 3 | } 4 | -------------------------------------------------------------------------------- /src/core/schemas/utils/maybeSkipValidation.ts: -------------------------------------------------------------------------------- 1 | import { BaseSchema, MaybeValid, SchemaOptions } from "../Schema"; 2 | 3 | export function maybeSkipValidation, Raw, Parsed>(schema: S): S { 4 | return { 5 | ...schema, 6 | json: transformAndMaybeSkipValidation(schema.json), 7 | parse: transformAndMaybeSkipValidation(schema.parse), 8 | }; 9 | } 10 | 11 | function transformAndMaybeSkipValidation( 12 | transform: (value: unknown, opts?: SchemaOptions) => MaybeValid, 13 | ): (value: unknown, opts?: SchemaOptions) => MaybeValid { 14 | return (value, opts): MaybeValid => { 15 | const transformed = transform(value, opts); 16 | const { skipValidation = false } = opts ?? {}; 17 | if (!transformed.ok && skipValidation) { 18 | // eslint-disable-next-line no-console 19 | console.warn( 20 | [ 21 | "Failed to validate.", 22 | ...transformed.errors.map( 23 | (error) => 24 | " - " + 25 | (error.path.length > 0 ? `${error.path.join(".")}: ${error.message}` : error.message), 26 | ), 27 | ].join("\n"), 28 | ); 29 | 30 | return { 31 | ok: true, 32 | value: value as T, 33 | }; 34 | } else { 35 | return transformed; 36 | } 37 | }; 38 | } 39 | -------------------------------------------------------------------------------- /src/core/schemas/utils/partition.ts: -------------------------------------------------------------------------------- 1 | export function partition(items: readonly T[], predicate: (item: T) => boolean): [T[], T[]] { 2 | const trueItems: T[] = [], 3 | falseItems: T[] = []; 4 | for (const item of items) { 5 | if (predicate(item)) { 6 | trueItems.push(item); 7 | } else { 8 | falseItems.push(item); 9 | } 10 | } 11 | return [trueItems, falseItems]; 12 | } 13 | -------------------------------------------------------------------------------- /src/core/streaming-fetcher/index.ts: -------------------------------------------------------------------------------- 1 | export { Stream } from "./Stream"; 2 | -------------------------------------------------------------------------------- /src/core/websocket/events.ts: -------------------------------------------------------------------------------- 1 | export class Event { 2 | public target: any; 3 | public type: string; 4 | constructor(type: string, target: any) { 5 | this.target = target; 6 | this.type = type; 7 | } 8 | } 9 | 10 | export class ErrorEvent extends Event { 11 | public message: string; 12 | public error: Error; 13 | constructor(error: Error, target: any) { 14 | super("error", target); 15 | this.message = error.message; 16 | this.error = error; 17 | } 18 | } 19 | 20 | export class CloseEvent extends Event { 21 | public code: number; 22 | public reason: string; 23 | public wasClean = true; 24 | constructor(code = 1000, reason = "", target: any) { 25 | super("close", target); 26 | this.code = code; 27 | this.reason = reason; 28 | } 29 | } 30 | export interface WebSocketEventMap { 31 | close: CloseEvent; 32 | error: ErrorEvent; 33 | message: MessageEvent; 34 | open: Event; 35 | } 36 | 37 | export interface WebSocketEventListenerMap { 38 | close: (event: CloseEvent) => void | { handleEvent: (event: CloseEvent) => void }; 39 | error: (event: ErrorEvent) => void | { handleEvent: (event: ErrorEvent) => void }; 40 | message: (event: MessageEvent) => void | { handleEvent: (event: MessageEvent) => void }; 41 | open: (event: Event) => void | { handleEvent: (event: Event) => void }; 42 | } 43 | -------------------------------------------------------------------------------- /src/core/websocket/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./ws"; 2 | -------------------------------------------------------------------------------- /src/environments.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export const CartesiaEnvironment = { 6 | Production: "https://api.cartesia.ai", 7 | } as const; 8 | 9 | export type CartesiaEnvironment = typeof CartesiaEnvironment.Production; 10 | -------------------------------------------------------------------------------- /src/errors/CartesiaError.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import { toJson } from "../core/json"; 6 | 7 | export class CartesiaError extends Error { 8 | readonly statusCode?: number; 9 | readonly body?: unknown; 10 | 11 | constructor({ message, statusCode, body }: { message?: string; statusCode?: number; body?: unknown }) { 12 | super(buildMessage({ message, statusCode, body })); 13 | Object.setPrototypeOf(this, CartesiaError.prototype); 14 | if (statusCode != null) { 15 | this.statusCode = statusCode; 16 | } 17 | 18 | if (body !== undefined) { 19 | this.body = body; 20 | } 21 | } 22 | } 23 | 24 | function buildMessage({ 25 | message, 26 | statusCode, 27 | body, 28 | }: { 29 | message: string | undefined; 30 | statusCode: number | undefined; 31 | body: unknown | undefined; 32 | }): string { 33 | let lines: string[] = []; 34 | if (message != null) { 35 | lines.push(message); 36 | } 37 | 38 | if (statusCode != null) { 39 | lines.push(`Status code: ${statusCode.toString()}`); 40 | } 41 | 42 | if (body != null) { 43 | lines.push(`Body: ${toJson(body, undefined, 2)}`); 44 | } 45 | 46 | return lines.join("\n"); 47 | } 48 | -------------------------------------------------------------------------------- /src/errors/CartesiaTimeoutError.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | export class CartesiaTimeoutError extends Error { 6 | constructor(message: string) { 7 | super(message); 8 | Object.setPrototypeOf(this, CartesiaTimeoutError.prototype); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/errors/index.ts: -------------------------------------------------------------------------------- 1 | export { CartesiaError } from "./CartesiaError"; 2 | export { CartesiaTimeoutError } from "./CartesiaTimeoutError"; 3 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * as Cartesia from "./api"; 2 | export { CartesiaClient } from "./wrapper/Client"; 3 | export { WebPlayer } from "./wrapper/WebPlayer"; 4 | export { CartesiaEnvironment } from "./environments"; 5 | export { CartesiaError, CartesiaTimeoutError } from "./errors"; 6 | -------------------------------------------------------------------------------- /src/serialization/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./resources"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/apiStatus/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/apiStatus/types/ApiInfo.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const ApiInfo: core.serialization.ObjectSchema = 10 | core.serialization.object({ 11 | ok: core.serialization.boolean(), 12 | version: core.serialization.string(), 13 | }); 14 | 15 | export declare namespace ApiInfo { 16 | export interface Raw { 17 | ok: boolean; 18 | version: string; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/serialization/resources/apiStatus/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./ApiInfo"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/auth/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/auth/types/TokenGrant.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const TokenGrant: core.serialization.ObjectSchema = 10 | core.serialization.object({ 11 | tts: core.serialization.boolean(), 12 | }); 13 | 14 | export declare namespace TokenGrant { 15 | export interface Raw { 16 | tts: boolean; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/serialization/resources/auth/types/TokenRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { TokenGrant } from "./TokenGrant"; 9 | 10 | export const TokenRequest: core.serialization.ObjectSchema = 11 | core.serialization.object({ 12 | grants: TokenGrant, 13 | expiresIn: core.serialization.property("expires_in", core.serialization.number().optional()), 14 | }); 15 | 16 | export declare namespace TokenRequest { 17 | export interface Raw { 18 | grants: TokenGrant.Raw; 19 | expires_in?: number | null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/serialization/resources/auth/types/TokenResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const TokenResponse: core.serialization.ObjectSchema = 10 | core.serialization.object({ 11 | token: core.serialization.string(), 12 | }); 13 | 14 | export declare namespace TokenResponse { 15 | export interface Raw { 16 | token: string; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/serialization/resources/auth/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./TokenGrant"; 2 | export * from "./TokenRequest"; 3 | export * from "./TokenResponse"; 4 | -------------------------------------------------------------------------------- /src/serialization/resources/embedding/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/embedding/types/Embedding.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const Embedding: core.serialization.Schema = 10 | core.serialization.list(core.serialization.number()); 11 | 12 | export declare namespace Embedding { 13 | export type Raw = number[]; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/embedding/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./Embedding"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/index.ts: -------------------------------------------------------------------------------- 1 | export * as apiStatus from "./apiStatus"; 2 | export * from "./apiStatus/types"; 3 | export * as auth from "./auth"; 4 | export * from "./auth/types"; 5 | export * as embedding from "./embedding"; 6 | export * from "./embedding/types"; 7 | export * as tts from "./tts"; 8 | export * from "./tts/types"; 9 | export * as voiceChanger from "./voiceChanger"; 10 | export * from "./voiceChanger/types"; 11 | export * as voices from "./voices"; 12 | export * from "./voices/types"; 13 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/CancelContextRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { ContextId } from "./ContextId"; 9 | 10 | export const CancelContextRequest: core.serialization.ObjectSchema< 11 | serializers.CancelContextRequest.Raw, 12 | Cartesia.CancelContextRequest 13 | > = core.serialization.object({ 14 | contextId: core.serialization.property("context_id", ContextId), 15 | cancel: core.serialization.booleanLiteral(true), 16 | }); 17 | 18 | export declare namespace CancelContextRequest { 19 | export interface Raw { 20 | context_id: ContextId.Raw; 21 | cancel: true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/ContextId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const ContextId: core.serialization.Schema = 10 | core.serialization.string(); 11 | 12 | export declare namespace ContextId { 13 | export type Raw = string; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/Controls.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { Speed } from "./Speed"; 9 | import { Emotion } from "./Emotion"; 10 | 11 | export const Controls: core.serialization.ObjectSchema = 12 | core.serialization.object({ 13 | speed: Speed, 14 | emotion: core.serialization.list(Emotion), 15 | }); 16 | 17 | export declare namespace Controls { 18 | export interface Raw { 19 | speed: Speed.Raw; 20 | emotion: Emotion.Raw[]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/Emotion.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const Emotion: core.serialization.Schema = core.serialization.enum_([ 10 | "anger:lowest", 11 | "anger:low", 12 | "anger", 13 | "anger:high", 14 | "anger:highest", 15 | "positivity:lowest", 16 | "positivity:low", 17 | "positivity", 18 | "positivity:high", 19 | "positivity:highest", 20 | "surprise:lowest", 21 | "surprise:low", 22 | "surprise", 23 | "surprise:high", 24 | "surprise:highest", 25 | "sadness:lowest", 26 | "sadness:low", 27 | "sadness", 28 | "sadness:high", 29 | "sadness:highest", 30 | "curiosity:lowest", 31 | "curiosity:low", 32 | "curiosity", 33 | "curiosity:high", 34 | "curiosity:highest", 35 | ]); 36 | 37 | export declare namespace Emotion { 38 | export type Raw = 39 | | "anger:lowest" 40 | | "anger:low" 41 | | "anger" 42 | | "anger:high" 43 | | "anger:highest" 44 | | "positivity:lowest" 45 | | "positivity:low" 46 | | "positivity" 47 | | "positivity:high" 48 | | "positivity:highest" 49 | | "surprise:lowest" 50 | | "surprise:low" 51 | | "surprise" 52 | | "surprise:high" 53 | | "surprise:highest" 54 | | "sadness:lowest" 55 | | "sadness:low" 56 | | "sadness" 57 | | "sadness:high" 58 | | "sadness:highest" 59 | | "curiosity:lowest" 60 | | "curiosity:low" 61 | | "curiosity" 62 | | "curiosity:high" 63 | | "curiosity:highest"; 64 | } 65 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/FlushId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const FlushId: core.serialization.Schema = 10 | core.serialization.number(); 11 | 12 | export declare namespace FlushId { 13 | export type Raw = number; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/ModelSpeed.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const ModelSpeed: core.serialization.Schema = 10 | core.serialization.enum_(["slow", "normal", "fast"]); 11 | 12 | export declare namespace ModelSpeed { 13 | export type Raw = "slow" | "normal" | "fast"; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/Mp3OutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const Mp3OutputFormat: core.serialization.ObjectSchema< 10 | serializers.Mp3OutputFormat.Raw, 11 | Cartesia.Mp3OutputFormat 12 | > = core.serialization.object({ 13 | sampleRate: core.serialization.property("sample_rate", core.serialization.number()), 14 | bitRate: core.serialization.property("bit_rate", core.serialization.number()), 15 | }); 16 | 17 | export declare namespace Mp3OutputFormat { 18 | export interface Raw { 19 | sample_rate: number; 20 | bit_rate: number; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/NaturalSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const NaturalSpecifier: core.serialization.Schema = 10 | core.serialization.enum_(["slowest", "slow", "normal", "fast", "fastest"]); 11 | 12 | export declare namespace NaturalSpecifier { 13 | export type Raw = "slowest" | "slow" | "normal" | "fast" | "fastest"; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/NumericalSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const NumericalSpecifier: core.serialization.Schema< 10 | serializers.NumericalSpecifier.Raw, 11 | Cartesia.NumericalSpecifier 12 | > = core.serialization.number(); 13 | 14 | export declare namespace NumericalSpecifier { 15 | export type Raw = number; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/OutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { RawOutputFormat } from "./RawOutputFormat"; 9 | import { WavOutputFormat } from "./WavOutputFormat"; 10 | import { Mp3OutputFormat } from "./Mp3OutputFormat"; 11 | 12 | export const OutputFormat: core.serialization.Schema = 13 | core.serialization 14 | .union("container", { 15 | raw: RawOutputFormat, 16 | wav: WavOutputFormat, 17 | mp3: Mp3OutputFormat, 18 | }) 19 | .transform({ 20 | transform: (value) => value, 21 | untransform: (value) => value, 22 | }); 23 | 24 | export declare namespace OutputFormat { 25 | type Raw = OutputFormat._Raw | OutputFormat.Wav | OutputFormat.Mp3; 26 | 27 | interface _Raw extends RawOutputFormat.Raw { 28 | container: "raw"; 29 | } 30 | 31 | interface Wav extends WavOutputFormat.Raw { 32 | container: "wav"; 33 | } 34 | 35 | interface Mp3 extends Mp3OutputFormat.Raw { 36 | container: "mp3"; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/PhonemeTimestamps.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const PhonemeTimestamps: core.serialization.ObjectSchema< 10 | serializers.PhonemeTimestamps.Raw, 11 | Cartesia.PhonemeTimestamps 12 | > = core.serialization.object({ 13 | phonemes: core.serialization.list(core.serialization.string()), 14 | start: core.serialization.list(core.serialization.number()), 15 | end: core.serialization.list(core.serialization.number()), 16 | }); 17 | 18 | export declare namespace PhonemeTimestamps { 19 | export interface Raw { 20 | phonemes: string[]; 21 | start: number[]; 22 | end: number[]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/RawEncoding.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const RawEncoding: core.serialization.Schema = 10 | core.serialization.enum_(["pcm_f32le", "pcm_s16le", "pcm_mulaw", "pcm_alaw"]); 11 | 12 | export declare namespace RawEncoding { 13 | export type Raw = "pcm_f32le" | "pcm_s16le" | "pcm_mulaw" | "pcm_alaw"; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/RawOutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { RawEncoding } from "./RawEncoding"; 9 | 10 | export const RawOutputFormat: core.serialization.ObjectSchema< 11 | serializers.RawOutputFormat.Raw, 12 | Cartesia.RawOutputFormat 13 | > = core.serialization.object({ 14 | encoding: RawEncoding, 15 | sampleRate: core.serialization.property("sample_rate", core.serialization.number()), 16 | bitRate: core.serialization.property("bit_rate", core.serialization.number().optional()), 17 | }); 18 | 19 | export declare namespace RawOutputFormat { 20 | export interface Raw { 21 | encoding: RawEncoding.Raw; 22 | sample_rate: number; 23 | bit_rate?: number | null; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/Speed.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { NumericalSpecifier } from "./NumericalSpecifier"; 9 | import { NaturalSpecifier } from "./NaturalSpecifier"; 10 | 11 | export const Speed: core.serialization.Schema = 12 | core.serialization.undiscriminatedUnion([NumericalSpecifier, NaturalSpecifier]); 13 | 14 | export declare namespace Speed { 15 | export type Raw = NumericalSpecifier.Raw | NaturalSpecifier.Raw; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/SupportedLanguage.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const SupportedLanguage: core.serialization.Schema< 10 | serializers.SupportedLanguage.Raw, 11 | Cartesia.SupportedLanguage 12 | > = core.serialization.enum_([ 13 | "en", 14 | "fr", 15 | "de", 16 | "es", 17 | "pt", 18 | "zh", 19 | "ja", 20 | "hi", 21 | "it", 22 | "ko", 23 | "nl", 24 | "pl", 25 | "ru", 26 | "sv", 27 | "tr", 28 | ]); 29 | 30 | export declare namespace SupportedLanguage { 31 | export type Raw = 32 | | "en" 33 | | "fr" 34 | | "de" 35 | | "es" 36 | | "pt" 37 | | "zh" 38 | | "ja" 39 | | "hi" 40 | | "it" 41 | | "ko" 42 | | "nl" 43 | | "pl" 44 | | "ru" 45 | | "sv" 46 | | "tr"; 47 | } 48 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/TtsRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { TtsRequestVoiceSpecifier } from "./TtsRequestVoiceSpecifier"; 9 | import { SupportedLanguage } from "./SupportedLanguage"; 10 | import { OutputFormat } from "./OutputFormat"; 11 | import { ModelSpeed } from "./ModelSpeed"; 12 | 13 | export const TtsRequest: core.serialization.ObjectSchema = 14 | core.serialization.object({ 15 | modelId: core.serialization.property("model_id", core.serialization.string()), 16 | transcript: core.serialization.string(), 17 | voice: TtsRequestVoiceSpecifier, 18 | language: SupportedLanguage.optional(), 19 | outputFormat: core.serialization.property("output_format", OutputFormat), 20 | duration: core.serialization.number().optional(), 21 | speed: ModelSpeed.optional(), 22 | }); 23 | 24 | export declare namespace TtsRequest { 25 | export interface Raw { 26 | model_id: string; 27 | transcript: string; 28 | voice: TtsRequestVoiceSpecifier.Raw; 29 | language?: SupportedLanguage.Raw | null; 30 | output_format: OutputFormat.Raw; 31 | duration?: number | null; 32 | speed?: ModelSpeed.Raw | null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/TtsRequestEmbeddingSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { Embedding } from "../../embedding/types/Embedding"; 9 | import { Controls } from "./Controls"; 10 | 11 | export const TtsRequestEmbeddingSpecifier: core.serialization.ObjectSchema< 12 | serializers.TtsRequestEmbeddingSpecifier.Raw, 13 | Cartesia.TtsRequestEmbeddingSpecifier 14 | > = core.serialization.object({ 15 | mode: core.serialization.stringLiteral("embedding"), 16 | embedding: Embedding, 17 | experimentalControls: core.serialization.property("__experimental_controls", Controls.optional()), 18 | }); 19 | 20 | export declare namespace TtsRequestEmbeddingSpecifier { 21 | export interface Raw { 22 | mode: "embedding"; 23 | embedding: Embedding.Raw; 24 | __experimental_controls?: Controls.Raw | null; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/TtsRequestIdSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { VoiceId } from "../../voices/types/VoiceId"; 9 | import { Controls } from "./Controls"; 10 | 11 | export const TtsRequestIdSpecifier: core.serialization.ObjectSchema< 12 | serializers.TtsRequestIdSpecifier.Raw, 13 | Cartesia.TtsRequestIdSpecifier 14 | > = core.serialization.object({ 15 | mode: core.serialization.stringLiteral("id"), 16 | id: VoiceId, 17 | experimentalControls: core.serialization.property("__experimental_controls", Controls.optional()), 18 | }); 19 | 20 | export declare namespace TtsRequestIdSpecifier { 21 | export interface Raw { 22 | mode: "id"; 23 | id: VoiceId.Raw; 24 | __experimental_controls?: Controls.Raw | null; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/TtsRequestVoiceSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { TtsRequestIdSpecifier } from "./TtsRequestIdSpecifier"; 9 | import { TtsRequestEmbeddingSpecifier } from "./TtsRequestEmbeddingSpecifier"; 10 | 11 | export const TtsRequestVoiceSpecifier: core.serialization.Schema< 12 | serializers.TtsRequestVoiceSpecifier.Raw, 13 | Cartesia.TtsRequestVoiceSpecifier 14 | > = core.serialization.undiscriminatedUnion([TtsRequestIdSpecifier, TtsRequestEmbeddingSpecifier]); 15 | 16 | export declare namespace TtsRequestVoiceSpecifier { 17 | export type Raw = TtsRequestIdSpecifier.Raw | TtsRequestEmbeddingSpecifier.Raw; 18 | } 19 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WavOutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { RawOutputFormat } from "./RawOutputFormat"; 9 | 10 | export const WavOutputFormat: core.serialization.ObjectSchema< 11 | serializers.WavOutputFormat.Raw, 12 | Cartesia.WavOutputFormat 13 | > = core.serialization.object({}).extend(RawOutputFormat); 14 | 15 | export declare namespace WavOutputFormat { 16 | export interface Raw extends RawOutputFormat.Raw {} 17 | } 18 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketBaseResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { ContextId } from "./ContextId"; 9 | 10 | export const WebSocketBaseResponse: core.serialization.ObjectSchema< 11 | serializers.WebSocketBaseResponse.Raw, 12 | Cartesia.WebSocketBaseResponse 13 | > = core.serialization.object({ 14 | contextId: core.serialization.property("context_id", ContextId.optional()), 15 | statusCode: core.serialization.property("status_code", core.serialization.number()), 16 | done: core.serialization.boolean(), 17 | }); 18 | 19 | export declare namespace WebSocketBaseResponse { 20 | export interface Raw { 21 | context_id?: ContextId.Raw | null; 22 | status_code: number; 23 | done: boolean; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketChunkResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; 9 | 10 | export const WebSocketChunkResponse: core.serialization.ObjectSchema< 11 | serializers.WebSocketChunkResponse.Raw, 12 | Cartesia.WebSocketChunkResponse 13 | > = core.serialization 14 | .object({ 15 | data: core.serialization.string(), 16 | stepTime: core.serialization.property("step_time", core.serialization.number()), 17 | }) 18 | .extend(WebSocketBaseResponse); 19 | 20 | export declare namespace WebSocketChunkResponse { 21 | export interface Raw extends WebSocketBaseResponse.Raw { 22 | data: string; 23 | step_time: number; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketDoneResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; 9 | 10 | export const WebSocketDoneResponse: core.serialization.ObjectSchema< 11 | serializers.WebSocketDoneResponse.Raw, 12 | Cartesia.WebSocketDoneResponse 13 | > = core.serialization.object({}).extend(WebSocketBaseResponse); 14 | 15 | export declare namespace WebSocketDoneResponse { 16 | export interface Raw extends WebSocketBaseResponse.Raw {} 17 | } 18 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketErrorResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; 9 | 10 | export const WebSocketErrorResponse: core.serialization.ObjectSchema< 11 | serializers.WebSocketErrorResponse.Raw, 12 | Cartesia.WebSocketErrorResponse 13 | > = core.serialization 14 | .object({ 15 | error: core.serialization.string(), 16 | }) 17 | .extend(WebSocketBaseResponse); 18 | 19 | export declare namespace WebSocketErrorResponse { 20 | export interface Raw extends WebSocketBaseResponse.Raw { 21 | error: string; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketFlushDoneResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { FlushId } from "./FlushId"; 9 | import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; 10 | 11 | export const WebSocketFlushDoneResponse: core.serialization.ObjectSchema< 12 | serializers.WebSocketFlushDoneResponse.Raw, 13 | Cartesia.WebSocketFlushDoneResponse 14 | > = core.serialization 15 | .object({ 16 | flushId: core.serialization.property("flush_id", FlushId), 17 | flushDone: core.serialization.property("flush_done", core.serialization.boolean()), 18 | }) 19 | .extend(WebSocketBaseResponse); 20 | 21 | export declare namespace WebSocketFlushDoneResponse { 22 | export interface Raw extends WebSocketBaseResponse.Raw { 23 | flush_id: FlushId.Raw; 24 | flush_done: boolean; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketPhonemeTimestampsResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { PhonemeTimestamps } from "./PhonemeTimestamps"; 9 | import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; 10 | 11 | export const WebSocketPhonemeTimestampsResponse: core.serialization.ObjectSchema< 12 | serializers.WebSocketPhonemeTimestampsResponse.Raw, 13 | Cartesia.WebSocketPhonemeTimestampsResponse 14 | > = core.serialization 15 | .object({ 16 | phonemeTimestamps: core.serialization.property("phoneme_timestamps", PhonemeTimestamps.optional()), 17 | }) 18 | .extend(WebSocketBaseResponse); 19 | 20 | export declare namespace WebSocketPhonemeTimestampsResponse { 21 | export interface Raw extends WebSocketBaseResponse.Raw { 22 | phoneme_timestamps?: PhonemeTimestamps.Raw | null; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketRawOutputFormat.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { RawEncoding } from "./RawEncoding"; 9 | 10 | export const WebSocketRawOutputFormat: core.serialization.ObjectSchema< 11 | serializers.WebSocketRawOutputFormat.Raw, 12 | Cartesia.WebSocketRawOutputFormat 13 | > = core.serialization.object({ 14 | container: core.serialization.stringLiteral("raw"), 15 | encoding: RawEncoding, 16 | sampleRate: core.serialization.property("sample_rate", core.serialization.number()), 17 | }); 18 | 19 | export declare namespace WebSocketRawOutputFormat { 20 | export interface Raw { 21 | container: "raw"; 22 | encoding: RawEncoding.Raw; 23 | sample_rate: number; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { GenerationRequest } from "./GenerationRequest"; 9 | import { CancelContextRequest } from "./CancelContextRequest"; 10 | 11 | export const WebSocketRequest: core.serialization.Schema = 12 | core.serialization.undiscriminatedUnion([GenerationRequest, CancelContextRequest]); 13 | 14 | export declare namespace WebSocketRequest { 15 | export type Raw = GenerationRequest.Raw | CancelContextRequest.Raw; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { WebSocketChunkResponse } from "./WebSocketChunkResponse"; 9 | import { WebSocketFlushDoneResponse } from "./WebSocketFlushDoneResponse"; 10 | import { WebSocketDoneResponse } from "./WebSocketDoneResponse"; 11 | import { WebSocketTimestampsResponse } from "./WebSocketTimestampsResponse"; 12 | import { WebSocketErrorResponse } from "./WebSocketErrorResponse"; 13 | import { WebSocketPhonemeTimestampsResponse } from "./WebSocketPhonemeTimestampsResponse"; 14 | 15 | export const WebSocketResponse: core.serialization.Schema< 16 | serializers.WebSocketResponse.Raw, 17 | Cartesia.WebSocketResponse 18 | > = core.serialization 19 | .union("type", { 20 | chunk: WebSocketChunkResponse, 21 | flush_done: WebSocketFlushDoneResponse, 22 | done: WebSocketDoneResponse, 23 | timestamps: WebSocketTimestampsResponse, 24 | error: WebSocketErrorResponse, 25 | phoneme_timestamps: WebSocketPhonemeTimestampsResponse, 26 | }) 27 | .transform({ 28 | transform: (value) => value, 29 | untransform: (value) => value, 30 | }); 31 | 32 | export declare namespace WebSocketResponse { 33 | export type Raw = 34 | | WebSocketResponse.Chunk 35 | | WebSocketResponse.FlushDone 36 | | WebSocketResponse.Done 37 | | WebSocketResponse.Timestamps 38 | | WebSocketResponse.Error 39 | | WebSocketResponse.PhonemeTimestamps; 40 | 41 | export interface Chunk extends WebSocketChunkResponse.Raw { 42 | type: "chunk"; 43 | } 44 | 45 | export interface FlushDone extends WebSocketFlushDoneResponse.Raw { 46 | type: "flush_done"; 47 | } 48 | 49 | export interface Done extends WebSocketDoneResponse.Raw { 50 | type: "done"; 51 | } 52 | 53 | export interface Timestamps extends WebSocketTimestampsResponse.Raw { 54 | type: "timestamps"; 55 | } 56 | 57 | export interface Error extends WebSocketErrorResponse.Raw { 58 | type: "error"; 59 | } 60 | 61 | export interface PhonemeTimestamps extends WebSocketPhonemeTimestampsResponse.Raw { 62 | type: "phoneme_timestamps"; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketStreamOptions.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const WebSocketStreamOptions: core.serialization.ObjectSchema< 10 | serializers.WebSocketStreamOptions.Raw, 11 | Cartesia.WebSocketStreamOptions 12 | > = core.serialization.object({ 13 | timeout: core.serialization.number().optional(), 14 | }); 15 | 16 | export declare namespace WebSocketStreamOptions { 17 | export interface Raw { 18 | timeout?: number | null; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketTimestampsResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { WordTimestamps } from "./WordTimestamps"; 9 | import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; 10 | 11 | export const WebSocketTimestampsResponse: core.serialization.ObjectSchema< 12 | serializers.WebSocketTimestampsResponse.Raw, 13 | Cartesia.WebSocketTimestampsResponse 14 | > = core.serialization 15 | .object({ 16 | wordTimestamps: core.serialization.property("word_timestamps", WordTimestamps.optional()), 17 | }) 18 | .extend(WebSocketBaseResponse); 19 | 20 | export declare namespace WebSocketTimestampsResponse { 21 | export interface Raw extends WebSocketBaseResponse.Raw { 22 | word_timestamps?: WordTimestamps.Raw | null; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketTtsOutput.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { WordTimestamps } from "./WordTimestamps"; 9 | import { PhonemeTimestamps } from "./PhonemeTimestamps"; 10 | import { ContextId } from "./ContextId"; 11 | import { FlushId } from "./FlushId"; 12 | 13 | export const WebSocketTtsOutput: core.serialization.ObjectSchema< 14 | serializers.WebSocketTtsOutput.Raw, 15 | Cartesia.WebSocketTtsOutput 16 | > = core.serialization.object({ 17 | wordTimestamps: core.serialization.property("word_timestamps", WordTimestamps.optional()), 18 | phonemeTimestamps: core.serialization.property("phoneme_timestamps", PhonemeTimestamps.optional()), 19 | audio: core.serialization.unknown().optional(), 20 | contextId: core.serialization.property("context_id", ContextId.optional()), 21 | flushId: core.serialization.property("flush_id", FlushId.optional()), 22 | flushDone: core.serialization.property("flush_done", core.serialization.boolean().optional()), 23 | }); 24 | 25 | export declare namespace WebSocketTtsOutput { 26 | export interface Raw { 27 | word_timestamps?: WordTimestamps.Raw | null; 28 | phoneme_timestamps?: PhonemeTimestamps.Raw | null; 29 | audio?: unknown | null; 30 | context_id?: ContextId.Raw | null; 31 | flush_id?: FlushId.Raw | null; 32 | flush_done?: boolean | null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WebSocketTtsRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { OutputFormat } from "./OutputFormat"; 9 | import { TtsRequestVoiceSpecifier } from "./TtsRequestVoiceSpecifier"; 10 | import { ModelSpeed } from "./ModelSpeed"; 11 | 12 | export const WebSocketTtsRequest: core.serialization.ObjectSchema< 13 | serializers.WebSocketTtsRequest.Raw, 14 | Cartesia.WebSocketTtsRequest 15 | > = core.serialization.object({ 16 | modelId: core.serialization.property("model_id", core.serialization.string()), 17 | outputFormat: core.serialization.property("output_format", OutputFormat.optional()), 18 | transcript: core.serialization.string().optional(), 19 | voice: TtsRequestVoiceSpecifier, 20 | duration: core.serialization.number().optional(), 21 | language: core.serialization.string().optional(), 22 | addTimestamps: core.serialization.property("add_timestamps", core.serialization.boolean().optional()), 23 | addPhonemeTimestamps: core.serialization.property( 24 | "add_phoneme_timestamps", 25 | core.serialization.boolean().optional(), 26 | ), 27 | useOriginalTimestamps: core.serialization.property( 28 | "use_original_timestamps", 29 | core.serialization.boolean().optional(), 30 | ), 31 | continue: core.serialization.boolean().optional(), 32 | contextId: core.serialization.property("context_id", core.serialization.string().optional()), 33 | maxBufferDelayMs: core.serialization.property("max_buffer_delay_ms", core.serialization.number().optional()), 34 | speed: ModelSpeed.optional(), 35 | }); 36 | 37 | export declare namespace WebSocketTtsRequest { 38 | export interface Raw { 39 | model_id: string; 40 | output_format?: OutputFormat.Raw | null; 41 | transcript?: string | null; 42 | voice: TtsRequestVoiceSpecifier.Raw; 43 | duration?: number | null; 44 | language?: string | null; 45 | add_timestamps?: boolean | null; 46 | add_phoneme_timestamps?: boolean | null; 47 | use_original_timestamps?: boolean | null; 48 | continue?: boolean | null; 49 | context_id?: string | null; 50 | max_buffer_delay_ms?: number | null; 51 | speed?: ModelSpeed.Raw | null; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/WordTimestamps.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const WordTimestamps: core.serialization.ObjectSchema = 10 | core.serialization.object({ 11 | words: core.serialization.list(core.serialization.string()), 12 | start: core.serialization.list(core.serialization.number()), 13 | end: core.serialization.list(core.serialization.number()), 14 | }); 15 | 16 | export declare namespace WordTimestamps { 17 | export interface Raw { 18 | words: string[]; 19 | start: number[]; 20 | end: number[]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/serialization/resources/tts/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./ContextId"; 2 | export * from "./FlushId"; 3 | export * from "./ModelSpeed"; 4 | export * from "./WebSocketBaseResponse"; 5 | export * from "./WebSocketResponse"; 6 | export * from "./WebSocketErrorResponse"; 7 | export * from "./WebSocketChunkResponse"; 8 | export * from "./WebSocketTimestampsResponse"; 9 | export * from "./WebSocketPhonemeTimestampsResponse"; 10 | export * from "./WebSocketTtsOutput"; 11 | export * from "./WebSocketStreamOptions"; 12 | export * from "./WordTimestamps"; 13 | export * from "./PhonemeTimestamps"; 14 | export * from "./WebSocketDoneResponse"; 15 | export * from "./WebSocketFlushDoneResponse"; 16 | export * from "./CancelContextRequest"; 17 | export * from "./GenerationRequest"; 18 | export * from "./WebSocketRawOutputFormat"; 19 | export * from "./WebSocketRequest"; 20 | export * from "./WebSocketTtsRequest"; 21 | export * from "./TtsRequest"; 22 | export * from "./SupportedLanguage"; 23 | export * from "./OutputFormat"; 24 | export * from "./RawOutputFormat"; 25 | export * from "./RawEncoding"; 26 | export * from "./WavOutputFormat"; 27 | export * from "./Mp3OutputFormat"; 28 | export * from "./TtsRequestVoiceSpecifier"; 29 | export * from "./TtsRequestIdSpecifier"; 30 | export * from "./TtsRequestEmbeddingSpecifier"; 31 | export * from "./Controls"; 32 | export * from "./Speed"; 33 | export * from "./NumericalSpecifier"; 34 | export * from "./NaturalSpecifier"; 35 | export * from "./Emotion"; 36 | -------------------------------------------------------------------------------- /src/serialization/resources/voiceChanger/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/voiceChanger/types/OutputFormatContainer.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const OutputFormatContainer: core.serialization.Schema< 10 | serializers.OutputFormatContainer.Raw, 11 | Cartesia.OutputFormatContainer 12 | > = core.serialization.enum_(["raw", "wav", "mp3"]); 13 | 14 | export declare namespace OutputFormatContainer { 15 | export type Raw = "raw" | "wav" | "mp3"; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/voiceChanger/types/StreamingResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { WebSocketChunkResponse } from "../../tts/types/WebSocketChunkResponse"; 9 | import { WebSocketDoneResponse } from "../../tts/types/WebSocketDoneResponse"; 10 | import { WebSocketErrorResponse } from "../../tts/types/WebSocketErrorResponse"; 11 | 12 | export const StreamingResponse: core.serialization.Schema< 13 | serializers.StreamingResponse.Raw, 14 | Cartesia.StreamingResponse 15 | > = core.serialization 16 | .union("type", { 17 | chunk: WebSocketChunkResponse, 18 | done: WebSocketDoneResponse, 19 | error: WebSocketErrorResponse, 20 | }) 21 | .transform({ 22 | transform: (value) => value, 23 | untransform: (value) => value, 24 | }); 25 | 26 | export declare namespace StreamingResponse { 27 | export type Raw = StreamingResponse.Chunk | StreamingResponse.Done | StreamingResponse.Error; 28 | 29 | export interface Chunk extends WebSocketChunkResponse.Raw { 30 | type: "chunk"; 31 | } 32 | 33 | export interface Done extends WebSocketDoneResponse.Raw { 34 | type: "done"; 35 | } 36 | 37 | export interface Error extends WebSocketErrorResponse.Raw { 38 | type: "error"; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/serialization/resources/voiceChanger/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./OutputFormatContainer"; 2 | export * from "./StreamingResponse"; 3 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/client/index.ts: -------------------------------------------------------------------------------- 1 | export * as list from "./list"; 2 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/client/list.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { Voice } from "../types/Voice"; 9 | 10 | export const Response: core.serialization.Schema = 11 | core.serialization.list(Voice); 12 | 13 | export declare namespace Response { 14 | export type Raw = Voice.Raw[]; 15 | } 16 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./types"; 2 | export * from "./client"; 3 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/BaseVoiceId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { VoiceId } from "./VoiceId"; 9 | 10 | export const BaseVoiceId: core.serialization.Schema = VoiceId; 11 | 12 | export declare namespace BaseVoiceId { 13 | export type Raw = VoiceId.Raw; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/CloneMode.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const CloneMode: core.serialization.Schema = 10 | core.serialization.enum_(["similarity", "stability"]); 11 | 12 | export declare namespace CloneMode { 13 | export type Raw = "similarity" | "stability"; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/CreateVoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { Embedding } from "../../embedding/types/Embedding"; 9 | import { SupportedLanguage } from "../../tts/types/SupportedLanguage"; 10 | import { BaseVoiceId } from "./BaseVoiceId"; 11 | 12 | export const CreateVoiceRequest: core.serialization.ObjectSchema< 13 | serializers.CreateVoiceRequest.Raw, 14 | Cartesia.CreateVoiceRequest 15 | > = core.serialization.object({ 16 | name: core.serialization.string(), 17 | description: core.serialization.string(), 18 | embedding: Embedding, 19 | language: SupportedLanguage.optional(), 20 | baseVoiceId: core.serialization.property("base_voice_id", BaseVoiceId.optional()), 21 | }); 22 | 23 | export declare namespace CreateVoiceRequest { 24 | export interface Raw { 25 | name: string; 26 | description: string; 27 | embedding: Embedding.Raw; 28 | language?: SupportedLanguage.Raw | null; 29 | base_voice_id?: BaseVoiceId.Raw | null; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/EmbeddingResponse.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { Embedding } from "../../embedding/types/Embedding"; 9 | 10 | export const EmbeddingResponse: core.serialization.ObjectSchema< 11 | serializers.EmbeddingResponse.Raw, 12 | Cartesia.EmbeddingResponse 13 | > = core.serialization.object({ 14 | embedding: Embedding, 15 | }); 16 | 17 | export declare namespace EmbeddingResponse { 18 | export interface Raw { 19 | embedding: Embedding.Raw; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/EmbeddingSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { Embedding } from "../../embedding/types/Embedding"; 9 | import { Weight } from "./Weight"; 10 | 11 | export const EmbeddingSpecifier: core.serialization.ObjectSchema< 12 | serializers.EmbeddingSpecifier.Raw, 13 | Cartesia.EmbeddingSpecifier 14 | > = core.serialization.object({ 15 | embedding: Embedding, 16 | weight: Weight, 17 | }); 18 | 19 | export declare namespace EmbeddingSpecifier { 20 | export interface Raw { 21 | embedding: Embedding.Raw; 22 | weight: Weight.Raw; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/Gender.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const Gender: core.serialization.Schema = core.serialization.enum_([ 10 | "male", 11 | "female", 12 | ]); 13 | 14 | export declare namespace Gender { 15 | export type Raw = "male" | "female"; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/IdSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { VoiceId } from "./VoiceId"; 9 | import { Weight } from "./Weight"; 10 | 11 | export const IdSpecifier: core.serialization.ObjectSchema = 12 | core.serialization.object({ 13 | id: VoiceId, 14 | weight: Weight, 15 | }); 16 | 17 | export declare namespace IdSpecifier { 18 | export interface Raw { 19 | id: VoiceId.Raw; 20 | weight: Weight.Raw; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/LocalizeDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { LocalizeEnglishDialect } from "./LocalizeEnglishDialect"; 9 | import { LocalizeSpanishDialect } from "./LocalizeSpanishDialect"; 10 | import { LocalizePortugueseDialect } from "./LocalizePortugueseDialect"; 11 | import { LocalizeFrenchDialect } from "./LocalizeFrenchDialect"; 12 | 13 | export const LocalizeDialect: core.serialization.Schema = 14 | core.serialization.undiscriminatedUnion([ 15 | LocalizeEnglishDialect, 16 | LocalizeSpanishDialect, 17 | LocalizePortugueseDialect, 18 | LocalizeFrenchDialect, 19 | ]); 20 | 21 | export declare namespace LocalizeDialect { 22 | export type Raw = 23 | | LocalizeEnglishDialect.Raw 24 | | LocalizeSpanishDialect.Raw 25 | | LocalizePortugueseDialect.Raw 26 | | LocalizeFrenchDialect.Raw; 27 | } 28 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/LocalizeEnglishDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const LocalizeEnglishDialect: core.serialization.Schema< 10 | serializers.LocalizeEnglishDialect.Raw, 11 | Cartesia.LocalizeEnglishDialect 12 | > = core.serialization.enum_(["au", "in", "so", "uk", "us"]); 13 | 14 | export declare namespace LocalizeEnglishDialect { 15 | export type Raw = "au" | "in" | "so" | "uk" | "us"; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/LocalizeFrenchDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const LocalizeFrenchDialect: core.serialization.Schema< 10 | serializers.LocalizeFrenchDialect.Raw, 11 | Cartesia.LocalizeFrenchDialect 12 | > = core.serialization.enum_(["eu", "ca"]); 13 | 14 | export declare namespace LocalizeFrenchDialect { 15 | export type Raw = "eu" | "ca"; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/LocalizePortugueseDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const LocalizePortugueseDialect: core.serialization.Schema< 10 | serializers.LocalizePortugueseDialect.Raw, 11 | Cartesia.LocalizePortugueseDialect 12 | > = core.serialization.enum_(["br", "eu"]); 13 | 14 | export declare namespace LocalizePortugueseDialect { 15 | export type Raw = "br" | "eu"; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/LocalizeSpanishDialect.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const LocalizeSpanishDialect: core.serialization.Schema< 10 | serializers.LocalizeSpanishDialect.Raw, 11 | Cartesia.LocalizeSpanishDialect 12 | > = core.serialization.enum_(["mx", "pe"]); 13 | 14 | export declare namespace LocalizeSpanishDialect { 15 | export type Raw = "mx" | "pe"; 16 | } 17 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/LocalizeTargetLanguage.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const LocalizeTargetLanguage: core.serialization.Schema< 10 | serializers.LocalizeTargetLanguage.Raw, 11 | Cartesia.LocalizeTargetLanguage 12 | > = core.serialization.enum_([ 13 | "en", 14 | "de", 15 | "es", 16 | "fr", 17 | "ja", 18 | "pt", 19 | "zh", 20 | "hi", 21 | "it", 22 | "ko", 23 | "nl", 24 | "pl", 25 | "ru", 26 | "sv", 27 | "tr", 28 | ]); 29 | 30 | export declare namespace LocalizeTargetLanguage { 31 | export type Raw = 32 | | "en" 33 | | "de" 34 | | "es" 35 | | "fr" 36 | | "ja" 37 | | "pt" 38 | | "zh" 39 | | "hi" 40 | | "it" 41 | | "ko" 42 | | "nl" 43 | | "pl" 44 | | "ru" 45 | | "sv" 46 | | "tr"; 47 | } 48 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/LocalizeVoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { LocalizeTargetLanguage } from "./LocalizeTargetLanguage"; 9 | import { Gender } from "./Gender"; 10 | import { LocalizeDialect } from "./LocalizeDialect"; 11 | 12 | export const LocalizeVoiceRequest: core.serialization.ObjectSchema< 13 | serializers.LocalizeVoiceRequest.Raw, 14 | Cartesia.LocalizeVoiceRequest 15 | > = core.serialization.object({ 16 | voiceId: core.serialization.property("voice_id", core.serialization.string()), 17 | name: core.serialization.string(), 18 | description: core.serialization.string(), 19 | language: LocalizeTargetLanguage, 20 | originalSpeakerGender: core.serialization.property("original_speaker_gender", Gender), 21 | dialect: LocalizeDialect.optional(), 22 | }); 23 | 24 | export declare namespace LocalizeVoiceRequest { 25 | export interface Raw { 26 | voice_id: string; 27 | name: string; 28 | description: string; 29 | language: LocalizeTargetLanguage.Raw; 30 | original_speaker_gender: Gender.Raw; 31 | dialect?: LocalizeDialect.Raw | null; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/MixVoiceSpecifier.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { IdSpecifier } from "./IdSpecifier"; 9 | import { EmbeddingSpecifier } from "./EmbeddingSpecifier"; 10 | 11 | export const MixVoiceSpecifier: core.serialization.Schema< 12 | serializers.MixVoiceSpecifier.Raw, 13 | Cartesia.MixVoiceSpecifier 14 | > = core.serialization.undiscriminatedUnion([IdSpecifier, EmbeddingSpecifier]); 15 | 16 | export declare namespace MixVoiceSpecifier { 17 | export type Raw = IdSpecifier.Raw | EmbeddingSpecifier.Raw; 18 | } 19 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/MixVoicesRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { MixVoiceSpecifier } from "./MixVoiceSpecifier"; 9 | 10 | export const MixVoicesRequest: core.serialization.ObjectSchema< 11 | serializers.MixVoicesRequest.Raw, 12 | Cartesia.MixVoicesRequest 13 | > = core.serialization.object({ 14 | voices: core.serialization.list(MixVoiceSpecifier), 15 | }); 16 | 17 | export declare namespace MixVoicesRequest { 18 | export interface Raw { 19 | voices: MixVoiceSpecifier.Raw[]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/UpdateVoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const UpdateVoiceRequest: core.serialization.ObjectSchema< 10 | serializers.UpdateVoiceRequest.Raw, 11 | Cartesia.UpdateVoiceRequest 12 | > = core.serialization.object({ 13 | name: core.serialization.string(), 14 | description: core.serialization.string(), 15 | }); 16 | 17 | export declare namespace UpdateVoiceRequest { 18 | export interface Raw { 19 | name: string; 20 | description: string; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/Voice.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { VoiceId } from "./VoiceId"; 9 | import { Embedding } from "../../embedding/types/Embedding"; 10 | import { SupportedLanguage } from "../../tts/types/SupportedLanguage"; 11 | 12 | export const Voice: core.serialization.ObjectSchema = core.serialization.object({ 13 | id: VoiceId, 14 | userId: core.serialization.property("user_id", core.serialization.string().optional()), 15 | isPublic: core.serialization.property("is_public", core.serialization.boolean()), 16 | name: core.serialization.string(), 17 | description: core.serialization.string(), 18 | createdAt: core.serialization.property("created_at", core.serialization.date()), 19 | embedding: Embedding, 20 | language: SupportedLanguage, 21 | }); 22 | 23 | export declare namespace Voice { 24 | export interface Raw { 25 | id: VoiceId.Raw; 26 | user_id?: string | null; 27 | is_public: boolean; 28 | name: string; 29 | description: string; 30 | created_at: string; 31 | embedding: Embedding.Raw; 32 | language: SupportedLanguage.Raw; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/VoiceId.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const VoiceId: core.serialization.Schema = 10 | core.serialization.string(); 11 | 12 | export declare namespace VoiceId { 13 | export type Raw = string; 14 | } 15 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/VoiceMetadata.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | import { VoiceId } from "./VoiceId"; 9 | import { SupportedLanguage } from "../../tts/types/SupportedLanguage"; 10 | 11 | export const VoiceMetadata: core.serialization.ObjectSchema = 12 | core.serialization.object({ 13 | id: VoiceId, 14 | userId: core.serialization.property("user_id", core.serialization.string()), 15 | isPublic: core.serialization.property("is_public", core.serialization.boolean()), 16 | name: core.serialization.string(), 17 | description: core.serialization.string(), 18 | createdAt: core.serialization.property("created_at", core.serialization.date()), 19 | language: SupportedLanguage, 20 | }); 21 | 22 | export declare namespace VoiceMetadata { 23 | export interface Raw { 24 | id: VoiceId.Raw; 25 | user_id: string; 26 | is_public: boolean; 27 | name: string; 28 | description: string; 29 | created_at: string; 30 | language: SupportedLanguage.Raw; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/Weight.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was auto-generated by Fern from our API Definition. 3 | */ 4 | 5 | import * as serializers from "../../../index"; 6 | import * as Cartesia from "../../../../api/index"; 7 | import * as core from "../../../../core"; 8 | 9 | export const Weight: core.serialization.Schema = core.serialization.number(); 10 | 11 | export declare namespace Weight { 12 | export type Raw = number; 13 | } 14 | -------------------------------------------------------------------------------- /src/serialization/resources/voices/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./VoiceId"; 2 | export * from "./BaseVoiceId"; 3 | export * from "./Voice"; 4 | export * from "./VoiceMetadata"; 5 | export * from "./CreateVoiceRequest"; 6 | export * from "./UpdateVoiceRequest"; 7 | export * from "./LocalizeTargetLanguage"; 8 | export * from "./LocalizeEnglishDialect"; 9 | export * from "./LocalizeFrenchDialect"; 10 | export * from "./LocalizeSpanishDialect"; 11 | export * from "./LocalizePortugueseDialect"; 12 | export * from "./LocalizeDialect"; 13 | export * from "./Gender"; 14 | export * from "./LocalizeVoiceRequest"; 15 | export * from "./EmbeddingResponse"; 16 | export * from "./MixVoicesRequest"; 17 | export * from "./Weight"; 18 | export * from "./IdSpecifier"; 19 | export * from "./EmbeddingSpecifier"; 20 | export * from "./MixVoiceSpecifier"; 21 | export * from "./CloneMode"; 22 | -------------------------------------------------------------------------------- /src/version.ts: -------------------------------------------------------------------------------- 1 | export const SDK_VERSION = "2.2.3"; 2 | -------------------------------------------------------------------------------- /src/wrapper/Client.ts: -------------------------------------------------------------------------------- 1 | import { CartesiaClient as FernCartesiaClient } from "../Client"; 2 | import { StreamingTTSClient } from "./StreamingTTSClient"; 3 | 4 | export class CartesiaClient extends FernCartesiaClient { 5 | protected _tts: StreamingTTSClient | undefined; 6 | 7 | public get tts(): StreamingTTSClient { 8 | return (this._tts ??= new StreamingTTSClient(this._options)); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/wrapper/StreamingTTSClient.ts: -------------------------------------------------------------------------------- 1 | import { Tts } from "../api/resources/tts/client/Client"; 2 | import Websocket from "./Websocket"; 3 | 4 | export class StreamingTTSClient extends Tts { 5 | constructor(options: Tts.Options = {}) { 6 | super(options); 7 | } 8 | 9 | /** 10 | * Get a WebSocket client for streaming TTS. 11 | * 12 | * @param options - Options for the WebSocket client. 13 | * @returns A WebSocket client configured for streaming TTS. 14 | */ 15 | websocket({ 16 | sampleRate, 17 | container, 18 | encoding, 19 | }: { 20 | sampleRate: number; 21 | container?: string; 22 | encoding?: string; 23 | }): Websocket { 24 | return new Websocket({ sampleRate, container, encoding }, { cartesiaVersion: "2024-06-10", ...this._options }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tests/custom.test.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This is a custom test file, if you wish to add more tests 3 | * to your SDK. 4 | * Be sure to mark this file in `.fernignore`. 5 | * 6 | * If you include example requests/responses in your fern definition, 7 | * you will have tests automatically generated for you. 8 | */ 9 | describe("test", () => { 10 | it("default", () => { 11 | expect(true).toBe(true); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /tests/unit/fetcher/createRequestUrl.test.ts: -------------------------------------------------------------------------------- 1 | import { createRequestUrl } from "../../../src/core/fetcher/createRequestUrl"; 2 | 3 | describe("Test createRequestUrl", () => { 4 | it("should return the base URL when no query parameters are provided", () => { 5 | const baseUrl = "https://api.example.com"; 6 | expect(createRequestUrl(baseUrl)).toBe(baseUrl); 7 | }); 8 | 9 | it("should append simple query parameters", () => { 10 | const baseUrl = "https://api.example.com"; 11 | const queryParams = { key: "value", another: "param" }; 12 | expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?key=value&another=param"); 13 | }); 14 | 15 | it("should handle array query parameters", () => { 16 | const baseUrl = "https://api.example.com"; 17 | const queryParams = { items: ["a", "b", "c"] }; 18 | expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?items=a&items=b&items=c"); 19 | }); 20 | 21 | it("should handle object query parameters", () => { 22 | const baseUrl = "https://api.example.com"; 23 | const queryParams = { filter: { name: "John", age: 30 } }; 24 | expect(createRequestUrl(baseUrl, queryParams)).toBe( 25 | "https://api.example.com?filter%5Bname%5D=John&filter%5Bage%5D=30", 26 | ); 27 | }); 28 | 29 | it("should handle mixed types of query parameters", () => { 30 | const baseUrl = "https://api.example.com"; 31 | const queryParams = { 32 | simple: "value", 33 | array: ["x", "y"], 34 | object: { key: "value" }, 35 | }; 36 | expect(createRequestUrl(baseUrl, queryParams)).toBe( 37 | "https://api.example.com?simple=value&array=x&array=y&object%5Bkey%5D=value", 38 | ); 39 | }); 40 | 41 | it("should handle empty query parameters object", () => { 42 | const baseUrl = "https://api.example.com"; 43 | expect(createRequestUrl(baseUrl, {})).toBe(baseUrl); 44 | }); 45 | 46 | it("should encode special characters in query parameters", () => { 47 | const baseUrl = "https://api.example.com"; 48 | const queryParams = { special: "a&b=c d" }; 49 | expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?special=a%26b%3Dc%20d"); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /tests/unit/fetcher/getFetchFn.test.ts: -------------------------------------------------------------------------------- 1 | import { RUNTIME } from "../../../src/core/runtime"; 2 | import { getFetchFn } from "../../../src/core/fetcher/getFetchFn"; 3 | 4 | describe("Test for getFetchFn", () => { 5 | it("should get node-fetch function", async () => { 6 | if (RUNTIME.type == "node") { 7 | if (RUNTIME.parsedVersion != null && RUNTIME.parsedVersion >= 18) { 8 | expect(await getFetchFn()).toBe(fetch); 9 | } else { 10 | expect(await getFetchFn()).toEqual((await import("node-fetch")).default as any); 11 | } 12 | } 13 | }); 14 | 15 | it("should get fetch function", async () => { 16 | if (RUNTIME.type == "browser") { 17 | const fetchFn = await getFetchFn(); 18 | expect(typeof fetchFn).toBe("function"); 19 | expect(fetchFn.name).toBe("fetch"); 20 | } 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /tests/unit/fetcher/makeRequest.test.ts: -------------------------------------------------------------------------------- 1 | import { makeRequest } from "../../../src/core/fetcher/makeRequest"; 2 | 3 | describe("Test makeRequest", () => { 4 | const mockPostUrl = "https://httpbin.org/post"; 5 | const mockGetUrl = "https://httpbin.org/get"; 6 | const mockHeaders = { "Content-Type": "application/json" }; 7 | const mockBody = JSON.stringify({ key: "value" }); 8 | 9 | let mockFetch: jest.Mock; 10 | 11 | beforeEach(() => { 12 | mockFetch = jest.fn(); 13 | mockFetch.mockResolvedValue(new Response(JSON.stringify({ test: "successful" }), { status: 200 })); 14 | }); 15 | 16 | it("should handle POST request correctly", async () => { 17 | const response = await makeRequest(mockFetch, mockPostUrl, "POST", mockHeaders, mockBody); 18 | const responseBody = await response.json(); 19 | expect(responseBody).toEqual({ test: "successful" }); 20 | expect(mockFetch).toHaveBeenCalledTimes(1); 21 | const [calledUrl, calledOptions] = mockFetch.mock.calls[0]; 22 | expect(calledUrl).toBe(mockPostUrl); 23 | expect(calledOptions).toEqual( 24 | expect.objectContaining({ 25 | method: "POST", 26 | headers: mockHeaders, 27 | body: mockBody, 28 | credentials: undefined, 29 | }), 30 | ); 31 | expect(calledOptions.signal).toBeDefined(); 32 | expect(calledOptions.signal).toBeInstanceOf(AbortSignal); 33 | }); 34 | 35 | it("should handle GET request correctly", async () => { 36 | const response = await makeRequest(mockFetch, mockGetUrl, "GET", mockHeaders, undefined); 37 | const responseBody = await response.json(); 38 | expect(responseBody).toEqual({ test: "successful" }); 39 | expect(mockFetch).toHaveBeenCalledTimes(1); 40 | const [calledUrl, calledOptions] = mockFetch.mock.calls[0]; 41 | expect(calledUrl).toBe(mockGetUrl); 42 | expect(calledOptions).toEqual( 43 | expect.objectContaining({ 44 | method: "GET", 45 | headers: mockHeaders, 46 | body: undefined, 47 | credentials: undefined, 48 | }), 49 | ); 50 | expect(calledOptions.signal).toBeDefined(); 51 | expect(calledOptions.signal).toBeInstanceOf(AbortSignal); 52 | }); 53 | }); 54 | -------------------------------------------------------------------------------- /tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts: -------------------------------------------------------------------------------- 1 | import { RUNTIME } from "../../../../src/core/runtime"; 2 | import { Node18UniversalStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper"; 3 | import { NodePre18StreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/NodePre18StreamWrapper"; 4 | import { UndiciStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/UndiciStreamWrapper"; 5 | import { chooseStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/chooseStreamWrapper"; 6 | 7 | describe("chooseStreamWrapper", () => { 8 | beforeEach(() => { 9 | RUNTIME.type = "unknown"; 10 | RUNTIME.parsedVersion = 0; 11 | }); 12 | 13 | it('should return a Node18UniversalStreamWrapper when RUNTIME.type is "node" and RUNTIME.parsedVersion is not null and RUNTIME.parsedVersion is greater than or equal to 18', async () => { 14 | const expected = new Node18UniversalStreamWrapper(new ReadableStream()); 15 | RUNTIME.type = "node"; 16 | RUNTIME.parsedVersion = 18; 17 | 18 | const result = await chooseStreamWrapper(new ReadableStream()); 19 | 20 | expect(JSON.stringify(result)).toBe(JSON.stringify(expected)); 21 | }); 22 | 23 | it('should return a NodePre18StreamWrapper when RUNTIME.type is "node" and RUNTIME.parsedVersion is not null and RUNTIME.parsedVersion is less than 18', async () => { 24 | const stream = await import("readable-stream"); 25 | const expected = new NodePre18StreamWrapper(new stream.Readable()); 26 | 27 | RUNTIME.type = "node"; 28 | RUNTIME.parsedVersion = 16; 29 | 30 | const result = await chooseStreamWrapper(new stream.Readable()); 31 | 32 | expect(JSON.stringify(result)).toEqual(JSON.stringify(expected)); 33 | }); 34 | 35 | it('should return a Undici when RUNTIME.type is not "node"', async () => { 36 | const expected = new UndiciStreamWrapper(new ReadableStream()); 37 | RUNTIME.type = "browser"; 38 | 39 | const result = await chooseStreamWrapper(new ReadableStream()); 40 | 41 | expect(JSON.stringify(result)).toEqual(JSON.stringify(expected)); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /tests/unit/fetcher/stream-wrappers/webpack.test.ts: -------------------------------------------------------------------------------- 1 | import webpack from "webpack"; 2 | 3 | describe("test env compatibility", () => { 4 | test("webpack", () => { 5 | return new Promise((resolve, reject) => { 6 | webpack( 7 | { 8 | mode: "production", 9 | entry: "./src/index.ts", 10 | module: { 11 | rules: [ 12 | { 13 | test: /\.tsx?$/, 14 | use: "ts-loader", 15 | exclude: /node_modules/, 16 | }, 17 | ], 18 | }, 19 | resolve: { 20 | extensions: [".tsx", ".ts", ".jsx", ".js"], 21 | extensionAlias: { 22 | ".js": [".ts", ".js"], 23 | ".jsx": [".tsx", ".jsx"], 24 | }, 25 | }, 26 | }, 27 | (err, stats) => { 28 | try { 29 | expect(err).toBe(null); 30 | if (stats?.hasErrors()) { 31 | console.log(stats?.toString()); 32 | } 33 | expect(stats?.hasErrors()).toBe(false); 34 | resolve(); 35 | } catch (error) { 36 | reject(error); 37 | } 38 | }, 39 | ); 40 | }); 41 | }, 60_000); 42 | }); 43 | -------------------------------------------------------------------------------- /tests/unit/fetcher/test-file.txt: -------------------------------------------------------------------------------- 1 | This is a test file! 2 | -------------------------------------------------------------------------------- /tests/unit/zurg/bigint/bigint.test.ts: -------------------------------------------------------------------------------- 1 | import { bigint } from "../../../../src/core/schemas/builders/bigint"; 2 | import { itJson, itParse, itSchema } from "../utils/itSchema"; 3 | import { itValidateJson, itValidateParse } from "../utils/itValidate"; 4 | 5 | describe("bigint", () => { 6 | itSchema("converts between raw bigint and parsed bigint", bigint(), { 7 | raw: BigInt("9007199254740992"), 8 | parsed: BigInt("9007199254740992"), 9 | }); 10 | 11 | itParse("converts between raw number and parsed bigint", bigint(), { 12 | raw: 10, 13 | parsed: BigInt("10"), 14 | }); 15 | 16 | itParse("converts between raw number and parsed bigint", bigint(), { 17 | raw: BigInt("10"), 18 | parsed: BigInt("10"), 19 | }); 20 | 21 | itJson("converts raw bigint to parsed bigint", bigint(), { 22 | parsed: BigInt("10"), 23 | raw: BigInt("10"), 24 | }); 25 | 26 | itValidateParse("string", bigint(), "42", [ 27 | { 28 | message: 'Expected bigint | number. Received "42".', 29 | path: [], 30 | }, 31 | ]); 32 | 33 | itValidateJson("number", bigint(), 42, [ 34 | { 35 | message: "Expected bigint. Received 42.", 36 | path: [], 37 | }, 38 | ]); 39 | 40 | itValidateJson("string", bigint(), "42", [ 41 | { 42 | message: 'Expected bigint. Received "42".', 43 | path: [], 44 | }, 45 | ]); 46 | }); 47 | -------------------------------------------------------------------------------- /tests/unit/zurg/date/date.test.ts: -------------------------------------------------------------------------------- 1 | import { date } from "../../../../src/core/schemas/builders/date"; 2 | import { itSchema } from "../utils/itSchema"; 3 | import { itValidateJson, itValidateParse } from "../utils/itValidate"; 4 | 5 | describe("date", () => { 6 | itSchema("converts between raw ISO string and parsed Date", date(), { 7 | raw: "2022-09-29T05:41:21.939Z", 8 | parsed: new Date("2022-09-29T05:41:21.939Z"), 9 | }); 10 | 11 | itValidateParse("non-string", date(), 42, [ 12 | { 13 | message: "Expected string. Received 42.", 14 | path: [], 15 | }, 16 | ]); 17 | 18 | itValidateParse("non-ISO", date(), "hello world", [ 19 | { 20 | message: 'Expected ISO 8601 date string. Received "hello world".', 21 | path: [], 22 | }, 23 | ]); 24 | 25 | itValidateJson("non-Date", date(), "hello", [ 26 | { 27 | message: 'Expected Date object. Received "hello".', 28 | path: [], 29 | }, 30 | ]); 31 | }); 32 | -------------------------------------------------------------------------------- /tests/unit/zurg/enum/enum.test.ts: -------------------------------------------------------------------------------- 1 | import { enum_ } from "../../../../src/core/schemas/builders/enum"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | import { itValidate } from "../utils/itValidate"; 4 | 5 | describe("enum", () => { 6 | itSchemaIdentity(enum_(["A", "B", "C"]), "A"); 7 | 8 | itSchemaIdentity(enum_(["A", "B", "C"]), "D" as any, { 9 | opts: { allowUnrecognizedEnumValues: true }, 10 | }); 11 | 12 | itValidate("invalid enum", enum_(["A", "B", "C"]), "D", [ 13 | { 14 | message: 'Expected enum. Received "D".', 15 | path: [], 16 | }, 17 | ]); 18 | 19 | itValidate( 20 | "non-string", 21 | enum_(["A", "B", "C"]), 22 | [], 23 | [ 24 | { 25 | message: "Expected string. Received list.", 26 | path: [], 27 | }, 28 | ], 29 | ); 30 | }); 31 | -------------------------------------------------------------------------------- /tests/unit/zurg/lazy/lazy.test.ts: -------------------------------------------------------------------------------- 1 | import { Schema } from "../../../../src/core/schemas/Schema"; 2 | import { lazy, list, object, string } from "../../../../src/core/schemas/builders"; 3 | import { itSchemaIdentity } from "../utils/itSchema"; 4 | 5 | describe("lazy", () => { 6 | it("doesn't run immediately", () => { 7 | let wasRun = false; 8 | lazy(() => { 9 | wasRun = true; 10 | return string(); 11 | }); 12 | expect(wasRun).toBe(false); 13 | }); 14 | 15 | it("only runs first time", async () => { 16 | let count = 0; 17 | const schema = lazy(() => { 18 | count++; 19 | return string(); 20 | }); 21 | await schema.parse("hello"); 22 | await schema.json("world"); 23 | expect(count).toBe(1); 24 | }); 25 | 26 | itSchemaIdentity( 27 | lazy(() => object({})), 28 | { foo: "hello" }, 29 | { 30 | title: "passes opts through", 31 | opts: { unrecognizedObjectKeys: "passthrough" }, 32 | }, 33 | ); 34 | 35 | itSchemaIdentity( 36 | lazy(() => object({ foo: string() })), 37 | { foo: "hello" }, 38 | ); 39 | 40 | // eslint-disable-next-line jest/expect-expect 41 | it("self-referencial schema doesn't compile", () => { 42 | () => { 43 | // @ts-expect-error 44 | const a = lazy(() => object({ foo: a })); 45 | }; 46 | }); 47 | 48 | // eslint-disable-next-line jest/expect-expect 49 | it("self-referencial compiles with explicit type", () => { 50 | () => { 51 | interface TreeNode { 52 | children: TreeNode[]; 53 | } 54 | const TreeNode: Schema = lazy(() => object({ children: list(TreeNode) })); 55 | }; 56 | }); 57 | }); 58 | -------------------------------------------------------------------------------- /tests/unit/zurg/lazy/lazyObject.test.ts: -------------------------------------------------------------------------------- 1 | import { lazyObject, number, object, string } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | 4 | describe("lazy", () => { 5 | itSchemaIdentity( 6 | lazyObject(() => object({ foo: string() })), 7 | { foo: "hello" }, 8 | ); 9 | 10 | itSchemaIdentity( 11 | lazyObject(() => object({ foo: string() })).extend(object({ bar: number() })), 12 | { 13 | foo: "hello", 14 | bar: 42, 15 | }, 16 | { title: "returned schema has object utils" }, 17 | ); 18 | }); 19 | -------------------------------------------------------------------------------- /tests/unit/zurg/lazy/recursive/a.ts: -------------------------------------------------------------------------------- 1 | import { object } from "../../../../../src/core/schemas/builders/object"; 2 | import { schemaB } from "./b"; 3 | 4 | // @ts-expect-error 5 | export const schemaA = object({ 6 | b: schemaB, 7 | }); 8 | -------------------------------------------------------------------------------- /tests/unit/zurg/lazy/recursive/b.ts: -------------------------------------------------------------------------------- 1 | import { object } from "../../../../../src/core/schemas/builders/object"; 2 | import { optional } from "../../../../../src/core/schemas/builders/schema-utils"; 3 | import { schemaA } from "./a"; 4 | 5 | // @ts-expect-error 6 | export const schemaB = object({ 7 | a: optional(schemaA), 8 | }); 9 | -------------------------------------------------------------------------------- /tests/unit/zurg/list/list.test.ts: -------------------------------------------------------------------------------- 1 | import { list, object, property, string } from "../../../../src/core/schemas/builders"; 2 | import { itSchema, itSchemaIdentity } from "../utils/itSchema"; 3 | import { itValidate } from "../utils/itValidate"; 4 | 5 | describe("list", () => { 6 | itSchemaIdentity(list(string()), ["hello", "world"], { 7 | title: "functions as identity when item type is primitive", 8 | }); 9 | 10 | itSchema( 11 | "converts objects correctly", 12 | list( 13 | object({ 14 | helloWorld: property("hello_world", string()), 15 | }), 16 | ), 17 | { 18 | raw: [{ hello_world: "123" }], 19 | parsed: [{ helloWorld: "123" }], 20 | }, 21 | ); 22 | 23 | itValidate("not a list", list(string()), 42, [ 24 | { 25 | path: [], 26 | message: "Expected list. Received 42.", 27 | }, 28 | ]); 29 | 30 | itValidate( 31 | "invalid item type", 32 | list(string()), 33 | [42], 34 | [ 35 | { 36 | path: ["[0]"], 37 | message: "Expected string. Received 42.", 38 | }, 39 | ], 40 | ); 41 | }); 42 | -------------------------------------------------------------------------------- /tests/unit/zurg/literals/stringLiteral.test.ts: -------------------------------------------------------------------------------- 1 | import { stringLiteral } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | import { itValidate } from "../utils/itValidate"; 4 | 5 | describe("stringLiteral", () => { 6 | itSchemaIdentity(stringLiteral("A"), "A"); 7 | 8 | itValidate("incorrect string", stringLiteral("A"), "B", [ 9 | { 10 | path: [], 11 | message: 'Expected "A". Received "B".', 12 | }, 13 | ]); 14 | 15 | itValidate("non-string", stringLiteral("A"), 42, [ 16 | { 17 | path: [], 18 | message: 'Expected "A". Received 42.', 19 | }, 20 | ]); 21 | }); 22 | -------------------------------------------------------------------------------- /tests/unit/zurg/object-like/withParsedProperties.test.ts: -------------------------------------------------------------------------------- 1 | import { object, property, string, stringLiteral } from "../../../../src/core/schemas/builders"; 2 | 3 | describe("withParsedProperties", () => { 4 | it("Added properties included on parsed object", async () => { 5 | const schema = object({ 6 | foo: property("raw_foo", string()), 7 | bar: stringLiteral("bar"), 8 | }).withParsedProperties({ 9 | printFoo: (parsed) => () => parsed.foo, 10 | printHelloWorld: () => () => "Hello world", 11 | helloWorld: "Hello world", 12 | }); 13 | 14 | const parsed = await schema.parse({ raw_foo: "value of foo", bar: "bar" }); 15 | if (!parsed.ok) { 16 | throw new Error("Failed to parse"); 17 | } 18 | expect(parsed.value.printFoo()).toBe("value of foo"); 19 | expect(parsed.value.printHelloWorld()).toBe("Hello world"); 20 | expect(parsed.value.helloWorld).toBe("Hello world"); 21 | }); 22 | 23 | it("Added property is removed on raw object", async () => { 24 | const schema = object({ 25 | foo: property("raw_foo", string()), 26 | bar: stringLiteral("bar"), 27 | }).withParsedProperties({ 28 | printFoo: (parsed) => () => parsed.foo, 29 | }); 30 | 31 | const original = { raw_foo: "value of foo", bar: "bar" } as const; 32 | const parsed = await schema.parse(original); 33 | if (!parsed.ok) { 34 | throw new Error("Failed to parse()"); 35 | } 36 | 37 | const raw = await schema.json(parsed.value); 38 | 39 | if (!raw.ok) { 40 | throw new Error("Failed to json()"); 41 | } 42 | 43 | expect(raw.value).toEqual(original); 44 | }); 45 | 46 | describe("compile", () => { 47 | // eslint-disable-next-line jest/expect-expect 48 | it("doesn't compile with non-object schema", () => { 49 | () => 50 | object({ 51 | foo: string(), 52 | }) 53 | // @ts-expect-error 54 | .withParsedProperties(42); 55 | }); 56 | }); 57 | }); 58 | -------------------------------------------------------------------------------- /tests/unit/zurg/object/objectWithoutOptionalProperties.test.ts: -------------------------------------------------------------------------------- 1 | import { objectWithoutOptionalProperties, string, stringLiteral } from "../../../../src/core/schemas/builders"; 2 | import { itSchema } from "../utils/itSchema"; 3 | 4 | describe("objectWithoutOptionalProperties", () => { 5 | itSchema( 6 | "all properties are required", 7 | objectWithoutOptionalProperties({ 8 | foo: string(), 9 | bar: stringLiteral("bar").optional(), 10 | }), 11 | { 12 | raw: { 13 | foo: "hello", 14 | }, 15 | // @ts-expect-error 16 | parsed: { 17 | foo: "hello", 18 | }, 19 | }, 20 | ); 21 | }); 22 | -------------------------------------------------------------------------------- /tests/unit/zurg/primitives/any.test.ts: -------------------------------------------------------------------------------- 1 | import { any } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | 4 | describe("any", () => { 5 | itSchemaIdentity(any(), true); 6 | }); 7 | -------------------------------------------------------------------------------- /tests/unit/zurg/primitives/boolean.test.ts: -------------------------------------------------------------------------------- 1 | import { boolean } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | import { itValidate } from "../utils/itValidate"; 4 | 5 | describe("boolean", () => { 6 | itSchemaIdentity(boolean(), true); 7 | 8 | itValidate("non-boolean", boolean(), {}, [ 9 | { 10 | path: [], 11 | message: "Expected boolean. Received object.", 12 | }, 13 | ]); 14 | }); 15 | -------------------------------------------------------------------------------- /tests/unit/zurg/primitives/number.test.ts: -------------------------------------------------------------------------------- 1 | import { number } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | import { itValidate } from "../utils/itValidate"; 4 | 5 | describe("number", () => { 6 | itSchemaIdentity(number(), 42); 7 | 8 | itValidate("non-number", number(), "hello", [ 9 | { 10 | path: [], 11 | message: 'Expected number. Received "hello".', 12 | }, 13 | ]); 14 | }); 15 | -------------------------------------------------------------------------------- /tests/unit/zurg/primitives/string.test.ts: -------------------------------------------------------------------------------- 1 | import { string } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | import { itValidate } from "../utils/itValidate"; 4 | 5 | describe("string", () => { 6 | itSchemaIdentity(string(), "hello"); 7 | 8 | itValidate("non-string", string(), 42, [ 9 | { 10 | path: [], 11 | message: "Expected string. Received 42.", 12 | }, 13 | ]); 14 | }); 15 | -------------------------------------------------------------------------------- /tests/unit/zurg/primitives/unknown.test.ts: -------------------------------------------------------------------------------- 1 | import { unknown } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | 4 | describe("unknown", () => { 5 | itSchemaIdentity(unknown(), true); 6 | }); 7 | -------------------------------------------------------------------------------- /tests/unit/zurg/record/record.test.ts: -------------------------------------------------------------------------------- 1 | import { number, record, string } from "../../../../src/core/schemas/builders"; 2 | import { itSchemaIdentity } from "../utils/itSchema"; 3 | import { itValidate } from "../utils/itValidate"; 4 | 5 | describe("record", () => { 6 | itSchemaIdentity(record(string(), string()), { hello: "world" }); 7 | itSchemaIdentity(record(number(), string()), { 42: "world" }); 8 | 9 | itValidate( 10 | "non-record", 11 | record(number(), string()), 12 | [], 13 | [ 14 | { 15 | path: [], 16 | message: "Expected object. Received list.", 17 | }, 18 | ], 19 | ); 20 | 21 | itValidate("invalid key type", record(number(), string()), { hello: "world" }, [ 22 | { 23 | path: ["hello (key)"], 24 | message: 'Expected number. Received "hello".', 25 | }, 26 | ]); 27 | 28 | itValidate("invalid value type", record(string(), number()), { hello: "world" }, [ 29 | { 30 | path: ["hello"], 31 | message: 'Expected number. Received "world".', 32 | }, 33 | ]); 34 | }); 35 | -------------------------------------------------------------------------------- /tests/unit/zurg/schema.test.ts: -------------------------------------------------------------------------------- 1 | import { 2 | boolean, 3 | discriminant, 4 | list, 5 | number, 6 | object, 7 | string, 8 | stringLiteral, 9 | union, 10 | } from "../../../src/core/schemas/builders"; 11 | import { booleanLiteral } from "../../../src/core/schemas/builders/literals/booleanLiteral"; 12 | import { property } from "../../../src/core/schemas/builders/object/property"; 13 | import { itSchema } from "./utils/itSchema"; 14 | 15 | describe("Schema", () => { 16 | itSchema( 17 | "large nested object", 18 | object({ 19 | a: string(), 20 | b: stringLiteral("b value"), 21 | c: property( 22 | "raw_c", 23 | list( 24 | object({ 25 | animal: union(discriminant("type", "_type"), { 26 | dog: object({ value: boolean() }), 27 | cat: object({ value: property("raw_cat", number()) }), 28 | }), 29 | }), 30 | ), 31 | ), 32 | d: property("raw_d", boolean()), 33 | e: booleanLiteral(true), 34 | }), 35 | { 36 | raw: { 37 | a: "hello", 38 | b: "b value", 39 | raw_c: [ 40 | { 41 | animal: { 42 | _type: "dog", 43 | value: true, 44 | }, 45 | }, 46 | { 47 | animal: { 48 | _type: "cat", 49 | raw_cat: 42, 50 | }, 51 | }, 52 | ], 53 | raw_d: false, 54 | e: true, 55 | }, 56 | parsed: { 57 | a: "hello", 58 | b: "b value", 59 | c: [ 60 | { 61 | animal: { 62 | type: "dog", 63 | value: true, 64 | }, 65 | }, 66 | { 67 | animal: { 68 | type: "cat", 69 | value: 42, 70 | }, 71 | }, 72 | ], 73 | d: false, 74 | e: true, 75 | }, 76 | }, 77 | ); 78 | }); 79 | -------------------------------------------------------------------------------- /tests/unit/zurg/set/set.test.ts: -------------------------------------------------------------------------------- 1 | import { set, string } from "../../../../src/core/schemas/builders"; 2 | import { itSchema } from "../utils/itSchema"; 3 | import { itValidateJson, itValidateParse } from "../utils/itValidate"; 4 | 5 | describe("set", () => { 6 | itSchema("converts between raw list and parsed Set", set(string()), { 7 | raw: ["A", "B"], 8 | parsed: new Set(["A", "B"]), 9 | }); 10 | 11 | itValidateParse("not a list", set(string()), 42, [ 12 | { 13 | path: [], 14 | message: "Expected list. Received 42.", 15 | }, 16 | ]); 17 | 18 | itValidateJson( 19 | "not a Set", 20 | set(string()), 21 | [], 22 | [ 23 | { 24 | path: [], 25 | message: "Expected Set. Received list.", 26 | }, 27 | ], 28 | ); 29 | 30 | itValidateParse( 31 | "invalid item type", 32 | set(string()), 33 | [42], 34 | [ 35 | { 36 | path: ["[0]"], 37 | message: "Expected string. Received 42.", 38 | }, 39 | ], 40 | ); 41 | 42 | itValidateJson("invalid item type", set(string()), new Set([42]), [ 43 | { 44 | path: ["[0]"], 45 | message: "Expected string. Received 42.", 46 | }, 47 | ]); 48 | }); 49 | -------------------------------------------------------------------------------- /tests/unit/zurg/skipValidation.test.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | import { boolean, number, object, property, string, undiscriminatedUnion } from "../../../src/core/schemas/builders"; 3 | 4 | describe("skipValidation", () => { 5 | it("allows data that doesn't conform to the schema", async () => { 6 | const warningLogs: string[] = []; 7 | const originalConsoleWarn = console.warn; 8 | console.warn = (...args) => warningLogs.push(args.join(" ")); 9 | 10 | const schema = object({ 11 | camelCase: property("snake_case", string()), 12 | numberProperty: number(), 13 | requiredProperty: boolean(), 14 | anyPrimitive: undiscriminatedUnion([string(), number(), boolean()]), 15 | }); 16 | 17 | const parsed = await schema.parse( 18 | { 19 | snake_case: "hello", 20 | numberProperty: "oops", 21 | anyPrimitive: true, 22 | }, 23 | { 24 | skipValidation: true, 25 | }, 26 | ); 27 | 28 | expect(parsed).toEqual({ 29 | ok: true, 30 | value: { 31 | camelCase: "hello", 32 | numberProperty: "oops", 33 | anyPrimitive: true, 34 | }, 35 | }); 36 | 37 | expect(warningLogs).toEqual([ 38 | `Failed to validate. 39 | - numberProperty: Expected number. Received "oops".`, 40 | ]); 41 | 42 | console.warn = originalConsoleWarn; 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /tests/unit/zurg/undiscriminated-union/undiscriminatedUnion.test.ts: -------------------------------------------------------------------------------- 1 | import { number, object, property, string, undiscriminatedUnion } from "../../../../src/core/schemas/builders"; 2 | import { itSchema, itSchemaIdentity } from "../utils/itSchema"; 3 | 4 | describe("undiscriminatedUnion", () => { 5 | itSchemaIdentity(undiscriminatedUnion([string(), number()]), "hello world"); 6 | 7 | itSchemaIdentity(undiscriminatedUnion([object({ hello: string() }), object({ goodbye: string() })]), { 8 | goodbye: "foo", 9 | }); 10 | 11 | itSchema( 12 | "Correctly transforms", 13 | undiscriminatedUnion([object({ hello: string() }), object({ helloWorld: property("hello_world", string()) })]), 14 | { 15 | raw: { hello_world: "foo " }, 16 | parsed: { helloWorld: "foo " }, 17 | }, 18 | ); 19 | 20 | it("Returns errors for all variants", async () => { 21 | const result = await undiscriminatedUnion([string(), number()]).parse(true); 22 | if (result.ok) { 23 | throw new Error("Unexpectedly passed validation"); 24 | } 25 | expect(result.errors).toEqual([ 26 | { 27 | message: "[Variant 0] Expected string. Received true.", 28 | path: [], 29 | }, 30 | { 31 | message: "[Variant 1] Expected number. Received true.", 32 | path: [], 33 | }, 34 | ]); 35 | }); 36 | 37 | describe("compile", () => { 38 | // eslint-disable-next-line jest/expect-expect 39 | it("doesn't compile with zero members", () => { 40 | // @ts-expect-error 41 | () => undiscriminatedUnion([]); 42 | }); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /tests/unit/zurg/utils/itSchema.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable jest/no-export */ 2 | import { Schema, SchemaOptions } from "../../../../src/core/schemas/Schema"; 3 | 4 | export function itSchemaIdentity( 5 | schema: Schema, 6 | value: T, 7 | { title = "functions as identity", opts }: { title?: string; opts?: SchemaOptions } = {}, 8 | ): void { 9 | itSchema(title, schema, { raw: value, parsed: value, opts }); 10 | } 11 | 12 | export function itSchema( 13 | title: string, 14 | schema: Schema, 15 | { 16 | raw, 17 | parsed, 18 | opts, 19 | only = false, 20 | }: { 21 | raw: Raw; 22 | parsed: Parsed; 23 | opts?: SchemaOptions; 24 | only?: boolean; 25 | }, 26 | ): void { 27 | // eslint-disable-next-line jest/valid-title 28 | (only ? describe.only : describe)(title, () => { 29 | itParse("parse()", schema, { raw, parsed, opts }); 30 | itJson("json()", schema, { raw, parsed, opts }); 31 | }); 32 | } 33 | 34 | export function itParse( 35 | title: string, 36 | schema: Schema, 37 | { 38 | raw, 39 | parsed, 40 | opts, 41 | }: { 42 | raw: Raw; 43 | parsed: Parsed; 44 | opts?: SchemaOptions; 45 | }, 46 | ): void { 47 | // eslint-disable-next-line jest/valid-title 48 | it(title, () => { 49 | const maybeValid = schema.parse(raw, opts); 50 | if (!maybeValid.ok) { 51 | throw new Error("Failed to parse() " + JSON.stringify(maybeValid.errors, undefined, 4)); 52 | } 53 | expect(maybeValid.value).toStrictEqual(parsed); 54 | }); 55 | } 56 | 57 | export function itJson( 58 | title: string, 59 | schema: Schema, 60 | { 61 | raw, 62 | parsed, 63 | opts, 64 | }: { 65 | raw: Raw; 66 | parsed: Parsed; 67 | opts?: SchemaOptions; 68 | }, 69 | ): void { 70 | // eslint-disable-next-line jest/valid-title 71 | it(title, () => { 72 | const maybeValid = schema.json(parsed, opts); 73 | if (!maybeValid.ok) { 74 | throw new Error("Failed to json() " + JSON.stringify(maybeValid.errors, undefined, 4)); 75 | } 76 | expect(maybeValid.value).toStrictEqual(raw); 77 | }); 78 | } 79 | -------------------------------------------------------------------------------- /tests/unit/zurg/utils/itValidate.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable jest/no-export */ 2 | import { Schema, SchemaOptions, ValidationError } from "../../../../src/core/schemas/Schema"; 3 | 4 | export function itValidate( 5 | title: string, 6 | schema: Schema, 7 | input: unknown, 8 | errors: ValidationError[], 9 | opts?: SchemaOptions, 10 | ): void { 11 | // eslint-disable-next-line jest/valid-title 12 | describe("parse()", () => { 13 | itValidateParse(title, schema, input, errors, opts); 14 | }); 15 | describe("json()", () => { 16 | itValidateJson(title, schema, input, errors, opts); 17 | }); 18 | } 19 | 20 | export function itValidateParse( 21 | title: string, 22 | schema: Schema, 23 | raw: unknown, 24 | errors: ValidationError[], 25 | opts?: SchemaOptions, 26 | ): void { 27 | describe("parse", () => { 28 | // eslint-disable-next-line jest/valid-title 29 | it(title, async () => { 30 | const maybeValid = await schema.parse(raw, opts); 31 | if (maybeValid.ok) { 32 | throw new Error("Value passed validation"); 33 | } 34 | expect(maybeValid.errors).toStrictEqual(errors); 35 | }); 36 | }); 37 | } 38 | 39 | export function itValidateJson( 40 | title: string, 41 | schema: Schema, 42 | parsed: unknown, 43 | errors: ValidationError[], 44 | opts?: SchemaOptions, 45 | ): void { 46 | describe("json", () => { 47 | // eslint-disable-next-line jest/valid-title 48 | it(title, async () => { 49 | const maybeValid = await schema.json(parsed, opts); 50 | if (maybeValid.ok) { 51 | throw new Error("Value passed validation"); 52 | } 53 | expect(maybeValid.errors).toStrictEqual(errors); 54 | }); 55 | }); 56 | } 57 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "extendedDiagnostics": true, 4 | "strict": true, 5 | "target": "ES6", 6 | "moduleResolution": "node", 7 | "esModuleInterop": true, 8 | "skipLibCheck": true, 9 | "declaration": true, 10 | "outDir": "dist", 11 | "rootDir": "src", 12 | "baseUrl": "src", 13 | "module": "CommonJS" 14 | }, 15 | "include": ["src"], 16 | "exclude": [] 17 | } 18 | --------------------------------------------------------------------------------