diff --git a/jest.config.js b/jest.config.js index 618205d..35d6e65 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,12 +1,5 @@ /** @type {import('jest').Config} */ module.exports = { - preset: "ts-jest/presets/default-esm", + preset: "ts-jest", testEnvironment: "node", - extensionsToTreatAsEsm: [".ts"], - globals: { - "ts-jest": { - useESM: true, - }, - }, - transformIgnorePatterns: ["/node_modules/(?!(emittery)/)"], }; diff --git a/package.json b/package.json index be1ecf1..bc59cd4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@cartesia/cartesia-js", - "version": "1.3.1", + "version": "2.0.0-alpha0", "private": false, "repository": "https://github.com/cartesia-ai/cartesia-js", "main": "./index.js", @@ -12,33 +12,29 @@ "test": "jest" }, "dependencies": { - "emittery": "^1.0.3", + "url-join": "4.0.1", "form-data": "^4.0.0", - "form-data-encoder": "^4.0.2", "formdata-node": "^6.0.3", - "human-id": "^4.1.1", "node-fetch": "2.7.0", "qs": "6.11.2", "readable-stream": "^4.5.2", - "url-join": "4.0.1", - "ws": "^8.14.2" + "form-data-encoder": "^4.0.2" }, "devDependencies": { - "@types/jest": "29.5.5", - "@types/node": "17.0.33", - "@types/node-fetch": "2.6.9", + "@types/url-join": "4.0.1", "@types/qs": "6.9.8", + "@types/node-fetch": "2.6.9", "@types/readable-stream": "^4.0.15", - "@types/url-join": "4.0.1", - "@types/ws": "^8.5.13", "fetch-mock-jest": "^1.5.1", + "webpack": "^5.94.0", + "ts-loader": "^9.3.1", "jest": "29.7.0", + "@types/jest": "29.5.5", + "ts-jest": "29.1.1", "jest-environment-jsdom": "29.7.0", + "@types/node": "17.0.33", "prettier": "2.7.1", - "ts-jest": "29.1.1", - "ts-loader": "^9.3.1", - "typescript": "4.6.4", - "webpack": "^5.94.0" + "typescript": "4.6.4" }, "browser": { "fs": false, diff --git a/reference.md b/reference.md index a64a99d..0d372d0 100644 --- a/reference.md +++ b/reference.md @@ -44,7 +44,7 @@ await client.apiStatus.get(); ## Tts -
client.tts.bytes({ ...params }) -> stream.Readable +
client.tts.bytes({ ...params }) -> void
@@ -58,17 +58,17 @@ await client.apiStatus.get(); ```typescript await client.tts.bytes({ - modelId: "sonic-english", + model_id: "sonic-english", transcript: "Hello, world!", voice: { mode: "id", id: "694f9389-aac1-45b6-b726-9d9369183238", }, language: "en", - outputFormat: { + output_format: { container: "mp3", - sampleRate: 44100, - bitRate: 128000, + sample_rate: 44100, + bit_rate: 128000, }, }); ``` @@ -119,18 +119,13 @@ await client.tts.bytes({ ```typescript const response = await client.tts.sse({ - modelId: "string", + model_id: "string", transcript: "string", voice: { mode: "id", - id: "string", - experimentalControls: { - speed: 1.1, - emotion: "anger:lowest", - }, }, language: "en", - outputFormat: { + output_format: { container: "raw", }, duration: 1.1, @@ -205,10 +200,10 @@ This endpoint is priced at 15 characters per second of input audio. ```typescript await client.voiceChanger.bytes(fs.createReadStream("/path/to/your/file"), { - voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - outputFormatContainer: "mp3", - outputFormatSampleRate: 44100, - outputFormatBitRate: 128000, + "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + "output_format[container]": "mp3", + "output_format[sample_rate]": 44100, + "output_format[bit_rate]": 128000, }); ``` @@ -266,10 +261,10 @@ await client.voiceChanger.bytes(fs.createReadStream("/path/to/your/file"), { ```typescript const response = await client.voiceChanger.sse(fs.createReadStream("/path/to/your/file"), { - voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - outputFormatContainer: "mp3", - outputFormatSampleRate: 44100, - outputFormatBitRate: 128000, + "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + "output_format[container]": "mp3", + "output_format[sample_rate]": 44100, + "output_format[bit_rate]": 128000, }); for await (const item of response) { console.log(item); @@ -383,7 +378,7 @@ await client.voices.create({ 1, 1, 1, 1, 1, 1, 1, ], language: "en", - baseVoiceId: "string", + base_voice_id: "string", }); ``` @@ -597,7 +592,7 @@ await client.voices.localize({ 1, 1, 1, 1, 1, 1, 1, ], language: "en", - originalSpeakerGender: "male", + original_speaker_gender: "male", dialect: "au", }); ``` @@ -689,7 +684,7 @@ await client.voices.mix({
-
client.voices.cloneFromClip(clip, { ...params }) -> Cartesia.EmbeddingResponse +
client.voices.clone(clip, { ...params }) -> Cartesia.VoiceMetadata
@@ -701,9 +696,11 @@ await client.voices.mix({
-Clone a voice from a clip. The clip should be a 15-20 second recording of a person speaking with little to no background noise. +Clone a voice from an audio clip. This endpoint has two modes, stability and similarity. + +Similarity mode clones are more similar to the source clip, but may reproduce background noise. For these, use an audio clip about 5 seconds long. -The endpoint will return an embedding that can either be used directly with text-to-speech endpoints or used to create a new voice. +Stability mode clones are more stable, but may not sound as similar to the source clip. For these, use an audio clip 10-20 seconds long.
@@ -719,7 +716,13 @@ The endpoint will return an embedding that can either be used directly with text
```typescript -await client.voices.cloneFromClip(fs.createReadStream("/path/to/your/file"), {}); +await client.voices.clone(fs.createReadStream("/path/to/your/file"), { + name: "A high-stability cloned voice", + description: "Copied from Cartesia docs", + mode: "stability", + language: "en", + enhance: true, +}); ```
@@ -743,7 +746,7 @@ await client.voices.cloneFromClip(fs.createReadStream("/path/to/your/file"), {})
-**request:** `Cartesia.CloneFromClipRequest` +**request:** `Cartesia.CloneVoiceRequest`
diff --git a/src/api/resources/apiStatus/client/Client.ts b/src/api/resources/apiStatus/client/Client.ts index 4089c6c..1e15a7d 100644 --- a/src/api/resources/apiStatus/client/Client.ts +++ b/src/api/resources/apiStatus/client/Client.ts @@ -5,7 +5,6 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Cartesia from "../../../index"; -import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; export declare namespace ApiStatus { @@ -46,8 +45,8 @@ export class ApiStatus { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), @@ -59,13 +58,7 @@ export class ApiStatus { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ApiInfo.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.ApiInfo; } if (_response.error.reason === "status-code") { diff --git a/src/api/resources/tts/client/Client.ts b/src/api/resources/tts/client/Client.ts index bd4b42d..f2a80bd 100644 --- a/src/api/resources/tts/client/Client.ts +++ b/src/api/resources/tts/client/Client.ts @@ -5,10 +5,10 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Cartesia from "../../../index"; -import * as stream from "stream"; -import * as serializers from "../../../../serialization/index"; import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; +import * as stream from "stream"; +import * as serializers from "../../../../serialization/index"; export declare namespace Tts { interface Options { @@ -34,8 +34,60 @@ export declare namespace Tts { export class Tts { constructor(protected readonly _options: Tts.Options = {}) {} - public async bytes(request: Cartesia.TtsRequest, requestOptions?: Tts.RequestOptions): Promise { - const _response = await (this._options.fetcher ?? core.fetcher)({ + /** + * @param {Cartesia.TtsRequest} request + * @param {Tts.RequestOptions} requestOptions - Request-specific configuration. + * + * @example + * await client.tts.bytes({ + * model_id: "sonic-english", + * transcript: "Hello, world!", + * voice: { + * mode: "id", + * id: "694f9389-aac1-45b6-b726-9d9369183238" + * }, + * language: "en", + * output_format: { + * container: "mp3", + * sample_rate: 44100, + * bit_rate: 128000 + * } + * }) + * + * @example + * await client.tts.bytes({ + * model_id: "sonic-english", + * transcript: "Hello, world!", + * voice: { + * mode: "id", + * id: "694f9389-aac1-45b6-b726-9d9369183238" + * }, + * language: "en", + * output_format: { + * container: "wav", + * sample_rate: 44100, + * encoding: "pcm_f32le" + * } + * }) + * + * @example + * await client.tts.bytes({ + * model_id: "sonic-english", + * transcript: "Hello, world!", + * voice: { + * mode: "id", + * id: "694f9389-aac1-45b6-b726-9d9369183238" + * }, + * language: "en", + * output_format: { + * container: "raw", + * sample_rate: 44100, + * encoding: "pcm_f32le" + * } + * }) + */ + public async bytes(request: Cartesia.TtsRequest, requestOptions?: Tts.RequestOptions): Promise { + const _response = await (this._options.fetcher ?? core.fetcher)({ url: urlJoin( (await core.Supplier.get(this._options.environment)) ?? environments.CartesiaEnvironment.Production, "/tts/bytes" @@ -45,22 +97,21 @@ export class Tts { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), }, contentType: "application/json", requestType: "json", - body: serializers.TtsRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }), - responseType: "streaming", + body: request, timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return _response.body; + return; } if (_response.error.reason === "status-code") { @@ -99,15 +150,15 @@ export class Tts { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), }, contentType: "application/json", requestType: "json", - body: serializers.TtsRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }), + body: request, responseType: "sse", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, @@ -127,8 +178,8 @@ export class Tts { }, signal: requestOptions?.abortSignal, eventShape: { - type: "sse", - streamTerminator: "[DONE]", + type: "json", + messageTerminator: "\n", }, }); } diff --git a/src/api/resources/tts/types/CancelContextRequest.ts b/src/api/resources/tts/types/CancelContextRequest.ts index f5622ad..31c7bd4 100644 --- a/src/api/resources/tts/types/CancelContextRequest.ts +++ b/src/api/resources/tts/types/CancelContextRequest.ts @@ -6,7 +6,7 @@ import * as Cartesia from "../../../index"; export interface CancelContextRequest { /** The ID of the context to cancel. */ - contextId: Cartesia.ContextId; + context_id: Cartesia.ContextId; /** Whether to cancel the context, so that no more messages are generated for that context. */ cancel: true; } diff --git a/src/api/resources/tts/types/GenerationRequest.ts b/src/api/resources/tts/types/GenerationRequest.ts index 0dce467..8ac66ce 100644 --- a/src/api/resources/tts/types/GenerationRequest.ts +++ b/src/api/resources/tts/types/GenerationRequest.ts @@ -6,22 +6,22 @@ import * as Cartesia from "../../../index"; export interface GenerationRequest { /** The ID of the model to use for the generation. See [Models](/build-with-sonic/models) for available models. */ - modelId: string; + model_id: string; transcript: string; voice: Cartesia.TtsRequestVoiceSpecifier; language?: Cartesia.SupportedLanguage; - outputFormat: Cartesia.WebSocketRawOutputFormat; + output_format: Cartesia.WebSocketRawOutputFormat; /** * The maximum duration of the audio in seconds. You do not usually need to specify this. * If the duration is not appropriate for the length of the transcript, the output audio may be truncated. */ duration?: number; - contextId: Cartesia.ContextId; + context_id: Cartesia.ContextId; /** * Whether this input may be followed by more inputs. * If not specified, this defaults to `false`. */ continue?: boolean; /** Whether to return word-level timestamps. */ - addTimestamps?: boolean; + add_timestamps?: boolean; } diff --git a/src/api/resources/tts/types/Mp3OutputFormat.ts b/src/api/resources/tts/types/Mp3OutputFormat.ts index 4ca41a6..7031390 100644 --- a/src/api/resources/tts/types/Mp3OutputFormat.ts +++ b/src/api/resources/tts/types/Mp3OutputFormat.ts @@ -3,6 +3,6 @@ */ export interface Mp3OutputFormat { - sampleRate: number; - bitRate: number; + sample_rate: number; + bit_rate: number; } diff --git a/src/api/resources/tts/types/RawOutputFormat.ts b/src/api/resources/tts/types/RawOutputFormat.ts index 0f32735..83118fa 100644 --- a/src/api/resources/tts/types/RawOutputFormat.ts +++ b/src/api/resources/tts/types/RawOutputFormat.ts @@ -6,5 +6,5 @@ import * as Cartesia from "../../../index"; export interface RawOutputFormat { encoding: Cartesia.RawEncoding; - sampleRate: number; + sample_rate: number; } diff --git a/src/api/resources/tts/types/TtsRequest.ts b/src/api/resources/tts/types/TtsRequest.ts index 154f6d1..7778620 100644 --- a/src/api/resources/tts/types/TtsRequest.ts +++ b/src/api/resources/tts/types/TtsRequest.ts @@ -6,11 +6,11 @@ import * as Cartesia from "../../../index"; export interface TtsRequest { /** The ID of the model to use for the generation. See [Models](/build-with-sonic/models) for available models. */ - modelId: string; + model_id: string; transcript: string; voice: Cartesia.TtsRequestVoiceSpecifier; language?: Cartesia.SupportedLanguage; - outputFormat: Cartesia.OutputFormat; + output_format: Cartesia.OutputFormat; /** * The maximum duration of the audio in seconds. You do not usually need to specify this. * If the duration is not appropriate for the length of the transcript, the output audio may be truncated. diff --git a/src/api/resources/tts/types/TtsRequestEmbeddingSpecifier.ts b/src/api/resources/tts/types/TtsRequestEmbeddingSpecifier.ts index b85fc8e..0653cb8 100644 --- a/src/api/resources/tts/types/TtsRequestEmbeddingSpecifier.ts +++ b/src/api/resources/tts/types/TtsRequestEmbeddingSpecifier.ts @@ -5,7 +5,6 @@ import * as Cartesia from "../../../index"; export interface TtsRequestEmbeddingSpecifier { - mode: "embedding"; embedding: Cartesia.Embedding; - experimentalControls?: Cartesia.Controls; + __experimental_controls?: Cartesia.Controls; } diff --git a/src/api/resources/tts/types/TtsRequestIdSpecifier.ts b/src/api/resources/tts/types/TtsRequestIdSpecifier.ts index ffdce30..447fcc9 100644 --- a/src/api/resources/tts/types/TtsRequestIdSpecifier.ts +++ b/src/api/resources/tts/types/TtsRequestIdSpecifier.ts @@ -5,7 +5,6 @@ import * as Cartesia from "../../../index"; export interface TtsRequestIdSpecifier { - mode: "id"; id: Cartesia.VoiceId; - experimentalControls?: Cartesia.Controls; + __experimental_controls?: Cartesia.Controls; } diff --git a/src/api/resources/tts/types/TtsRequestVoiceSpecifier.ts b/src/api/resources/tts/types/TtsRequestVoiceSpecifier.ts index 7b9ccef..fbb0619 100644 --- a/src/api/resources/tts/types/TtsRequestVoiceSpecifier.ts +++ b/src/api/resources/tts/types/TtsRequestVoiceSpecifier.ts @@ -4,4 +4,16 @@ import * as Cartesia from "../../../index"; -export type TtsRequestVoiceSpecifier = Cartesia.TtsRequestIdSpecifier | Cartesia.TtsRequestEmbeddingSpecifier; +export type TtsRequestVoiceSpecifier = + | Cartesia.TtsRequestVoiceSpecifier.Id + | Cartesia.TtsRequestVoiceSpecifier.Embedding; + +export declare namespace TtsRequestVoiceSpecifier { + interface Id extends Cartesia.TtsRequestIdSpecifier { + mode: "id"; + } + + interface Embedding extends Cartesia.TtsRequestEmbeddingSpecifier { + mode: "embedding"; + } +} diff --git a/src/api/resources/tts/types/WebSocketBaseResponse.ts b/src/api/resources/tts/types/WebSocketBaseResponse.ts index 62279a6..d3154e2 100644 --- a/src/api/resources/tts/types/WebSocketBaseResponse.ts +++ b/src/api/resources/tts/types/WebSocketBaseResponse.ts @@ -5,7 +5,7 @@ import * as Cartesia from "../../../index"; export interface WebSocketBaseResponse { - contextId?: Cartesia.ContextId; - statusCode: number; + context_id: Cartesia.ContextId; + status_code: number; done: boolean; } diff --git a/src/api/resources/tts/types/WebSocketChunkResponse.ts b/src/api/resources/tts/types/WebSocketChunkResponse.ts index 1e1c82e..0be3498 100644 --- a/src/api/resources/tts/types/WebSocketChunkResponse.ts +++ b/src/api/resources/tts/types/WebSocketChunkResponse.ts @@ -6,5 +6,5 @@ import * as Cartesia from "../../../index"; export interface WebSocketChunkResponse extends Cartesia.WebSocketBaseResponse { data: string; - stepTime: number; + step_time: number; } diff --git a/src/api/resources/tts/types/WebSocketRawOutputFormat.ts b/src/api/resources/tts/types/WebSocketRawOutputFormat.ts index 17a25a7..79bd10d 100644 --- a/src/api/resources/tts/types/WebSocketRawOutputFormat.ts +++ b/src/api/resources/tts/types/WebSocketRawOutputFormat.ts @@ -7,5 +7,5 @@ import * as Cartesia from "../../../index"; export interface WebSocketRawOutputFormat { container: "raw"; encoding: Cartesia.RawEncoding; - sampleRate: number; + sample_rate: number; } diff --git a/src/api/resources/tts/types/WebSocketResponse.ts b/src/api/resources/tts/types/WebSocketResponse.ts index 861851b..a43b3de 100644 --- a/src/api/resources/tts/types/WebSocketResponse.ts +++ b/src/api/resources/tts/types/WebSocketResponse.ts @@ -7,7 +7,7 @@ import * as Cartesia from "../../../index"; export type WebSocketResponse = | Cartesia.WebSocketResponse.Chunk | Cartesia.WebSocketResponse.Done - | Cartesia.WebSocketResponse.Timestamps + | Cartesia.WebSocketResponse.Timestamp | Cartesia.WebSocketResponse.Error_; export declare namespace WebSocketResponse { @@ -19,8 +19,8 @@ export declare namespace WebSocketResponse { type: "done"; } - interface Timestamps extends Cartesia.WebSocketTimestampsResponse { - type: "timestamps"; + interface Timestamp extends Cartesia.WebSocketTimestampResponse { + type: "timestamp"; } interface Error_ extends Cartesia.WebSocketErrorResponse { diff --git a/src/api/resources/tts/types/WebSocketStreamOptions.ts b/src/api/resources/tts/types/WebSocketStreamOptions.ts deleted file mode 100644 index ff4ba05..0000000 --- a/src/api/resources/tts/types/WebSocketStreamOptions.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -export interface WebSocketStreamOptions { - timeout?: number; -} diff --git a/src/api/resources/tts/types/WebSocketTimestampResponse.ts b/src/api/resources/tts/types/WebSocketTimestampResponse.ts new file mode 100644 index 0000000..991b426 --- /dev/null +++ b/src/api/resources/tts/types/WebSocketTimestampResponse.ts @@ -0,0 +1,9 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import * as Cartesia from "../../../index"; + +export interface WebSocketTimestampResponse extends Cartesia.WebSocketBaseResponse { + word_timestamps: Cartesia.WordTimestamps; +} diff --git a/src/api/resources/tts/types/WebSocketTimestampsResponse.ts b/src/api/resources/tts/types/WebSocketTimestampsResponse.ts deleted file mode 100644 index 68c368d..0000000 --- a/src/api/resources/tts/types/WebSocketTimestampsResponse.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Cartesia from "../../../index"; - -export interface WebSocketTimestampsResponse extends Cartesia.WebSocketBaseResponse { - wordTimestamps?: Cartesia.WordTimestamps; -} diff --git a/src/api/resources/tts/types/WebSocketTtsOutput.ts b/src/api/resources/tts/types/WebSocketTtsOutput.ts deleted file mode 100644 index 73e2863..0000000 --- a/src/api/resources/tts/types/WebSocketTtsOutput.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Cartesia from "../../../index"; - -export interface WebSocketTtsOutput { - wordTimestamps?: Cartesia.WordTimestamps; - audio?: unknown; - contextId?: Cartesia.ContextId; -} diff --git a/src/api/resources/tts/types/WebSocketTtsRequest.ts b/src/api/resources/tts/types/WebSocketTtsRequest.ts deleted file mode 100644 index c0d3d8f..0000000 --- a/src/api/resources/tts/types/WebSocketTtsRequest.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as Cartesia from "../../../index"; - -export interface WebSocketTtsRequest { - /** The ID of the model to use for the generation. See [Models](/build-with-sonic/models) for available models. */ - modelId: string; - outputFormat?: Cartesia.OutputFormat; - transcript?: string; - voice: Cartesia.TtsRequestVoiceSpecifier; - duration?: number; - language?: string; - addTimestamps?: boolean; - contextId?: string; -} diff --git a/src/api/resources/tts/types/index.ts b/src/api/resources/tts/types/index.ts index 5212040..f1b034c 100644 --- a/src/api/resources/tts/types/index.ts +++ b/src/api/resources/tts/types/index.ts @@ -3,16 +3,13 @@ export * from "./WebSocketBaseResponse"; export * from "./WebSocketResponse"; export * from "./WebSocketErrorResponse"; export * from "./WebSocketChunkResponse"; -export * from "./WebSocketTimestampsResponse"; -export * from "./WebSocketTtsOutput"; -export * from "./WebSocketStreamOptions"; +export * from "./WebSocketTimestampResponse"; export * from "./WordTimestamps"; export * from "./WebSocketDoneResponse"; export * from "./CancelContextRequest"; export * from "./GenerationRequest"; export * from "./WebSocketRawOutputFormat"; export * from "./WebSocketRequest"; -export * from "./WebSocketTtsRequest"; export * from "./TtsRequest"; export * from "./SupportedLanguage"; export * from "./OutputFormat"; diff --git a/src/api/resources/voiceChanger/client/Client.ts b/src/api/resources/voiceChanger/client/Client.ts index e3ccb2d..78dcf26 100644 --- a/src/api/resources/voiceChanger/client/Client.ts +++ b/src/api/resources/voiceChanger/client/Client.ts @@ -48,15 +48,15 @@ export class VoiceChanger { ): Promise { const _request = await core.newFormData(); await _request.appendFile("clip", clip); - await _request.append("voice[id]", request.voiceId); - await _request.append("output_format[container]", request.outputFormatContainer); - await _request.append("output_format[sample_rate]", request.outputFormatSampleRate.toString()); - if (request.outputFormatEncoding != null) { - await _request.append("output_format[encoding]", request.outputFormatEncoding); + await _request.append("voice[id]", request.voice[id]); + await _request.append("output_format[container]", request.output_format[container]); + await _request.append("output_format[sample_rate]", request.output_format[sample_rate].toString()); + if (request.output_format[encoding] != null) { + await _request.append("output_format[encoding]", request.output_format[encoding]); } - if (request.outputFormatBitRate != null) { - await _request.append("output_format[bit_rate]", request.outputFormatBitRate.toString()); + if (request.output_format[bit_rate] != null) { + await _request.append("output_format[bit_rate]", request.output_format[bit_rate].toString()); } const _maybeEncodedRequest = await _request.getRequest(); @@ -70,8 +70,8 @@ export class VoiceChanger { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), @@ -118,15 +118,15 @@ export class VoiceChanger { ): Promise> { const _request = await core.newFormData(); await _request.appendFile("clip", clip); - await _request.append("voice[id]", request.voiceId); - await _request.append("output_format[container]", request.outputFormatContainer); - await _request.append("output_format[sample_rate]", request.outputFormatSampleRate.toString()); - if (request.outputFormatEncoding != null) { - await _request.append("output_format[encoding]", request.outputFormatEncoding); + await _request.append("voice[id]", request.voice[id]); + await _request.append("output_format[container]", request.output_format[container]); + await _request.append("output_format[sample_rate]", request.output_format[sample_rate].toString()); + if (request.output_format[encoding] != null) { + await _request.append("output_format[encoding]", request.output_format[encoding]); } - if (request.outputFormatBitRate != null) { - await _request.append("output_format[bit_rate]", request.outputFormatBitRate.toString()); + if (request.output_format[bit_rate] != null) { + await _request.append("output_format[bit_rate]", request.output_format[bit_rate].toString()); } const _maybeEncodedRequest = await _request.getRequest(); @@ -140,8 +140,8 @@ export class VoiceChanger { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), diff --git a/src/api/resources/voiceChanger/client/requests/VoiceChangerBytesRequest.ts b/src/api/resources/voiceChanger/client/requests/VoiceChangerBytesRequest.ts index d86f3bd..ecda6ea 100644 --- a/src/api/resources/voiceChanger/client/requests/VoiceChangerBytesRequest.ts +++ b/src/api/resources/voiceChanger/client/requests/VoiceChangerBytesRequest.ts @@ -7,40 +7,40 @@ import * as Cartesia from "../../../../index"; /** * @example * { - * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - * outputFormatContainer: "mp3", - * outputFormatSampleRate: 44100, - * outputFormatBitRate: 128000 + * "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + * "output_format[container]": "mp3", + * "output_format[sample_rate]": 44100, + * "output_format[bit_rate]": 128000 * } * * @example * { - * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - * outputFormatContainer: "wav", - * outputFormatSampleRate: 44100, - * outputFormatEncoding: "pcm_f32le" + * "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + * "output_format[container]": "wav", + * "output_format[sample_rate]": 44100, + * "output_format[encoding]": "pcm_f32le" * } * * @example * { - * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - * outputFormatContainer: "raw", - * outputFormatSampleRate: 44100, - * outputFormatEncoding: "pcm_f32le" + * "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + * "output_format[container]": "raw", + * "output_format[sample_rate]": 44100, + * "output_format[encoding]": "pcm_f32le" * } */ export interface VoiceChangerBytesRequest { - voiceId: string; - outputFormatContainer: Cartesia.OutputFormatContainer; - outputFormatSampleRate: number; + "voice[id]": string; + "output_format[container]": Cartesia.OutputFormatContainer; + "output_format[sample_rate]": number; /** * Required for `raw` and `wav` containers. * */ - outputFormatEncoding?: Cartesia.RawEncoding; + "output_format[encoding]"?: Cartesia.RawEncoding; /** * Required for `mp3` containers. * */ - outputFormatBitRate?: number; + "output_format[bit_rate]"?: number; } diff --git a/src/api/resources/voiceChanger/client/requests/VoiceChangerSseRequest.ts b/src/api/resources/voiceChanger/client/requests/VoiceChangerSseRequest.ts index b912610..6fa915c 100644 --- a/src/api/resources/voiceChanger/client/requests/VoiceChangerSseRequest.ts +++ b/src/api/resources/voiceChanger/client/requests/VoiceChangerSseRequest.ts @@ -7,40 +7,40 @@ import * as Cartesia from "../../../../index"; /** * @example * { - * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - * outputFormatContainer: "mp3", - * outputFormatSampleRate: 44100, - * outputFormatBitRate: 128000 + * "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + * "output_format[container]": "mp3", + * "output_format[sample_rate]": 44100, + * "output_format[bit_rate]": 128000 * } * * @example * { - * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - * outputFormatContainer: "wav", - * outputFormatSampleRate: 44100, - * outputFormatEncoding: "pcm_f32le" + * "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + * "output_format[container]": "wav", + * "output_format[sample_rate]": 44100, + * "output_format[encoding]": "pcm_f32le" * } * * @example * { - * voiceId: "694f9389-aac1-45b6-b726-9d9369183238", - * outputFormatContainer: "raw", - * outputFormatSampleRate: 44100, - * outputFormatEncoding: "pcm_f32le" + * "voice[id]": "694f9389-aac1-45b6-b726-9d9369183238", + * "output_format[container]": "raw", + * "output_format[sample_rate]": 44100, + * "output_format[encoding]": "pcm_f32le" * } */ export interface VoiceChangerSseRequest { - voiceId: string; - outputFormatContainer: Cartesia.OutputFormatContainer; - outputFormatSampleRate: number; + "voice[id]": string; + "output_format[container]": Cartesia.OutputFormatContainer; + "output_format[sample_rate]": number; /** * Required for `raw` and `wav` containers. * */ - outputFormatEncoding?: Cartesia.RawEncoding; + "output_format[encoding]"?: Cartesia.RawEncoding; /** * Required for `mp3` containers. * */ - outputFormatBitRate?: number; + "output_format[bit_rate]"?: number; } diff --git a/src/api/resources/voices/client/Client.ts b/src/api/resources/voices/client/Client.ts index 9b0e4b1..b52a579 100644 --- a/src/api/resources/voices/client/Client.ts +++ b/src/api/resources/voices/client/Client.ts @@ -6,7 +6,6 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Cartesia from "../../../index"; import urlJoin from "url-join"; -import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import * as fs from "fs"; import { Blob } from "buffer"; @@ -52,8 +51,8 @@ export class Voices { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), @@ -65,13 +64,7 @@ export class Voices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.voices.list.Response.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.Voice[]; } if (_response.error.reason === "status-code") { @@ -106,7 +99,7 @@ export class Voices { * description: "string", * embedding: [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], * language: "en", - * baseVoiceId: "string" + * base_voice_id: "string" * }) */ public async create( @@ -123,27 +116,21 @@ export class Voices { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), }, contentType: "application/json", requestType: "json", - body: serializers.CreateVoiceRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }), + body: request, timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.Voice.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.Voice; } if (_response.error.reason === "status-code") { @@ -179,15 +166,15 @@ export class Voices { const _response = await (this._options.fetcher ?? core.fetcher)({ url: urlJoin( (await core.Supplier.get(this._options.environment)) ?? environments.CartesiaEnvironment.Production, - `/voices/${encodeURIComponent(serializers.VoiceId.jsonOrThrow(id))}` + `/voices/${encodeURIComponent(id)}` ), method: "DELETE", headers: { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), @@ -243,34 +230,28 @@ export class Voices { const _response = await (this._options.fetcher ?? core.fetcher)({ url: urlJoin( (await core.Supplier.get(this._options.environment)) ?? environments.CartesiaEnvironment.Production, - `/voices/${encodeURIComponent(serializers.VoiceId.jsonOrThrow(id))}` + `/voices/${encodeURIComponent(id)}` ), method: "PATCH", headers: { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), }, contentType: "application/json", requestType: "json", - body: serializers.UpdateVoiceRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }), + body: request, timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.Voice.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.Voice; } if (_response.error.reason === "status-code") { @@ -306,15 +287,15 @@ export class Voices { const _response = await (this._options.fetcher ?? core.fetcher)({ url: urlJoin( (await core.Supplier.get(this._options.environment)) ?? environments.CartesiaEnvironment.Production, - `/voices/${encodeURIComponent(serializers.VoiceId.jsonOrThrow(id))}` + `/voices/${encodeURIComponent(id)}` ), method: "GET", headers: { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), @@ -326,13 +307,7 @@ export class Voices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.Voice.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.Voice; } if (_response.error.reason === "status-code") { @@ -365,7 +340,7 @@ export class Voices { * await client.voices.localize({ * embedding: [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], * language: "en", - * originalSpeakerGender: "male", + * original_speaker_gender: "male", * dialect: "au" * }) */ @@ -383,27 +358,21 @@ export class Voices { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), }, contentType: "application/json", requestType: "json", - body: serializers.LocalizeVoiceRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }), + body: request, timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.EmbeddingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.EmbeddingResponse; } if (_response.error.reason === "status-code") { @@ -454,27 +423,21 @@ export class Voices { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), }, contentType: "application/json", requestType: "json", - body: serializers.MixVoicesRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }), + body: request, timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.EmbeddingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.EmbeddingResponse; } if (_response.error.reason === "status-code") { @@ -500,38 +463,67 @@ export class Voices { } /** - * Clone a voice from a clip. The clip should be a 15-20 second recording of a person speaking with little to no background noise. + * Clone a voice from an audio clip. This endpoint has two modes, stability and similarity. + * + * Similarity mode clones are more similar to the source clip, but may reproduce background noise. For these, use an audio clip about 5 seconds long. * - * The endpoint will return an embedding that can either be used directly with text-to-speech endpoints or used to create a new voice. + * Stability mode clones are more stable, but may not sound as similar to the source clip. For these, use an audio clip 10-20 seconds long. * * @param {File | fs.ReadStream | Blob} clip - * @param {Cartesia.CloneFromClipRequest} request + * @param {Cartesia.CloneVoiceRequest} request * @param {Voices.RequestOptions} requestOptions - Request-specific configuration. * * @example - * await client.voices.cloneFromClip(fs.createReadStream("/path/to/your/file"), {}) + * await client.voices.clone(fs.createReadStream("/path/to/your/file"), { + * name: "A high-stability cloned voice", + * description: "Copied from Cartesia docs", + * mode: "stability", + * language: "en", + * enhance: true + * }) + * + * @example + * await client.voices.clone(fs.createReadStream("/path/to/your/file"), { + * name: "A high-similarity cloned voice", + * description: "Copied from Cartesia docs", + * mode: "similarity", + * language: "en", + * transcript: "A transcript of the words spoken in the audio clip.", + * enhance: false + * }) */ - public async cloneFromClip( + public async clone( clip: File | fs.ReadStream | Blob, - request: Cartesia.CloneFromClipRequest, + request: Cartesia.CloneVoiceRequest, requestOptions?: Voices.RequestOptions - ): Promise { + ): Promise { const _request = await core.newFormData(); await _request.appendFile("clip", clip); + await _request.append("name", request.name); + if (request.description != null) { + await _request.append("description", request.description); + } + + await _request.append("language", request.language); + await _request.append("mode", request.mode); await _request.append("enhance", request.enhance.toString()); + if (request.transcript != null) { + await _request.append("transcript", request.transcript); + } + const _maybeEncodedRequest = await _request.getRequest(); const _response = await (this._options.fetcher ?? core.fetcher)({ url: urlJoin( (await core.Supplier.get(this._options.environment)) ?? environments.CartesiaEnvironment.Production, - "/voices/clone/clip" + "/voices/clone" ), method: "POST", headers: { "Cartesia-Version": requestOptions?.cartesiaVersion ?? this._options?.cartesiaVersion ?? "2024-06-10", "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "@cartesia/cartesia-js", - "X-Fern-SDK-Version": "1.3.1", - "User-Agent": "@cartesia/cartesia-js/1.3.1", + "X-Fern-SDK-Version": "2.0.0-alpha0", + "User-Agent": "@cartesia/cartesia-js/2.0.0-alpha0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version, ...(await this._getCustomAuthorizationHeaders()), @@ -545,13 +537,7 @@ export class Voices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.EmbeddingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return _response.body as Cartesia.VoiceMetadata; } if (_response.error.reason === "status-code") { diff --git a/src/api/resources/voices/client/requests/CloneFromClipRequest.ts b/src/api/resources/voices/client/requests/CloneFromClipRequest.ts deleted file mode 100644 index ba9b921..0000000 --- a/src/api/resources/voices/client/requests/CloneFromClipRequest.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -/** - * @example - * {} - */ -export interface CloneFromClipRequest { - /** - * Whether to enhance the clip to improve its quality before cloning. Useful if the clip is low quality. - * - */ - enhance: boolean; -} diff --git a/src/api/resources/voices/client/requests/CloneVoiceRequest.ts b/src/api/resources/voices/client/requests/CloneVoiceRequest.ts new file mode 100644 index 0000000..323ad8f --- /dev/null +++ b/src/api/resources/voices/client/requests/CloneVoiceRequest.ts @@ -0,0 +1,58 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import * as Cartesia from "../../../../index"; + +/** + * @example + * { + * name: "A high-stability cloned voice", + * description: "Copied from Cartesia docs", + * mode: "stability", + * language: "en", + * enhance: true + * } + * + * @example + * { + * name: "A high-similarity cloned voice", + * description: "Copied from Cartesia docs", + * mode: "similarity", + * language: "en", + * transcript: "A transcript of the words spoken in the audio clip.", + * enhance: false + * } + */ +export interface CloneVoiceRequest { + /** + * The name of the voice. + * + */ + name: string; + /** + * A description for the voice. + * + */ + description?: string; + /** + * The language of the voice. + * + */ + language: Cartesia.SupportedLanguage; + /** + * 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. + * + */ + mode: Cartesia.CloneMode; + /** + * Whether to enhance the clip to improve its quality before cloning. Useful if the clip has background noise. + * + */ + enhance: boolean; + /** + * Optional transcript of the words spoken in the audio clip. Only used for similarity mode. + * + */ + transcript?: string; +} diff --git a/src/api/resources/voices/client/requests/index.ts b/src/api/resources/voices/client/requests/index.ts index 62f3da2..647edc0 100644 --- a/src/api/resources/voices/client/requests/index.ts +++ b/src/api/resources/voices/client/requests/index.ts @@ -1 +1 @@ -export { type CloneFromClipRequest } from "./CloneFromClipRequest"; +export { type CloneVoiceRequest } from "./CloneVoiceRequest"; diff --git a/src/api/resources/voices/types/CloneMode.ts b/src/api/resources/voices/types/CloneMode.ts new file mode 100644 index 0000000..e35fbd2 --- /dev/null +++ b/src/api/resources/voices/types/CloneMode.ts @@ -0,0 +1,10 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +export type CloneMode = "similarity" | "stability"; + +export const CloneMode = { + Similarity: "similarity", + Stability: "stability", +} as const; diff --git a/src/api/resources/voices/types/CreateVoiceRequest.ts b/src/api/resources/voices/types/CreateVoiceRequest.ts index 71824f9..e51f9b6 100644 --- a/src/api/resources/voices/types/CreateVoiceRequest.ts +++ b/src/api/resources/voices/types/CreateVoiceRequest.ts @@ -10,6 +10,6 @@ export interface CreateVoiceRequest { /** The description of the voice. */ description: string; embedding: Cartesia.Embedding; - language?: Cartesia.SupportedLanguage; - baseVoiceId?: Cartesia.BaseVoiceId; + language: Cartesia.SupportedLanguage; + base_voice_id?: Cartesia.BaseVoiceId; } diff --git a/src/api/resources/voices/types/LocalizeVoiceRequest.ts b/src/api/resources/voices/types/LocalizeVoiceRequest.ts index 768e437..529aed3 100644 --- a/src/api/resources/voices/types/LocalizeVoiceRequest.ts +++ b/src/api/resources/voices/types/LocalizeVoiceRequest.ts @@ -7,6 +7,6 @@ import * as Cartesia from "../../../index"; export interface LocalizeVoiceRequest { embedding: Cartesia.Embedding; language: Cartesia.LocalizeTargetLanguage; - originalSpeakerGender: Cartesia.Gender; - dialect?: Cartesia.LocalizeDialect; + original_speaker_gender: Cartesia.Gender; + dialect: Cartesia.LocalizeDialect; } diff --git a/src/api/resources/voices/types/Voice.ts b/src/api/resources/voices/types/Voice.ts index 523cde1..6c40f16 100644 --- a/src/api/resources/voices/types/Voice.ts +++ b/src/api/resources/voices/types/Voice.ts @@ -7,16 +7,16 @@ import * as Cartesia from "../../../index"; export interface Voice { id: Cartesia.VoiceId; /** The ID of the user who owns the voice. */ - userId?: string; + user_id: string; /** Whether the voice is publicly accessible. */ - isPublic: boolean; + is_public: boolean; /** The name of the voice. */ name: string; /** The description of the voice. */ description: string; /** The date and time the voice was created. */ - createdAt: Date; + created_at: string; embedding: Cartesia.Embedding; language: Cartesia.SupportedLanguage; - baseVoiceId?: Cartesia.BaseVoiceId; + base_voice_id?: Cartesia.BaseVoiceId; } diff --git a/src/api/resources/voices/types/VoiceMetadata.ts b/src/api/resources/voices/types/VoiceMetadata.ts new file mode 100644 index 0000000..69e5fdf --- /dev/null +++ b/src/api/resources/voices/types/VoiceMetadata.ts @@ -0,0 +1,20 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import * as Cartesia from "../../../index"; + +export interface VoiceMetadata { + id: Cartesia.VoiceId; + /** The ID of the user who owns the voice. */ + user_id: string; + /** Whether the voice is publicly accessible. */ + is_public: boolean; + /** The name of the voice. */ + name: string; + /** The description of the voice. */ + description: string; + /** The date and time the voice was created. */ + created_at: string; + language: Cartesia.SupportedLanguage; +} diff --git a/src/api/resources/voices/types/index.ts b/src/api/resources/voices/types/index.ts index 35b54d7..dd725da 100644 --- a/src/api/resources/voices/types/index.ts +++ b/src/api/resources/voices/types/index.ts @@ -1,6 +1,7 @@ export * from "./VoiceId"; export * from "./BaseVoiceId"; export * from "./Voice"; +export * from "./VoiceMetadata"; export * from "./CreateVoiceRequest"; export * from "./UpdateVoiceRequest"; export * from "./LocalizeTargetLanguage"; @@ -13,3 +14,4 @@ export * from "./Weight"; export * from "./IdSpecifier"; export * from "./EmbeddingSpecifier"; export * from "./MixVoiceSpecifier"; +export * from "./CloneMode"; diff --git a/src/core/index.ts b/src/core/index.ts index b6b4fe1..722f2e3 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -2,4 +2,3 @@ export * from "./fetcher"; export * from "./runtime"; export * from "./streaming-fetcher"; export * from "./form-data-utils"; -export * as serialization from "./schemas"; diff --git a/src/core/schemas/Schema.ts b/src/core/schemas/Schema.ts deleted file mode 100644 index 2a72eac..0000000 --- a/src/core/schemas/Schema.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { SchemaUtils } from "./builders"; - -export type Schema = BaseSchema & SchemaUtils; - -export type inferRaw = S extends Schema ? Raw : never; -export type inferParsed = S extends Schema ? Parsed : never; - -export interface BaseSchema { - parse: (raw: unknown, opts?: SchemaOptions) => MaybeValid; - json: (parsed: unknown, opts?: SchemaOptions) => MaybeValid; - getType: () => SchemaType | SchemaType; -} - -export const SchemaType = { - BIGINT: "bigint", - DATE: "date", - ENUM: "enum", - LIST: "list", - STRING_LITERAL: "stringLiteral", - BOOLEAN_LITERAL: "booleanLiteral", - OBJECT: "object", - ANY: "any", - BOOLEAN: "boolean", - NUMBER: "number", - STRING: "string", - UNKNOWN: "unknown", - RECORD: "record", - SET: "set", - UNION: "union", - UNDISCRIMINATED_UNION: "undiscriminatedUnion", - OPTIONAL: "optional", -} as const; -export type SchemaType = typeof SchemaType[keyof typeof SchemaType]; - -export type MaybeValid = Valid | Invalid; - -export interface Valid { - ok: true; - value: T; -} - -export interface Invalid { - ok: false; - errors: ValidationError[]; -} - -export interface ValidationError { - path: string[]; - message: string; -} - -export interface SchemaOptions { - /** - * how to handle unrecognized keys in objects - * - * @default "fail" - */ - unrecognizedObjectKeys?: "fail" | "passthrough" | "strip"; - - /** - * whether to fail when an unrecognized discriminant value is - * encountered in a union - * - * @default false - */ - allowUnrecognizedUnionMembers?: boolean; - - /** - * whether to fail when an unrecognized enum value is encountered - * - * @default false - */ - allowUnrecognizedEnumValues?: boolean; - - /** - * whether to allow data that doesn't conform to the schema. - * invalid data is passed through without transformation. - * - * when this is enabled, .parse() and .json() will always - * return `ok: true`. `.parseOrThrow()` and `.jsonOrThrow()` - * will never fail. - * - * @default false - */ - skipValidation?: boolean; - - /** - * each validation failure contains a "path" property, which is - * the breadcrumbs to the offending node in the JSON. you can supply - * a prefix that is prepended to all the errors' paths. this can be - * helpful for zurg's internal debug logging. - */ - breadcrumbsPrefix?: string[]; - - /** - * whether to send 'null' for optional properties explicitly set to 'undefined'. - */ - omitUndefined?: boolean; -} diff --git a/src/core/schemas/builders/bigint/bigint.ts b/src/core/schemas/builders/bigint/bigint.ts deleted file mode 100644 index dc9c742..0000000 --- a/src/core/schemas/builders/bigint/bigint.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { BaseSchema, Schema, SchemaType } from "../../Schema"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { getSchemaUtils } from "../schema-utils"; - -export function bigint(): Schema { - const baseSchema: BaseSchema = { - parse: (raw, { breadcrumbsPrefix = [] } = {}) => { - if (typeof raw !== "string") { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(raw, "string"), - }, - ], - }; - } - return { - ok: true, - value: BigInt(raw), - }; - }, - json: (bigint, { breadcrumbsPrefix = [] } = {}) => { - if (typeof bigint === "bigint") { - return { - ok: true, - value: bigint.toString(), - }; - } else { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(bigint, "bigint"), - }, - ], - }; - } - }, - getType: () => SchemaType.BIGINT, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - }; -} diff --git a/src/core/schemas/builders/bigint/index.ts b/src/core/schemas/builders/bigint/index.ts deleted file mode 100644 index e584304..0000000 --- a/src/core/schemas/builders/bigint/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { bigint } from "./bigint"; diff --git a/src/core/schemas/builders/date/date.ts b/src/core/schemas/builders/date/date.ts deleted file mode 100644 index b70f24b..0000000 --- a/src/core/schemas/builders/date/date.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { BaseSchema, Schema, SchemaType } from "../../Schema"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { getSchemaUtils } from "../schema-utils"; - -// https://stackoverflow.com/questions/12756159/regex-and-iso8601-formatted-datetime -const ISO_8601_REGEX = - /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; - -export function date(): Schema { - const baseSchema: BaseSchema = { - parse: (raw, { breadcrumbsPrefix = [] } = {}) => { - if (typeof raw !== "string") { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(raw, "string"), - }, - ], - }; - } - if (!ISO_8601_REGEX.test(raw)) { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(raw, "ISO 8601 date string"), - }, - ], - }; - } - return { - ok: true, - value: new Date(raw), - }; - }, - json: (date, { breadcrumbsPrefix = [] } = {}) => { - if (date instanceof Date) { - return { - ok: true, - value: date.toISOString(), - }; - } else { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(date, "Date object"), - }, - ], - }; - } - }, - getType: () => SchemaType.DATE, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - }; -} diff --git a/src/core/schemas/builders/date/index.ts b/src/core/schemas/builders/date/index.ts deleted file mode 100644 index 187b290..0000000 --- a/src/core/schemas/builders/date/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { date } from "./date"; diff --git a/src/core/schemas/builders/enum/enum.ts b/src/core/schemas/builders/enum/enum.ts deleted file mode 100644 index c1e24d6..0000000 --- a/src/core/schemas/builders/enum/enum.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Schema, SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; - -export function enum_(values: E): Schema { - const validValues = new Set(values); - - const schemaCreator = createIdentitySchemaCreator( - SchemaType.ENUM, - (value, { allowUnrecognizedEnumValues, breadcrumbsPrefix = [] } = {}) => { - if (typeof value !== "string") { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "string"), - }, - ], - }; - } - - if (!validValues.has(value) && !allowUnrecognizedEnumValues) { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "enum"), - }, - ], - }; - } - - return { - ok: true, - value: value as U, - }; - } - ); - - return schemaCreator(); -} diff --git a/src/core/schemas/builders/enum/index.ts b/src/core/schemas/builders/enum/index.ts deleted file mode 100644 index fe6faed..0000000 --- a/src/core/schemas/builders/enum/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { enum_ } from "./enum"; diff --git a/src/core/schemas/builders/index.ts b/src/core/schemas/builders/index.ts deleted file mode 100644 index 65211f9..0000000 --- a/src/core/schemas/builders/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -export * from "./bigint"; -export * from "./date"; -export * from "./enum"; -export * from "./lazy"; -export * from "./list"; -export * from "./literals"; -export * from "./object"; -export * from "./object-like"; -export * from "./primitives"; -export * from "./record"; -export * from "./schema-utils"; -export * from "./set"; -export * from "./undiscriminated-union"; -export * from "./union"; diff --git a/src/core/schemas/builders/lazy/index.ts b/src/core/schemas/builders/lazy/index.ts deleted file mode 100644 index 77420fb..0000000 --- a/src/core/schemas/builders/lazy/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { lazy } from "./lazy"; -export type { SchemaGetter } from "./lazy"; -export { lazyObject } from "./lazyObject"; diff --git a/src/core/schemas/builders/lazy/lazy.ts b/src/core/schemas/builders/lazy/lazy.ts deleted file mode 100644 index 835c61f..0000000 --- a/src/core/schemas/builders/lazy/lazy.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BaseSchema, Schema } from "../../Schema"; -import { getSchemaUtils } from "../schema-utils"; - -export type SchemaGetter> = () => SchemaType; - -export function lazy(getter: SchemaGetter>): Schema { - const baseSchema = constructLazyBaseSchema(getter); - return { - ...baseSchema, - ...getSchemaUtils(baseSchema), - }; -} - -export function constructLazyBaseSchema( - getter: SchemaGetter> -): BaseSchema { - return { - parse: (raw, opts) => getMemoizedSchema(getter).parse(raw, opts), - json: (parsed, opts) => getMemoizedSchema(getter).json(parsed, opts), - getType: () => getMemoizedSchema(getter).getType(), - }; -} - -type MemoizedGetter> = SchemaGetter & { __zurg_memoized?: SchemaType }; - -export function getMemoizedSchema>(getter: SchemaGetter): SchemaType { - const castedGetter = getter as MemoizedGetter; - if (castedGetter.__zurg_memoized == null) { - castedGetter.__zurg_memoized = getter(); - } - return castedGetter.__zurg_memoized; -} diff --git a/src/core/schemas/builders/lazy/lazyObject.ts b/src/core/schemas/builders/lazy/lazyObject.ts deleted file mode 100644 index 38c9e28..0000000 --- a/src/core/schemas/builders/lazy/lazyObject.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { getObjectUtils } from "../object"; -import { getObjectLikeUtils } from "../object-like"; -import { BaseObjectSchema, ObjectSchema } from "../object/types"; -import { getSchemaUtils } from "../schema-utils"; -import { constructLazyBaseSchema, getMemoizedSchema, SchemaGetter } from "./lazy"; - -export function lazyObject(getter: SchemaGetter>): ObjectSchema { - const baseSchema: BaseObjectSchema = { - ...constructLazyBaseSchema(getter), - _getRawProperties: () => getMemoizedSchema(getter)._getRawProperties(), - _getParsedProperties: () => getMemoizedSchema(getter)._getParsedProperties(), - }; - - return { - ...baseSchema, - ...getSchemaUtils(baseSchema), - ...getObjectLikeUtils(baseSchema), - ...getObjectUtils(baseSchema), - }; -} diff --git a/src/core/schemas/builders/list/index.ts b/src/core/schemas/builders/list/index.ts deleted file mode 100644 index 25f4bcc..0000000 --- a/src/core/schemas/builders/list/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { list } from "./list"; diff --git a/src/core/schemas/builders/list/list.ts b/src/core/schemas/builders/list/list.ts deleted file mode 100644 index e4c5c4a..0000000 --- a/src/core/schemas/builders/list/list.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { BaseSchema, MaybeValid, Schema, SchemaType, ValidationError } from "../../Schema"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { getSchemaUtils } from "../schema-utils"; - -export function list(schema: Schema): Schema { - const baseSchema: BaseSchema = { - parse: (raw, opts) => - validateAndTransformArray(raw, (item, index) => - schema.parse(item, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `[${index}]`], - }) - ), - json: (parsed, opts) => - validateAndTransformArray(parsed, (item, index) => - schema.json(item, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `[${index}]`], - }) - ), - getType: () => SchemaType.LIST, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - }; -} - -function validateAndTransformArray( - value: unknown, - transformItem: (item: Raw, index: number) => MaybeValid -): MaybeValid { - if (!Array.isArray(value)) { - return { - ok: false, - errors: [ - { - message: getErrorMessageForIncorrectType(value, "list"), - path: [], - }, - ], - }; - } - - const maybeValidItems = value.map((item, index) => transformItem(item, index)); - - return maybeValidItems.reduce>( - (acc, item) => { - if (acc.ok && item.ok) { - return { - ok: true, - value: [...acc.value, item.value], - }; - } - - const errors: ValidationError[] = []; - if (!acc.ok) { - errors.push(...acc.errors); - } - if (!item.ok) { - errors.push(...item.errors); - } - - return { - ok: false, - errors, - }; - }, - { ok: true, value: [] } - ); -} diff --git a/src/core/schemas/builders/literals/booleanLiteral.ts b/src/core/schemas/builders/literals/booleanLiteral.ts deleted file mode 100644 index a83d22c..0000000 --- a/src/core/schemas/builders/literals/booleanLiteral.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Schema, SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; - -export function booleanLiteral(literal: V): Schema { - const schemaCreator = createIdentitySchemaCreator( - SchemaType.BOOLEAN_LITERAL, - (value, { breadcrumbsPrefix = [] } = {}) => { - if (value === literal) { - return { - ok: true, - value: literal, - }; - } else { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, `${literal.toString()}`), - }, - ], - }; - } - } - ); - - return schemaCreator(); -} diff --git a/src/core/schemas/builders/literals/index.ts b/src/core/schemas/builders/literals/index.ts deleted file mode 100644 index d2bf08f..0000000 --- a/src/core/schemas/builders/literals/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { stringLiteral } from "./stringLiteral"; -export { booleanLiteral } from "./booleanLiteral"; diff --git a/src/core/schemas/builders/literals/stringLiteral.ts b/src/core/schemas/builders/literals/stringLiteral.ts deleted file mode 100644 index 3939b76..0000000 --- a/src/core/schemas/builders/literals/stringLiteral.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Schema, SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; - -export function stringLiteral(literal: V): Schema { - const schemaCreator = createIdentitySchemaCreator( - SchemaType.STRING_LITERAL, - (value, { breadcrumbsPrefix = [] } = {}) => { - if (value === literal) { - return { - ok: true, - value: literal, - }; - } else { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, `"${literal}"`), - }, - ], - }; - } - } - ); - - return schemaCreator(); -} diff --git a/src/core/schemas/builders/object-like/getObjectLikeUtils.ts b/src/core/schemas/builders/object-like/getObjectLikeUtils.ts deleted file mode 100644 index 8331d08..0000000 --- a/src/core/schemas/builders/object-like/getObjectLikeUtils.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { BaseSchema } from "../../Schema"; -import { filterObject } from "../../utils/filterObject"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { isPlainObject } from "../../utils/isPlainObject"; -import { getSchemaUtils } from "../schema-utils"; -import { ObjectLikeSchema, ObjectLikeUtils } from "./types"; - -export function getObjectLikeUtils(schema: BaseSchema): ObjectLikeUtils { - return { - withParsedProperties: (properties) => withParsedProperties(schema, properties), - }; -} - -/** - * object-like utils are defined in one file to resolve issues with circular imports - */ - -export function withParsedProperties( - objectLike: BaseSchema, - properties: { [K in keyof Properties]: Properties[K] | ((parsed: ParsedObjectShape) => Properties[K]) } -): ObjectLikeSchema { - const objectSchema: BaseSchema = { - parse: (raw, opts) => { - const parsedObject = objectLike.parse(raw, opts); - if (!parsedObject.ok) { - return parsedObject; - } - - const additionalProperties = Object.entries(properties).reduce>( - (processed, [key, value]) => { - return { - ...processed, - [key]: typeof value === "function" ? value(parsedObject.value) : value, - }; - }, - {} - ); - - return { - ok: true, - value: { - ...parsedObject.value, - ...(additionalProperties as Properties), - }, - }; - }, - - json: (parsed, opts) => { - if (!isPlainObject(parsed)) { - return { - ok: false, - errors: [ - { - path: opts?.breadcrumbsPrefix ?? [], - message: getErrorMessageForIncorrectType(parsed, "object"), - }, - ], - }; - } - - // strip out added properties - const addedPropertyKeys = new Set(Object.keys(properties)); - const parsedWithoutAddedProperties = filterObject( - parsed, - Object.keys(parsed).filter((key) => !addedPropertyKeys.has(key)) - ); - - return objectLike.json(parsedWithoutAddedProperties as ParsedObjectShape, opts); - }, - - getType: () => objectLike.getType(), - }; - - return { - ...objectSchema, - ...getSchemaUtils(objectSchema), - ...getObjectLikeUtils(objectSchema), - }; -} diff --git a/src/core/schemas/builders/object-like/index.ts b/src/core/schemas/builders/object-like/index.ts deleted file mode 100644 index c342e72..0000000 --- a/src/core/schemas/builders/object-like/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { getObjectLikeUtils, withParsedProperties } from "./getObjectLikeUtils"; -export type { ObjectLikeSchema, ObjectLikeUtils } from "./types"; diff --git a/src/core/schemas/builders/object-like/types.ts b/src/core/schemas/builders/object-like/types.ts deleted file mode 100644 index 75b3698..0000000 --- a/src/core/schemas/builders/object-like/types.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { BaseSchema, Schema } from "../../Schema"; - -export type ObjectLikeSchema = Schema & - BaseSchema & - ObjectLikeUtils; - -export interface ObjectLikeUtils { - withParsedProperties: >(properties: { - [K in keyof T]: T[K] | ((parsed: Parsed) => T[K]); - }) => ObjectLikeSchema; -} diff --git a/src/core/schemas/builders/object/index.ts b/src/core/schemas/builders/object/index.ts deleted file mode 100644 index e3f4388..0000000 --- a/src/core/schemas/builders/object/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -export { getObjectUtils, object } from "./object"; -export { objectWithoutOptionalProperties } from "./objectWithoutOptionalProperties"; -export type { - inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas, - inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas, -} from "./objectWithoutOptionalProperties"; -export { isProperty, property } from "./property"; -export type { Property } from "./property"; -export type { - BaseObjectSchema, - inferObjectSchemaFromPropertySchemas, - inferParsedObject, - inferParsedObjectFromPropertySchemas, - inferParsedPropertySchema, - inferRawKey, - inferRawObject, - inferRawObjectFromPropertySchemas, - inferRawPropertySchema, - ObjectSchema, - ObjectUtils, - PropertySchemas, -} from "./types"; diff --git a/src/core/schemas/builders/object/object.ts b/src/core/schemas/builders/object/object.ts deleted file mode 100644 index e00136d..0000000 --- a/src/core/schemas/builders/object/object.ts +++ /dev/null @@ -1,324 +0,0 @@ -import { MaybeValid, Schema, SchemaType, ValidationError } from "../../Schema"; -import { entries } from "../../utils/entries"; -import { filterObject } from "../../utils/filterObject"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { isPlainObject } from "../../utils/isPlainObject"; -import { keys } from "../../utils/keys"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { partition } from "../../utils/partition"; -import { getObjectLikeUtils } from "../object-like"; -import { getSchemaUtils } from "../schema-utils"; -import { isProperty } from "./property"; -import { - BaseObjectSchema, - inferObjectSchemaFromPropertySchemas, - inferParsedObjectFromPropertySchemas, - inferRawObjectFromPropertySchemas, - ObjectSchema, - ObjectUtils, - PropertySchemas, -} from "./types"; - -interface ObjectPropertyWithRawKey { - rawKey: string; - parsedKey: string; - valueSchema: Schema; -} - -export function object>( - schemas: T -): inferObjectSchemaFromPropertySchemas { - const baseSchema: BaseObjectSchema< - inferRawObjectFromPropertySchemas, - inferParsedObjectFromPropertySchemas - > = { - _getRawProperties: () => - Object.entries(schemas).map(([parsedKey, propertySchema]) => - isProperty(propertySchema) ? propertySchema.rawKey : parsedKey - ) as unknown as (keyof inferRawObjectFromPropertySchemas)[], - _getParsedProperties: () => keys(schemas) as unknown as (keyof inferParsedObjectFromPropertySchemas)[], - - parse: (raw, opts) => { - const rawKeyToProperty: Record = {}; - const requiredKeys: string[] = []; - - for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) { - const rawKey = isProperty(schemaOrObjectProperty) ? schemaOrObjectProperty.rawKey : parsedKey; - const valueSchema: Schema = isProperty(schemaOrObjectProperty) - ? schemaOrObjectProperty.valueSchema - : schemaOrObjectProperty; - - const property: ObjectPropertyWithRawKey = { - rawKey, - parsedKey: parsedKey as string, - valueSchema, - }; - - rawKeyToProperty[rawKey] = property; - - if (isSchemaRequired(valueSchema)) { - requiredKeys.push(rawKey); - } - } - - return validateAndTransformObject({ - value: raw, - requiredKeys, - getProperty: (rawKey) => { - const property = rawKeyToProperty[rawKey]; - if (property == null) { - return undefined; - } - return { - transformedKey: property.parsedKey, - transform: (propertyValue) => - property.valueSchema.parse(propertyValue, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), rawKey], - }), - }; - }, - unrecognizedObjectKeys: opts?.unrecognizedObjectKeys, - skipValidation: opts?.skipValidation, - breadcrumbsPrefix: opts?.breadcrumbsPrefix, - omitUndefined: opts?.omitUndefined, - }); - }, - - json: (parsed, opts) => { - const requiredKeys: string[] = []; - - for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) { - const valueSchema: Schema = isProperty(schemaOrObjectProperty) - ? schemaOrObjectProperty.valueSchema - : schemaOrObjectProperty; - - if (isSchemaRequired(valueSchema)) { - requiredKeys.push(parsedKey as string); - } - } - - return validateAndTransformObject({ - value: parsed, - requiredKeys, - getProperty: ( - parsedKey - ): { transformedKey: string; transform: (propertyValue: unknown) => MaybeValid } | undefined => { - const property = schemas[parsedKey as keyof T]; - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (property == null) { - return undefined; - } - - if (isProperty(property)) { - return { - transformedKey: property.rawKey, - transform: (propertyValue) => - property.valueSchema.json(propertyValue, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), parsedKey], - }), - }; - } else { - return { - transformedKey: parsedKey, - transform: (propertyValue) => - property.json(propertyValue, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), parsedKey], - }), - }; - } - }, - unrecognizedObjectKeys: opts?.unrecognizedObjectKeys, - skipValidation: opts?.skipValidation, - breadcrumbsPrefix: opts?.breadcrumbsPrefix, - omitUndefined: opts?.omitUndefined, - }); - }, - - getType: () => SchemaType.OBJECT, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - ...getObjectLikeUtils(baseSchema), - ...getObjectUtils(baseSchema), - }; -} - -function validateAndTransformObject({ - value, - requiredKeys, - getProperty, - unrecognizedObjectKeys = "fail", - skipValidation = false, - breadcrumbsPrefix = [], -}: { - value: unknown; - requiredKeys: string[]; - getProperty: ( - preTransformedKey: string - ) => { transformedKey: string; transform: (propertyValue: unknown) => MaybeValid } | undefined; - unrecognizedObjectKeys: "fail" | "passthrough" | "strip" | undefined; - skipValidation: boolean | undefined; - breadcrumbsPrefix: string[] | undefined; - omitUndefined: boolean | undefined; -}): MaybeValid { - if (!isPlainObject(value)) { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "object"), - }, - ], - }; - } - - const missingRequiredKeys = new Set(requiredKeys); - const errors: ValidationError[] = []; - const transformed: Record = {}; - - for (const [preTransformedKey, preTransformedItemValue] of Object.entries(value)) { - const property = getProperty(preTransformedKey); - - if (property != null) { - missingRequiredKeys.delete(preTransformedKey); - - const value = property.transform(preTransformedItemValue); - if (value.ok) { - transformed[property.transformedKey] = value.value; - } else { - transformed[preTransformedKey] = preTransformedItemValue; - errors.push(...value.errors); - } - } else { - switch (unrecognizedObjectKeys) { - case "fail": - errors.push({ - path: [...breadcrumbsPrefix, preTransformedKey], - message: `Unexpected key "${preTransformedKey}"`, - }); - break; - case "strip": - break; - case "passthrough": - transformed[preTransformedKey] = preTransformedItemValue; - break; - } - } - } - - errors.push( - ...requiredKeys - .filter((key) => missingRequiredKeys.has(key)) - .map((key) => ({ - path: breadcrumbsPrefix, - message: `Missing required key "${key}"`, - })) - ); - - if (errors.length === 0 || skipValidation) { - return { - ok: true, - value: transformed as Transformed, - }; - } else { - return { - ok: false, - errors, - }; - } -} - -export function getObjectUtils(schema: BaseObjectSchema): ObjectUtils { - return { - extend: (extension: ObjectSchema) => { - const baseSchema: BaseObjectSchema = { - _getParsedProperties: () => [...schema._getParsedProperties(), ...extension._getParsedProperties()], - _getRawProperties: () => [...schema._getRawProperties(), ...extension._getRawProperties()], - parse: (raw, opts) => { - return validateAndTransformExtendedObject({ - extensionKeys: extension._getRawProperties(), - value: raw, - transformBase: (rawBase) => schema.parse(rawBase, opts), - transformExtension: (rawExtension) => extension.parse(rawExtension, opts), - }); - }, - json: (parsed, opts) => { - return validateAndTransformExtendedObject({ - extensionKeys: extension._getParsedProperties(), - value: parsed, - transformBase: (parsedBase) => schema.json(parsedBase, opts), - transformExtension: (parsedExtension) => extension.json(parsedExtension, opts), - }); - }, - getType: () => SchemaType.OBJECT, - }; - - return { - ...baseSchema, - ...getSchemaUtils(baseSchema), - ...getObjectLikeUtils(baseSchema), - ...getObjectUtils(baseSchema), - }; - }, - }; -} - -function validateAndTransformExtendedObject({ - extensionKeys, - value, - transformBase, - transformExtension, -}: { - extensionKeys: (keyof PreTransformedExtension)[]; - value: unknown; - transformBase: (value: unknown) => MaybeValid; - transformExtension: (value: unknown) => MaybeValid; -}): MaybeValid { - const extensionPropertiesSet = new Set(extensionKeys); - const [extensionProperties, baseProperties] = partition(keys(value), (key) => - extensionPropertiesSet.has(key as keyof PreTransformedExtension) - ); - - const transformedBase = transformBase(filterObject(value, baseProperties)); - const transformedExtension = transformExtension(filterObject(value, extensionProperties)); - - if (transformedBase.ok && transformedExtension.ok) { - return { - ok: true, - value: { - ...transformedBase.value, - ...transformedExtension.value, - }, - }; - } else { - return { - ok: false, - errors: [ - ...(transformedBase.ok ? [] : transformedBase.errors), - ...(transformedExtension.ok ? [] : transformedExtension.errors), - ], - }; - } -} - -function isSchemaRequired(schema: Schema): boolean { - return !isSchemaOptional(schema); -} - -function isSchemaOptional(schema: Schema): boolean { - switch (schema.getType()) { - case SchemaType.ANY: - case SchemaType.UNKNOWN: - case SchemaType.OPTIONAL: - return true; - default: - return false; - } -} diff --git a/src/core/schemas/builders/object/objectWithoutOptionalProperties.ts b/src/core/schemas/builders/object/objectWithoutOptionalProperties.ts deleted file mode 100644 index a0951f4..0000000 --- a/src/core/schemas/builders/object/objectWithoutOptionalProperties.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { object } from "./object"; -import { inferParsedPropertySchema, inferRawObjectFromPropertySchemas, ObjectSchema, PropertySchemas } from "./types"; - -export function objectWithoutOptionalProperties>( - schemas: T -): inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas { - return object(schemas) as unknown as inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas; -} - -export type inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas> = - ObjectSchema< - inferRawObjectFromPropertySchemas, - inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas - >; - -export type inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas> = { - [K in keyof T]: inferParsedPropertySchema; -}; diff --git a/src/core/schemas/builders/object/property.ts b/src/core/schemas/builders/object/property.ts deleted file mode 100644 index d245c4b..0000000 --- a/src/core/schemas/builders/object/property.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Schema } from "../../Schema"; - -export function property( - rawKey: RawKey, - valueSchema: Schema -): Property { - return { - rawKey, - valueSchema, - isProperty: true, - }; -} - -export interface Property { - rawKey: RawKey; - valueSchema: Schema; - isProperty: true; -} - -export function isProperty>(maybeProperty: unknown): maybeProperty is O { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - return (maybeProperty as O).isProperty; -} diff --git a/src/core/schemas/builders/object/types.ts b/src/core/schemas/builders/object/types.ts deleted file mode 100644 index de9bb40..0000000 --- a/src/core/schemas/builders/object/types.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { BaseSchema, inferParsed, inferRaw, Schema } from "../../Schema"; -import { addQuestionMarksToNullableProperties } from "../../utils/addQuestionMarksToNullableProperties"; -import { ObjectLikeUtils } from "../object-like"; -import { SchemaUtils } from "../schema-utils"; -import { Property } from "./property"; - -export type ObjectSchema = BaseObjectSchema & - ObjectLikeUtils & - ObjectUtils & - SchemaUtils; - -export interface BaseObjectSchema extends BaseSchema { - _getRawProperties: () => (keyof Raw)[]; - _getParsedProperties: () => (keyof Parsed)[]; -} - -export interface ObjectUtils { - extend: ( - schemas: ObjectSchema - ) => ObjectSchema; -} - -export type inferRawObject> = O extends ObjectSchema ? Raw : never; - -export type inferParsedObject> = O extends ObjectSchema - ? Parsed - : never; - -export type inferObjectSchemaFromPropertySchemas> = ObjectSchema< - inferRawObjectFromPropertySchemas, - inferParsedObjectFromPropertySchemas ->; - -export type inferRawObjectFromPropertySchemas> = - addQuestionMarksToNullableProperties<{ - [ParsedKey in keyof T as inferRawKey]: inferRawPropertySchema; - }>; - -export type inferParsedObjectFromPropertySchemas> = - addQuestionMarksToNullableProperties<{ - [K in keyof T]: inferParsedPropertySchema; - }>; - -export type PropertySchemas = Record< - ParsedKeys, - Property | Schema ->; - -export type inferRawPropertySchema

| Schema> = P extends Property< - any, - infer Raw, - any -> - ? Raw - : P extends Schema - ? inferRaw

- : never; - -export type inferParsedPropertySchema

| Schema> = P extends Property< - any, - any, - infer Parsed -> - ? Parsed - : P extends Schema - ? inferParsed

- : never; - -export type inferRawKey< - ParsedKey extends string | number | symbol, - P extends Property | Schema -> = P extends Property ? Raw : ParsedKey; diff --git a/src/core/schemas/builders/primitives/any.ts b/src/core/schemas/builders/primitives/any.ts deleted file mode 100644 index fcaeb04..0000000 --- a/src/core/schemas/builders/primitives/any.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; - -export const any = createIdentitySchemaCreator(SchemaType.ANY, (value) => ({ ok: true, value })); diff --git a/src/core/schemas/builders/primitives/boolean.ts b/src/core/schemas/builders/primitives/boolean.ts deleted file mode 100644 index fad6056..0000000 --- a/src/core/schemas/builders/primitives/boolean.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; - -export const boolean = createIdentitySchemaCreator( - SchemaType.BOOLEAN, - (value, { breadcrumbsPrefix = [] } = {}) => { - if (typeof value === "boolean") { - return { - ok: true, - value, - }; - } else { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "boolean"), - }, - ], - }; - } - } -); diff --git a/src/core/schemas/builders/primitives/index.ts b/src/core/schemas/builders/primitives/index.ts deleted file mode 100644 index 788f941..0000000 --- a/src/core/schemas/builders/primitives/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { any } from "./any"; -export { boolean } from "./boolean"; -export { number } from "./number"; -export { string } from "./string"; -export { unknown } from "./unknown"; diff --git a/src/core/schemas/builders/primitives/number.ts b/src/core/schemas/builders/primitives/number.ts deleted file mode 100644 index c268945..0000000 --- a/src/core/schemas/builders/primitives/number.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; - -export const number = createIdentitySchemaCreator( - SchemaType.NUMBER, - (value, { breadcrumbsPrefix = [] } = {}) => { - if (typeof value === "number") { - return { - ok: true, - value, - }; - } else { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "number"), - }, - ], - }; - } - } -); diff --git a/src/core/schemas/builders/primitives/string.ts b/src/core/schemas/builders/primitives/string.ts deleted file mode 100644 index 949f1f2..0000000 --- a/src/core/schemas/builders/primitives/string.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; - -export const string = createIdentitySchemaCreator( - SchemaType.STRING, - (value, { breadcrumbsPrefix = [] } = {}) => { - if (typeof value === "string") { - return { - ok: true, - value, - }; - } else { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "string"), - }, - ], - }; - } - } -); diff --git a/src/core/schemas/builders/primitives/unknown.ts b/src/core/schemas/builders/primitives/unknown.ts deleted file mode 100644 index 4d52495..0000000 --- a/src/core/schemas/builders/primitives/unknown.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { SchemaType } from "../../Schema"; -import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator"; - -export const unknown = createIdentitySchemaCreator(SchemaType.UNKNOWN, (value) => ({ ok: true, value })); diff --git a/src/core/schemas/builders/record/index.ts b/src/core/schemas/builders/record/index.ts deleted file mode 100644 index 82e25c5..0000000 --- a/src/core/schemas/builders/record/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { record } from "./record"; -export type { BaseRecordSchema, RecordSchema } from "./types"; diff --git a/src/core/schemas/builders/record/record.ts b/src/core/schemas/builders/record/record.ts deleted file mode 100644 index 6683ac3..0000000 --- a/src/core/schemas/builders/record/record.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { MaybeValid, Schema, SchemaType, ValidationError } from "../../Schema"; -import { entries } from "../../utils/entries"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { isPlainObject } from "../../utils/isPlainObject"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { getSchemaUtils } from "../schema-utils"; -import { BaseRecordSchema, RecordSchema } from "./types"; - -export function record( - keySchema: Schema, - valueSchema: Schema -): RecordSchema { - const baseSchema: BaseRecordSchema = { - parse: (raw, opts) => { - return validateAndTransformRecord({ - value: raw, - isKeyNumeric: keySchema.getType() === SchemaType.NUMBER, - transformKey: (key) => - keySchema.parse(key, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key} (key)`], - }), - transformValue: (value, key) => - valueSchema.parse(value, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key}`], - }), - breadcrumbsPrefix: opts?.breadcrumbsPrefix, - }); - }, - json: (parsed, opts) => { - return validateAndTransformRecord({ - value: parsed, - isKeyNumeric: keySchema.getType() === SchemaType.NUMBER, - transformKey: (key) => - keySchema.json(key, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key} (key)`], - }), - transformValue: (value, key) => - valueSchema.json(value, { - ...opts, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key}`], - }), - breadcrumbsPrefix: opts?.breadcrumbsPrefix, - }); - }, - getType: () => SchemaType.RECORD, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - }; -} - -function validateAndTransformRecord({ - value, - isKeyNumeric, - transformKey, - transformValue, - breadcrumbsPrefix = [], -}: { - value: unknown; - isKeyNumeric: boolean; - transformKey: (key: string | number) => MaybeValid; - transformValue: (value: unknown, key: string | number) => MaybeValid; - breadcrumbsPrefix: string[] | undefined; -}): MaybeValid> { - if (!isPlainObject(value)) { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "object"), - }, - ], - }; - } - - return entries(value).reduce>>( - (accPromise, [stringKey, value]) => { - // skip nullish keys - if (value == null) { - return accPromise; - } - - const acc = accPromise; - - let key: string | number = stringKey; - if (isKeyNumeric) { - const numberKey = stringKey.length > 0 ? Number(stringKey) : NaN; - if (!isNaN(numberKey)) { - key = numberKey; - } - } - const transformedKey = transformKey(key); - - const transformedValue = transformValue(value, key); - - if (acc.ok && transformedKey.ok && transformedValue.ok) { - return { - ok: true, - value: { - ...acc.value, - [transformedKey.value]: transformedValue.value, - }, - }; - } - - const errors: ValidationError[] = []; - if (!acc.ok) { - errors.push(...acc.errors); - } - if (!transformedKey.ok) { - errors.push(...transformedKey.errors); - } - if (!transformedValue.ok) { - errors.push(...transformedValue.errors); - } - - return { - ok: false, - errors, - }; - }, - { ok: true, value: {} as Record } - ); -} diff --git a/src/core/schemas/builders/record/types.ts b/src/core/schemas/builders/record/types.ts deleted file mode 100644 index eb82cc7..0000000 --- a/src/core/schemas/builders/record/types.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { BaseSchema } from "../../Schema"; -import { SchemaUtils } from "../schema-utils"; - -export type RecordSchema< - RawKey extends string | number, - RawValue, - ParsedKey extends string | number, - ParsedValue -> = BaseRecordSchema & - SchemaUtils, Record>; - -export type BaseRecordSchema< - RawKey extends string | number, - RawValue, - ParsedKey extends string | number, - ParsedValue -> = BaseSchema, Record>; diff --git a/src/core/schemas/builders/schema-utils/JsonError.ts b/src/core/schemas/builders/schema-utils/JsonError.ts deleted file mode 100644 index 2b89ca0..0000000 --- a/src/core/schemas/builders/schema-utils/JsonError.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { ValidationError } from "../../Schema"; -import { stringifyValidationError } from "./stringifyValidationErrors"; - -export class JsonError extends Error { - constructor(public readonly errors: ValidationError[]) { - super(errors.map(stringifyValidationError).join("; ")); - Object.setPrototypeOf(this, JsonError.prototype); - } -} diff --git a/src/core/schemas/builders/schema-utils/ParseError.ts b/src/core/schemas/builders/schema-utils/ParseError.ts deleted file mode 100644 index d056eb4..0000000 --- a/src/core/schemas/builders/schema-utils/ParseError.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { ValidationError } from "../../Schema"; -import { stringifyValidationError } from "./stringifyValidationErrors"; - -export class ParseError extends Error { - constructor(public readonly errors: ValidationError[]) { - super(errors.map(stringifyValidationError).join("; ")); - Object.setPrototypeOf(this, ParseError.prototype); - } -} diff --git a/src/core/schemas/builders/schema-utils/getSchemaUtils.ts b/src/core/schemas/builders/schema-utils/getSchemaUtils.ts deleted file mode 100644 index 79ecad9..0000000 --- a/src/core/schemas/builders/schema-utils/getSchemaUtils.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { BaseSchema, Schema, SchemaOptions, SchemaType } from "../../Schema"; -import { JsonError } from "./JsonError"; -import { ParseError } from "./ParseError"; - -export interface SchemaUtils { - optional: () => Schema; - transform: (transformer: SchemaTransformer) => Schema; - parseOrThrow: (raw: unknown, opts?: SchemaOptions) => Parsed; - jsonOrThrow: (raw: unknown, opts?: SchemaOptions) => Raw; -} - -export interface SchemaTransformer { - transform: (parsed: Parsed) => Transformed; - untransform: (transformed: any) => Parsed; -} - -export function getSchemaUtils(schema: BaseSchema): SchemaUtils { - return { - optional: () => optional(schema), - transform: (transformer) => transform(schema, transformer), - parseOrThrow: (raw, opts) => { - const parsed = schema.parse(raw, opts); - if (parsed.ok) { - return parsed.value; - } - throw new ParseError(parsed.errors); - }, - jsonOrThrow: (parsed, opts) => { - const raw = schema.json(parsed, opts); - if (raw.ok) { - return raw.value; - } - throw new JsonError(raw.errors); - }, - }; -} - -/** - * schema utils are defined in one file to resolve issues with circular imports - */ - -export function optional( - schema: BaseSchema -): Schema { - const baseSchema: BaseSchema = { - parse: (raw, opts) => { - if (raw == null) { - return { - ok: true, - value: undefined, - }; - } - return schema.parse(raw, opts); - }, - json: (parsed, opts) => { - if (opts?.omitUndefined && parsed === undefined) { - return { - ok: true, - value: undefined, - }; - } - if (parsed == null) { - return { - ok: true, - value: null, - }; - } - return schema.json(parsed, opts); - }, - getType: () => SchemaType.OPTIONAL, - }; - - return { - ...baseSchema, - ...getSchemaUtils(baseSchema), - }; -} - -export function transform( - schema: BaseSchema, - transformer: SchemaTransformer -): Schema { - const baseSchema: BaseSchema = { - parse: (raw, opts) => { - const parsed = schema.parse(raw, opts); - if (!parsed.ok) { - return parsed; - } - return { - ok: true, - value: transformer.transform(parsed.value), - }; - }, - json: (transformed, opts) => { - const parsed = transformer.untransform(transformed); - return schema.json(parsed, opts); - }, - getType: () => schema.getType(), - }; - - return { - ...baseSchema, - ...getSchemaUtils(baseSchema), - }; -} diff --git a/src/core/schemas/builders/schema-utils/index.ts b/src/core/schemas/builders/schema-utils/index.ts deleted file mode 100644 index aa04e05..0000000 --- a/src/core/schemas/builders/schema-utils/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { getSchemaUtils, optional, transform } from "./getSchemaUtils"; -export type { SchemaUtils } from "./getSchemaUtils"; -export { JsonError } from "./JsonError"; -export { ParseError } from "./ParseError"; diff --git a/src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts b/src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts deleted file mode 100644 index 4160f0a..0000000 --- a/src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ValidationError } from "../../Schema"; - -export function stringifyValidationError(error: ValidationError): string { - if (error.path.length === 0) { - return error.message; - } - return `${error.path.join(" -> ")}: ${error.message}`; -} diff --git a/src/core/schemas/builders/set/index.ts b/src/core/schemas/builders/set/index.ts deleted file mode 100644 index f3310e8..0000000 --- a/src/core/schemas/builders/set/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { set } from "./set"; diff --git a/src/core/schemas/builders/set/set.ts b/src/core/schemas/builders/set/set.ts deleted file mode 100644 index e9e6bb7..0000000 --- a/src/core/schemas/builders/set/set.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { BaseSchema, Schema, SchemaType } from "../../Schema"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { list } from "../list"; -import { getSchemaUtils } from "../schema-utils"; - -export function set(schema: Schema): Schema> { - const listSchema = list(schema); - const baseSchema: BaseSchema> = { - parse: (raw, opts) => { - const parsedList = listSchema.parse(raw, opts); - if (parsedList.ok) { - return { - ok: true, - value: new Set(parsedList.value), - }; - } else { - return parsedList; - } - }, - json: (parsed, opts) => { - if (!(parsed instanceof Set)) { - return { - ok: false, - errors: [ - { - path: opts?.breadcrumbsPrefix ?? [], - message: getErrorMessageForIncorrectType(parsed, "Set"), - }, - ], - }; - } - const jsonList = listSchema.json([...parsed], opts); - return jsonList; - }, - getType: () => SchemaType.SET, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - }; -} diff --git a/src/core/schemas/builders/undiscriminated-union/index.ts b/src/core/schemas/builders/undiscriminated-union/index.ts deleted file mode 100644 index 75b71cb..0000000 --- a/src/core/schemas/builders/undiscriminated-union/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type { - inferParsedUnidiscriminatedUnionSchema, - inferRawUnidiscriminatedUnionSchema, - UndiscriminatedUnionSchema, -} from "./types"; -export { undiscriminatedUnion } from "./undiscriminatedUnion"; diff --git a/src/core/schemas/builders/undiscriminated-union/types.ts b/src/core/schemas/builders/undiscriminated-union/types.ts deleted file mode 100644 index 43e7108..0000000 --- a/src/core/schemas/builders/undiscriminated-union/types.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { inferParsed, inferRaw, Schema } from "../../Schema"; - -export type UndiscriminatedUnionSchema = Schema< - inferRawUnidiscriminatedUnionSchema, - inferParsedUnidiscriminatedUnionSchema ->; - -export type inferRawUnidiscriminatedUnionSchema = inferRaw; - -export type inferParsedUnidiscriminatedUnionSchema = inferParsed; diff --git a/src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts b/src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts deleted file mode 100644 index 21ed3df..0000000 --- a/src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { BaseSchema, MaybeValid, Schema, SchemaOptions, SchemaType, ValidationError } from "../../Schema"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { getSchemaUtils } from "../schema-utils"; -import { inferParsedUnidiscriminatedUnionSchema, inferRawUnidiscriminatedUnionSchema } from "./types"; - -export function undiscriminatedUnion, ...Schema[]]>( - schemas: Schemas -): Schema, inferParsedUnidiscriminatedUnionSchema> { - const baseSchema: BaseSchema< - inferRawUnidiscriminatedUnionSchema, - inferParsedUnidiscriminatedUnionSchema - > = { - parse: (raw, opts) => { - return validateAndTransformUndiscriminatedUnion>( - (schema, opts) => schema.parse(raw, opts), - schemas, - opts - ); - }, - json: (parsed, opts) => { - return validateAndTransformUndiscriminatedUnion>( - (schema, opts) => schema.json(parsed, opts), - schemas, - opts - ); - }, - getType: () => SchemaType.UNDISCRIMINATED_UNION, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - }; -} - -function validateAndTransformUndiscriminatedUnion( - transform: (schema: Schema, opts: SchemaOptions) => MaybeValid, - schemas: Schema[], - opts: SchemaOptions | undefined -): MaybeValid { - const errors: ValidationError[] = []; - for (const [index, schema] of schemas.entries()) { - const transformed = transform(schema, { ...opts, skipValidation: false }); - if (transformed.ok) { - return transformed; - } else { - for (const error of transformed.errors) { - errors.push({ - path: error.path, - message: `[Variant ${index}] ${error.message}`, - }); - } - } - } - - return { - ok: false, - errors, - }; -} diff --git a/src/core/schemas/builders/union/discriminant.ts b/src/core/schemas/builders/union/discriminant.ts deleted file mode 100644 index 55065bc..0000000 --- a/src/core/schemas/builders/union/discriminant.ts +++ /dev/null @@ -1,14 +0,0 @@ -export function discriminant( - parsedDiscriminant: ParsedDiscriminant, - rawDiscriminant: RawDiscriminant -): Discriminant { - return { - parsedDiscriminant, - rawDiscriminant, - }; -} - -export interface Discriminant { - parsedDiscriminant: ParsedDiscriminant; - rawDiscriminant: RawDiscriminant; -} diff --git a/src/core/schemas/builders/union/index.ts b/src/core/schemas/builders/union/index.ts deleted file mode 100644 index 85fc008..0000000 --- a/src/core/schemas/builders/union/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -export { discriminant } from "./discriminant"; -export type { Discriminant } from "./discriminant"; -export type { - inferParsedDiscriminant, - inferParsedUnion, - inferRawDiscriminant, - inferRawUnion, - UnionSubtypes, -} from "./types"; -export { union } from "./union"; diff --git a/src/core/schemas/builders/union/types.ts b/src/core/schemas/builders/union/types.ts deleted file mode 100644 index 6f82c86..0000000 --- a/src/core/schemas/builders/union/types.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { inferParsedObject, inferRawObject, ObjectSchema } from "../object"; -import { Discriminant } from "./discriminant"; - -export type UnionSubtypes = { - [K in DiscriminantValues]: ObjectSchema; -}; - -export type inferRawUnion, U extends UnionSubtypes> = { - [K in keyof U]: Record, K> & inferRawObject; -}[keyof U]; - -export type inferParsedUnion, U extends UnionSubtypes> = { - [K in keyof U]: Record, K> & inferParsedObject; -}[keyof U]; - -export type inferRawDiscriminant> = D extends string - ? D - : D extends Discriminant - ? Raw - : never; - -export type inferParsedDiscriminant> = D extends string - ? D - : D extends Discriminant - ? Parsed - : never; diff --git a/src/core/schemas/builders/union/union.ts b/src/core/schemas/builders/union/union.ts deleted file mode 100644 index ab61475..0000000 --- a/src/core/schemas/builders/union/union.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { BaseSchema, MaybeValid, SchemaType } from "../../Schema"; -import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType"; -import { isPlainObject } from "../../utils/isPlainObject"; -import { keys } from "../../utils/keys"; -import { maybeSkipValidation } from "../../utils/maybeSkipValidation"; -import { enum_ } from "../enum"; -import { ObjectSchema } from "../object"; -import { getObjectLikeUtils, ObjectLikeSchema } from "../object-like"; -import { getSchemaUtils } from "../schema-utils"; -import { Discriminant } from "./discriminant"; -import { inferParsedDiscriminant, inferParsedUnion, inferRawDiscriminant, inferRawUnion, UnionSubtypes } from "./types"; - -export function union, U extends UnionSubtypes>( - discriminant: D, - union: U -): ObjectLikeSchema, inferParsedUnion> { - const rawDiscriminant = - typeof discriminant === "string" ? discriminant : (discriminant.rawDiscriminant as inferRawDiscriminant); - const parsedDiscriminant = - typeof discriminant === "string" - ? discriminant - : (discriminant.parsedDiscriminant as inferParsedDiscriminant); - - const discriminantValueSchema = enum_(keys(union) as string[]); - - const baseSchema: BaseSchema, inferParsedUnion> = { - parse: (raw, opts) => { - return transformAndValidateUnion({ - value: raw, - discriminant: rawDiscriminant, - transformedDiscriminant: parsedDiscriminant, - transformDiscriminantValue: (discriminantValue) => - discriminantValueSchema.parse(discriminantValue, { - allowUnrecognizedEnumValues: opts?.allowUnrecognizedUnionMembers, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), rawDiscriminant], - }), - getAdditionalPropertiesSchema: (discriminantValue) => union[discriminantValue], - allowUnrecognizedUnionMembers: opts?.allowUnrecognizedUnionMembers, - transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => - additionalPropertiesSchema.parse(additionalProperties, opts), - breadcrumbsPrefix: opts?.breadcrumbsPrefix, - }); - }, - json: (parsed, opts) => { - return transformAndValidateUnion({ - value: parsed, - discriminant: parsedDiscriminant, - transformedDiscriminant: rawDiscriminant, - transformDiscriminantValue: (discriminantValue) => - discriminantValueSchema.json(discriminantValue, { - allowUnrecognizedEnumValues: opts?.allowUnrecognizedUnionMembers, - breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), parsedDiscriminant], - }), - getAdditionalPropertiesSchema: (discriminantValue) => union[discriminantValue], - allowUnrecognizedUnionMembers: opts?.allowUnrecognizedUnionMembers, - transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => - additionalPropertiesSchema.json(additionalProperties, opts), - breadcrumbsPrefix: opts?.breadcrumbsPrefix, - }); - }, - getType: () => SchemaType.UNION, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - ...getObjectLikeUtils(baseSchema), - }; -} - -function transformAndValidateUnion< - TransformedDiscriminant extends string, - TransformedDiscriminantValue extends string, - TransformedAdditionalProperties ->({ - value, - discriminant, - transformedDiscriminant, - transformDiscriminantValue, - getAdditionalPropertiesSchema, - allowUnrecognizedUnionMembers = false, - transformAdditionalProperties, - breadcrumbsPrefix = [], -}: { - value: unknown; - discriminant: string; - transformedDiscriminant: TransformedDiscriminant; - transformDiscriminantValue: (discriminantValue: unknown) => MaybeValid; - getAdditionalPropertiesSchema: (discriminantValue: string) => ObjectSchema | undefined; - allowUnrecognizedUnionMembers: boolean | undefined; - transformAdditionalProperties: ( - additionalProperties: unknown, - additionalPropertiesSchema: ObjectSchema - ) => MaybeValid; - breadcrumbsPrefix: string[] | undefined; -}): MaybeValid & TransformedAdditionalProperties> { - if (!isPlainObject(value)) { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: getErrorMessageForIncorrectType(value, "object"), - }, - ], - }; - } - - const { [discriminant]: discriminantValue, ...additionalProperties } = value; - - if (discriminantValue == null) { - return { - ok: false, - errors: [ - { - path: breadcrumbsPrefix, - message: `Missing discriminant ("${discriminant}")`, - }, - ], - }; - } - - const transformedDiscriminantValue = transformDiscriminantValue(discriminantValue); - if (!transformedDiscriminantValue.ok) { - return { - ok: false, - errors: transformedDiscriminantValue.errors, - }; - } - - const additionalPropertiesSchema = getAdditionalPropertiesSchema(transformedDiscriminantValue.value); - - if (additionalPropertiesSchema == null) { - if (allowUnrecognizedUnionMembers) { - return { - ok: true, - value: { - [transformedDiscriminant]: transformedDiscriminantValue.value, - ...additionalProperties, - } as Record & TransformedAdditionalProperties, - }; - } else { - return { - ok: false, - errors: [ - { - path: [...breadcrumbsPrefix, discriminant], - message: "Unexpected discriminant value", - }, - ], - }; - } - } - - const transformedAdditionalProperties = transformAdditionalProperties( - additionalProperties, - additionalPropertiesSchema - ); - if (!transformedAdditionalProperties.ok) { - return transformedAdditionalProperties; - } - - return { - ok: true, - value: { - [transformedDiscriminant]: discriminantValue, - ...transformedAdditionalProperties.value, - } as Record & TransformedAdditionalProperties, - }; -} diff --git a/src/core/schemas/index.ts b/src/core/schemas/index.ts deleted file mode 100644 index 5429d8b..0000000 --- a/src/core/schemas/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./builders"; -export type { inferParsed, inferRaw, Schema, SchemaOptions } from "./Schema"; diff --git a/src/core/schemas/utils/MaybePromise.ts b/src/core/schemas/utils/MaybePromise.ts deleted file mode 100644 index 9cd354b..0000000 --- a/src/core/schemas/utils/MaybePromise.ts +++ /dev/null @@ -1 +0,0 @@ -export type MaybePromise = T | Promise; diff --git a/src/core/schemas/utils/addQuestionMarksToNullableProperties.ts b/src/core/schemas/utils/addQuestionMarksToNullableProperties.ts deleted file mode 100644 index 4111d70..0000000 --- a/src/core/schemas/utils/addQuestionMarksToNullableProperties.ts +++ /dev/null @@ -1,15 +0,0 @@ -export type addQuestionMarksToNullableProperties = { - [K in OptionalKeys]?: T[K]; -} & Pick>; - -export type OptionalKeys = { - [K in keyof T]-?: undefined extends T[K] - ? K - : null extends T[K] - ? K - : 1 extends (any extends T[K] ? 0 : 1) - ? never - : K; -}[keyof T]; - -export type RequiredKeys = Exclude>; diff --git a/src/core/schemas/utils/createIdentitySchemaCreator.ts b/src/core/schemas/utils/createIdentitySchemaCreator.ts deleted file mode 100644 index de107cf..0000000 --- a/src/core/schemas/utils/createIdentitySchemaCreator.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { getSchemaUtils } from "../builders/schema-utils"; -import { BaseSchema, MaybeValid, Schema, SchemaOptions, SchemaType } from "../Schema"; -import { maybeSkipValidation } from "./maybeSkipValidation"; - -export function createIdentitySchemaCreator( - schemaType: SchemaType, - validate: (value: unknown, opts?: SchemaOptions) => MaybeValid -): () => Schema { - return () => { - const baseSchema: BaseSchema = { - parse: validate, - json: validate, - getType: () => schemaType, - }; - - return { - ...maybeSkipValidation(baseSchema), - ...getSchemaUtils(baseSchema), - }; - }; -} diff --git a/src/core/schemas/utils/entries.ts b/src/core/schemas/utils/entries.ts deleted file mode 100644 index e122952..0000000 --- a/src/core/schemas/utils/entries.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function entries(object: T): [keyof T, T[keyof T]][] { - return Object.entries(object) as [keyof T, T[keyof T]][]; -} diff --git a/src/core/schemas/utils/filterObject.ts b/src/core/schemas/utils/filterObject.ts deleted file mode 100644 index 2c25a34..0000000 --- a/src/core/schemas/utils/filterObject.ts +++ /dev/null @@ -1,10 +0,0 @@ -export function filterObject(obj: T, keysToInclude: K[]): Pick { - const keysToIncludeSet = new Set(keysToInclude); - return Object.entries(obj).reduce((acc, [key, value]) => { - if (keysToIncludeSet.has(key as K)) { - acc[key as K] = value; - } - return acc; - // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter - }, {} as Pick); -} diff --git a/src/core/schemas/utils/getErrorMessageForIncorrectType.ts b/src/core/schemas/utils/getErrorMessageForIncorrectType.ts deleted file mode 100644 index 1a5c310..0000000 --- a/src/core/schemas/utils/getErrorMessageForIncorrectType.ts +++ /dev/null @@ -1,25 +0,0 @@ -export function getErrorMessageForIncorrectType(value: unknown, expectedType: string): string { - return `Expected ${expectedType}. Received ${getTypeAsString(value)}.`; -} - -function getTypeAsString(value: unknown): string { - if (Array.isArray(value)) { - return "list"; - } - if (value === null) { - return "null"; - } - if (value instanceof BigInt) { - return "BigInt"; - } - switch (typeof value) { - case "string": - return `"${value}"`; - case "bigint": - case "number": - case "boolean": - case "undefined": - return `${value}`; - } - return typeof value; -} diff --git a/src/core/schemas/utils/isPlainObject.ts b/src/core/schemas/utils/isPlainObject.ts deleted file mode 100644 index db82a72..0000000 --- a/src/core/schemas/utils/isPlainObject.ts +++ /dev/null @@ -1,17 +0,0 @@ -// borrowed from https://github.com/lodash/lodash/blob/master/isPlainObject.js -export function isPlainObject(value: unknown): value is Record { - if (typeof value !== "object" || value === null) { - return false; - } - - if (Object.getPrototypeOf(value) === null) { - return true; - } - - let proto = value; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - - return Object.getPrototypeOf(value) === proto; -} diff --git a/src/core/schemas/utils/keys.ts b/src/core/schemas/utils/keys.ts deleted file mode 100644 index 0186709..0000000 --- a/src/core/schemas/utils/keys.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function keys(object: T): (keyof T)[] { - return Object.keys(object) as (keyof T)[]; -} diff --git a/src/core/schemas/utils/maybeSkipValidation.ts b/src/core/schemas/utils/maybeSkipValidation.ts deleted file mode 100644 index 86c07ab..0000000 --- a/src/core/schemas/utils/maybeSkipValidation.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { BaseSchema, MaybeValid, SchemaOptions } from "../Schema"; - -export function maybeSkipValidation, Raw, Parsed>(schema: S): S { - return { - ...schema, - json: transformAndMaybeSkipValidation(schema.json), - parse: transformAndMaybeSkipValidation(schema.parse), - }; -} - -function transformAndMaybeSkipValidation( - transform: (value: unknown, opts?: SchemaOptions) => MaybeValid -): (value: unknown, opts?: SchemaOptions) => MaybeValid { - return (value, opts): MaybeValid => { - const transformed = transform(value, opts); - const { skipValidation = false } = opts ?? {}; - if (!transformed.ok && skipValidation) { - // eslint-disable-next-line no-console - console.warn( - [ - "Failed to validate.", - ...transformed.errors.map( - (error) => - " - " + - (error.path.length > 0 ? `${error.path.join(".")}: ${error.message}` : error.message) - ), - ].join("\n") - ); - - return { - ok: true, - value: value as T, - }; - } else { - return transformed; - } - }; -} diff --git a/src/core/schemas/utils/partition.ts b/src/core/schemas/utils/partition.ts deleted file mode 100644 index f58d6f3..0000000 --- a/src/core/schemas/utils/partition.ts +++ /dev/null @@ -1,12 +0,0 @@ -export function partition(items: readonly T[], predicate: (item: T) => boolean): [T[], T[]] { - const trueItems: T[] = [], - falseItems: T[] = []; - for (const item of items) { - if (predicate(item)) { - trueItems.push(item); - } else { - falseItems.push(item); - } - } - return [trueItems, falseItems]; -} diff --git a/src/index.ts b/src/index.ts index 09e283c..7022611 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,4 @@ export * as Cartesia from "./api"; -export { CartesiaClient } from "./wrapper/Client"; +export { CartesiaClient } from "./Client"; export { CartesiaEnvironment } from "./environments"; export { CartesiaError, CartesiaTimeoutError } from "./errors"; -export { WebPlayer } from "./wrapper/WebPlayer"; diff --git a/src/serialization/index.ts b/src/serialization/index.ts deleted file mode 100644 index 3e5335f..0000000 --- a/src/serialization/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./resources"; diff --git a/src/serialization/resources/apiStatus/index.ts b/src/serialization/resources/apiStatus/index.ts deleted file mode 100644 index eea524d..0000000 --- a/src/serialization/resources/apiStatus/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./types"; diff --git a/src/serialization/resources/apiStatus/types/ApiInfo.ts b/src/serialization/resources/apiStatus/types/ApiInfo.ts deleted file mode 100644 index 18dd51e..0000000 --- a/src/serialization/resources/apiStatus/types/ApiInfo.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const ApiInfo: core.serialization.ObjectSchema = - core.serialization.object({ - ok: core.serialization.boolean(), - version: core.serialization.string(), - }); - -export declare namespace ApiInfo { - interface Raw { - ok: boolean; - version: string; - } -} diff --git a/src/serialization/resources/apiStatus/types/index.ts b/src/serialization/resources/apiStatus/types/index.ts deleted file mode 100644 index 1ce4f3e..0000000 --- a/src/serialization/resources/apiStatus/types/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./ApiInfo"; diff --git a/src/serialization/resources/embedding/index.ts b/src/serialization/resources/embedding/index.ts deleted file mode 100644 index eea524d..0000000 --- a/src/serialization/resources/embedding/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./types"; diff --git a/src/serialization/resources/embedding/types/Embedding.ts b/src/serialization/resources/embedding/types/Embedding.ts deleted file mode 100644 index 8bc8e01..0000000 --- a/src/serialization/resources/embedding/types/Embedding.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const Embedding: core.serialization.Schema = - core.serialization.list(core.serialization.number()); - -export declare namespace Embedding { - type Raw = number[]; -} diff --git a/src/serialization/resources/embedding/types/index.ts b/src/serialization/resources/embedding/types/index.ts deleted file mode 100644 index cd604e1..0000000 --- a/src/serialization/resources/embedding/types/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./Embedding"; diff --git a/src/serialization/resources/index.ts b/src/serialization/resources/index.ts deleted file mode 100644 index 61ee374..0000000 --- a/src/serialization/resources/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -export * as apiStatus from "./apiStatus"; -export * from "./apiStatus/types"; -export * as embedding from "./embedding"; -export * from "./embedding/types"; -export * as tts from "./tts"; -export * from "./tts/types"; -export * as voiceChanger from "./voiceChanger"; -export * from "./voiceChanger/types"; -export * as voices from "./voices"; -export * from "./voices/types"; diff --git a/src/serialization/resources/tts/index.ts b/src/serialization/resources/tts/index.ts deleted file mode 100644 index eea524d..0000000 --- a/src/serialization/resources/tts/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./types"; diff --git a/src/serialization/resources/tts/types/CancelContextRequest.ts b/src/serialization/resources/tts/types/CancelContextRequest.ts deleted file mode 100644 index 47e2abc..0000000 --- a/src/serialization/resources/tts/types/CancelContextRequest.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { ContextId } from "./ContextId"; - -export const CancelContextRequest: core.serialization.ObjectSchema< - serializers.CancelContextRequest.Raw, - Cartesia.CancelContextRequest -> = core.serialization.object({ - contextId: core.serialization.property("context_id", ContextId), - cancel: core.serialization.booleanLiteral(true), -}); - -export declare namespace CancelContextRequest { - interface Raw { - context_id: ContextId.Raw; - cancel: true; - } -} diff --git a/src/serialization/resources/tts/types/ContextId.ts b/src/serialization/resources/tts/types/ContextId.ts deleted file mode 100644 index 86d5619..0000000 --- a/src/serialization/resources/tts/types/ContextId.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const ContextId: core.serialization.Schema = - core.serialization.string(); - -export declare namespace ContextId { - type Raw = string; -} diff --git a/src/serialization/resources/tts/types/Controls.ts b/src/serialization/resources/tts/types/Controls.ts deleted file mode 100644 index b89bb6d..0000000 --- a/src/serialization/resources/tts/types/Controls.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { Speed } from "./Speed"; -import { Emotion } from "./Emotion"; - -export const Controls: core.serialization.ObjectSchema = - core.serialization.object({ - speed: Speed, - emotion: Emotion, - }); - -export declare namespace Controls { - interface Raw { - speed: Speed.Raw; - emotion: Emotion.Raw; - } -} diff --git a/src/serialization/resources/tts/types/Emotion.ts b/src/serialization/resources/tts/types/Emotion.ts deleted file mode 100644 index 910109d..0000000 --- a/src/serialization/resources/tts/types/Emotion.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const Emotion: core.serialization.Schema = core.serialization.enum_([ - "anger:lowest", - "anger:low", - "anger", - "anger:high", - "anger:highest", - "positivity:lowest", - "positivity:low", - "positivity", - "positivity:high", - "positivity:highest", - "surprise:lowest", - "surprise:high", - "surprise:highest", - "sadness:lowest", - "sadness:low", - "sadness", - "curiosity:low", - "curiosity", - "curiosity:high", - "curiosity:highest", -]); - -export declare namespace Emotion { - type Raw = - | "anger:lowest" - | "anger:low" - | "anger" - | "anger:high" - | "anger:highest" - | "positivity:lowest" - | "positivity:low" - | "positivity" - | "positivity:high" - | "positivity:highest" - | "surprise:lowest" - | "surprise:high" - | "surprise:highest" - | "sadness:lowest" - | "sadness:low" - | "sadness" - | "curiosity:low" - | "curiosity" - | "curiosity:high" - | "curiosity:highest"; -} diff --git a/src/serialization/resources/tts/types/GenerationRequest.ts b/src/serialization/resources/tts/types/GenerationRequest.ts deleted file mode 100644 index d985791..0000000 --- a/src/serialization/resources/tts/types/GenerationRequest.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { TtsRequestVoiceSpecifier } from "./TtsRequestVoiceSpecifier"; -import { SupportedLanguage } from "./SupportedLanguage"; -import { WebSocketRawOutputFormat } from "./WebSocketRawOutputFormat"; -import { ContextId } from "./ContextId"; - -export const GenerationRequest: core.serialization.ObjectSchema< - serializers.GenerationRequest.Raw, - Cartesia.GenerationRequest -> = core.serialization.object({ - modelId: core.serialization.property("model_id", core.serialization.string()), - transcript: core.serialization.string(), - voice: TtsRequestVoiceSpecifier, - language: SupportedLanguage.optional(), - outputFormat: core.serialization.property("output_format", WebSocketRawOutputFormat), - duration: core.serialization.number().optional(), - contextId: core.serialization.property("context_id", ContextId), - continue: core.serialization.boolean().optional(), - addTimestamps: core.serialization.property("add_timestamps", core.serialization.boolean().optional()), -}); - -export declare namespace GenerationRequest { - interface Raw { - model_id: string; - transcript: string; - voice: TtsRequestVoiceSpecifier.Raw; - language?: SupportedLanguage.Raw | null; - output_format: WebSocketRawOutputFormat.Raw; - duration?: number | null; - context_id: ContextId.Raw; - continue?: boolean | null; - add_timestamps?: boolean | null; - } -} diff --git a/src/serialization/resources/tts/types/Mp3OutputFormat.ts b/src/serialization/resources/tts/types/Mp3OutputFormat.ts deleted file mode 100644 index d099ddc..0000000 --- a/src/serialization/resources/tts/types/Mp3OutputFormat.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const Mp3OutputFormat: core.serialization.ObjectSchema< - serializers.Mp3OutputFormat.Raw, - Cartesia.Mp3OutputFormat -> = core.serialization.object({ - sampleRate: core.serialization.property("sample_rate", core.serialization.number()), - bitRate: core.serialization.property("bit_rate", core.serialization.number()), -}); - -export declare namespace Mp3OutputFormat { - interface Raw { - sample_rate: number; - bit_rate: number; - } -} diff --git a/src/serialization/resources/tts/types/NaturalSpecifier.ts b/src/serialization/resources/tts/types/NaturalSpecifier.ts deleted file mode 100644 index 865f64a..0000000 --- a/src/serialization/resources/tts/types/NaturalSpecifier.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const NaturalSpecifier: core.serialization.Schema = - core.serialization.enum_(["slowest", "slow", "normal", "fast", "fastest"]); - -export declare namespace NaturalSpecifier { - type Raw = "slowest" | "slow" | "normal" | "fast" | "fastest"; -} diff --git a/src/serialization/resources/tts/types/NumericalSpecifier.ts b/src/serialization/resources/tts/types/NumericalSpecifier.ts deleted file mode 100644 index 02a7731..0000000 --- a/src/serialization/resources/tts/types/NumericalSpecifier.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const NumericalSpecifier: core.serialization.Schema< - serializers.NumericalSpecifier.Raw, - Cartesia.NumericalSpecifier -> = core.serialization.number(); - -export declare namespace NumericalSpecifier { - type Raw = number; -} diff --git a/src/serialization/resources/tts/types/RawEncoding.ts b/src/serialization/resources/tts/types/RawEncoding.ts deleted file mode 100644 index 508fdce..0000000 --- a/src/serialization/resources/tts/types/RawEncoding.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const RawEncoding: core.serialization.Schema = - core.serialization.enum_(["pcm_f32le", "pcm_s16le", "pcm_mulaw", "pcm_alaw"]); - -export declare namespace RawEncoding { - type Raw = "pcm_f32le" | "pcm_s16le" | "pcm_mulaw" | "pcm_alaw"; -} diff --git a/src/serialization/resources/tts/types/RawOutputFormat.ts b/src/serialization/resources/tts/types/RawOutputFormat.ts deleted file mode 100644 index 62122f7..0000000 --- a/src/serialization/resources/tts/types/RawOutputFormat.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { RawEncoding } from "./RawEncoding"; - -export const RawOutputFormat: core.serialization.ObjectSchema< - serializers.RawOutputFormat.Raw, - Cartesia.RawOutputFormat -> = core.serialization.object({ - encoding: RawEncoding, - sampleRate: core.serialization.property("sample_rate", core.serialization.number()), -}); - -export declare namespace RawOutputFormat { - interface Raw { - encoding: RawEncoding.Raw; - sample_rate: number; - } -} diff --git a/src/serialization/resources/tts/types/Speed.ts b/src/serialization/resources/tts/types/Speed.ts deleted file mode 100644 index 20343cf..0000000 --- a/src/serialization/resources/tts/types/Speed.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { NumericalSpecifier } from "./NumericalSpecifier"; -import { NaturalSpecifier } from "./NaturalSpecifier"; - -export const Speed: core.serialization.Schema = - core.serialization.undiscriminatedUnion([NumericalSpecifier, NaturalSpecifier]); - -export declare namespace Speed { - type Raw = NumericalSpecifier.Raw | NaturalSpecifier.Raw; -} diff --git a/src/serialization/resources/tts/types/SupportedLanguage.ts b/src/serialization/resources/tts/types/SupportedLanguage.ts deleted file mode 100644 index 2065aa7..0000000 --- a/src/serialization/resources/tts/types/SupportedLanguage.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const SupportedLanguage: core.serialization.Schema< - serializers.SupportedLanguage.Raw, - Cartesia.SupportedLanguage -> = core.serialization.enum_([ - "en", - "fr", - "de", - "es", - "pt", - "zh", - "ja", - "hi", - "it", - "ko", - "nl", - "pl", - "ru", - "sv", - "tr", -]); - -export declare namespace SupportedLanguage { - type Raw = "en" | "fr" | "de" | "es" | "pt" | "zh" | "ja" | "hi" | "it" | "ko" | "nl" | "pl" | "ru" | "sv" | "tr"; -} diff --git a/src/serialization/resources/tts/types/TtsRequest.ts b/src/serialization/resources/tts/types/TtsRequest.ts deleted file mode 100644 index 685a0b5..0000000 --- a/src/serialization/resources/tts/types/TtsRequest.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { TtsRequestVoiceSpecifier } from "./TtsRequestVoiceSpecifier"; -import { SupportedLanguage } from "./SupportedLanguage"; -import { OutputFormat } from "./OutputFormat"; - -export const TtsRequest: core.serialization.ObjectSchema = - core.serialization.object({ - modelId: core.serialization.property("model_id", core.serialization.string()), - transcript: core.serialization.string(), - voice: TtsRequestVoiceSpecifier, - language: SupportedLanguage.optional(), - outputFormat: core.serialization.property("output_format", OutputFormat), - duration: core.serialization.number().optional(), - }); - -export declare namespace TtsRequest { - interface Raw { - model_id: string; - transcript: string; - voice: TtsRequestVoiceSpecifier.Raw; - language?: SupportedLanguage.Raw | null; - output_format: OutputFormat.Raw; - duration?: number | null; - } -} diff --git a/src/serialization/resources/tts/types/TtsRequestEmbeddingSpecifier.ts b/src/serialization/resources/tts/types/TtsRequestEmbeddingSpecifier.ts deleted file mode 100644 index 83a0a6c..0000000 --- a/src/serialization/resources/tts/types/TtsRequestEmbeddingSpecifier.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { Embedding } from "../../embedding/types/Embedding"; -import { Controls } from "./Controls"; - -export const TtsRequestEmbeddingSpecifier: core.serialization.ObjectSchema< - serializers.TtsRequestEmbeddingSpecifier.Raw, - Cartesia.TtsRequestEmbeddingSpecifier -> = core.serialization.object({ - mode: core.serialization.stringLiteral("embedding"), - embedding: Embedding, - experimentalControls: core.serialization.property("__experimental_controls", Controls.optional()), -}); - -export declare namespace TtsRequestEmbeddingSpecifier { - interface Raw { - mode: "embedding"; - embedding: Embedding.Raw; - __experimental_controls?: Controls.Raw | null; - } -} diff --git a/src/serialization/resources/tts/types/TtsRequestIdSpecifier.ts b/src/serialization/resources/tts/types/TtsRequestIdSpecifier.ts deleted file mode 100644 index 26ac33c..0000000 --- a/src/serialization/resources/tts/types/TtsRequestIdSpecifier.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { VoiceId } from "../../voices/types/VoiceId"; -import { Controls } from "./Controls"; - -export const TtsRequestIdSpecifier: core.serialization.ObjectSchema< - serializers.TtsRequestIdSpecifier.Raw, - Cartesia.TtsRequestIdSpecifier -> = core.serialization.object({ - mode: core.serialization.stringLiteral("id"), - id: VoiceId, - experimentalControls: core.serialization.property("__experimental_controls", Controls.optional()), -}); - -export declare namespace TtsRequestIdSpecifier { - interface Raw { - mode: "id"; - id: VoiceId.Raw; - __experimental_controls?: Controls.Raw | null; - } -} diff --git a/src/serialization/resources/tts/types/TtsRequestVoiceSpecifier.ts b/src/serialization/resources/tts/types/TtsRequestVoiceSpecifier.ts deleted file mode 100644 index c2a69c0..0000000 --- a/src/serialization/resources/tts/types/TtsRequestVoiceSpecifier.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { TtsRequestIdSpecifier } from "./TtsRequestIdSpecifier"; -import { TtsRequestEmbeddingSpecifier } from "./TtsRequestEmbeddingSpecifier"; - -export const TtsRequestVoiceSpecifier: core.serialization.Schema< - serializers.TtsRequestVoiceSpecifier.Raw, - Cartesia.TtsRequestVoiceSpecifier -> = core.serialization.undiscriminatedUnion([TtsRequestIdSpecifier, TtsRequestEmbeddingSpecifier]); - -export declare namespace TtsRequestVoiceSpecifier { - type Raw = TtsRequestIdSpecifier.Raw | TtsRequestEmbeddingSpecifier.Raw; -} diff --git a/src/serialization/resources/tts/types/WavOutputFormat.ts b/src/serialization/resources/tts/types/WavOutputFormat.ts deleted file mode 100644 index 2ddd0ad..0000000 --- a/src/serialization/resources/tts/types/WavOutputFormat.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { RawOutputFormat } from "./RawOutputFormat"; - -export const WavOutputFormat: core.serialization.ObjectSchema< - serializers.WavOutputFormat.Raw, - Cartesia.WavOutputFormat -> = core.serialization.object({}).extend(RawOutputFormat); - -export declare namespace WavOutputFormat { - interface Raw extends RawOutputFormat.Raw {} -} diff --git a/src/serialization/resources/tts/types/WebSocketBaseResponse.ts b/src/serialization/resources/tts/types/WebSocketBaseResponse.ts deleted file mode 100644 index 2bdb226..0000000 --- a/src/serialization/resources/tts/types/WebSocketBaseResponse.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { ContextId } from "./ContextId"; - -export const WebSocketBaseResponse: core.serialization.ObjectSchema< - serializers.WebSocketBaseResponse.Raw, - Cartesia.WebSocketBaseResponse -> = core.serialization.object({ - contextId: core.serialization.property("context_id", ContextId.optional()), - statusCode: core.serialization.property("status_code", core.serialization.number()), - done: core.serialization.boolean(), -}); - -export declare namespace WebSocketBaseResponse { - interface Raw { - context_id?: ContextId.Raw | null; - status_code: number; - done: boolean; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketChunkResponse.ts b/src/serialization/resources/tts/types/WebSocketChunkResponse.ts deleted file mode 100644 index 47b4a17..0000000 --- a/src/serialization/resources/tts/types/WebSocketChunkResponse.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; - -export const WebSocketChunkResponse: core.serialization.ObjectSchema< - serializers.WebSocketChunkResponse.Raw, - Cartesia.WebSocketChunkResponse -> = core.serialization - .object({ - data: core.serialization.string(), - stepTime: core.serialization.property("step_time", core.serialization.number()), - }) - .extend(WebSocketBaseResponse); - -export declare namespace WebSocketChunkResponse { - interface Raw extends WebSocketBaseResponse.Raw { - data: string; - step_time: number; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketDoneResponse.ts b/src/serialization/resources/tts/types/WebSocketDoneResponse.ts deleted file mode 100644 index 664b446..0000000 --- a/src/serialization/resources/tts/types/WebSocketDoneResponse.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; - -export const WebSocketDoneResponse: core.serialization.ObjectSchema< - serializers.WebSocketDoneResponse.Raw, - Cartesia.WebSocketDoneResponse -> = core.serialization.object({}).extend(WebSocketBaseResponse); - -export declare namespace WebSocketDoneResponse { - interface Raw extends WebSocketBaseResponse.Raw {} -} diff --git a/src/serialization/resources/tts/types/WebSocketErrorResponse.ts b/src/serialization/resources/tts/types/WebSocketErrorResponse.ts deleted file mode 100644 index 9db2694..0000000 --- a/src/serialization/resources/tts/types/WebSocketErrorResponse.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; - -export const WebSocketErrorResponse: core.serialization.ObjectSchema< - serializers.WebSocketErrorResponse.Raw, - Cartesia.WebSocketErrorResponse -> = core.serialization - .object({ - error: core.serialization.string(), - }) - .extend(WebSocketBaseResponse); - -export declare namespace WebSocketErrorResponse { - interface Raw extends WebSocketBaseResponse.Raw { - error: string; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketRawOutputFormat.ts b/src/serialization/resources/tts/types/WebSocketRawOutputFormat.ts deleted file mode 100644 index 44639aa..0000000 --- a/src/serialization/resources/tts/types/WebSocketRawOutputFormat.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { RawEncoding } from "./RawEncoding"; - -export const WebSocketRawOutputFormat: core.serialization.ObjectSchema< - serializers.WebSocketRawOutputFormat.Raw, - Cartesia.WebSocketRawOutputFormat -> = core.serialization.object({ - container: core.serialization.stringLiteral("raw"), - encoding: RawEncoding, - sampleRate: core.serialization.property("sample_rate", core.serialization.number()), -}); - -export declare namespace WebSocketRawOutputFormat { - interface Raw { - container: "raw"; - encoding: RawEncoding.Raw; - sample_rate: number; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketRequest.ts b/src/serialization/resources/tts/types/WebSocketRequest.ts deleted file mode 100644 index f55376c..0000000 --- a/src/serialization/resources/tts/types/WebSocketRequest.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { GenerationRequest } from "./GenerationRequest"; -import { CancelContextRequest } from "./CancelContextRequest"; - -export const WebSocketRequest: core.serialization.Schema = - core.serialization.undiscriminatedUnion([GenerationRequest, CancelContextRequest]); - -export declare namespace WebSocketRequest { - type Raw = GenerationRequest.Raw | CancelContextRequest.Raw; -} diff --git a/src/serialization/resources/tts/types/WebSocketResponse.ts b/src/serialization/resources/tts/types/WebSocketResponse.ts deleted file mode 100644 index 315992c..0000000 --- a/src/serialization/resources/tts/types/WebSocketResponse.ts +++ /dev/null @@ -1,50 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { WebSocketChunkResponse } from "./WebSocketChunkResponse"; -import { WebSocketDoneResponse } from "./WebSocketDoneResponse"; -import { WebSocketTimestampsResponse } from "./WebSocketTimestampsResponse"; -import { WebSocketErrorResponse } from "./WebSocketErrorResponse"; - -export const WebSocketResponse: core.serialization.Schema< - serializers.WebSocketResponse.Raw, - Cartesia.WebSocketResponse -> = core.serialization - .union("type", { - chunk: WebSocketChunkResponse, - done: WebSocketDoneResponse, - timestamps: WebSocketTimestampsResponse, - error: WebSocketErrorResponse, - }) - .transform({ - transform: (value) => value, - untransform: (value) => value, - }); - -export declare namespace WebSocketResponse { - type Raw = - | WebSocketResponse.Chunk - | WebSocketResponse.Done - | WebSocketResponse.Timestamps - | WebSocketResponse.Error; - - interface Chunk extends WebSocketChunkResponse.Raw { - type: "chunk"; - } - - interface Done extends WebSocketDoneResponse.Raw { - type: "done"; - } - - interface Timestamps extends WebSocketTimestampsResponse.Raw { - type: "timestamps"; - } - - interface Error extends WebSocketErrorResponse.Raw { - type: "error"; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketStreamOptions.ts b/src/serialization/resources/tts/types/WebSocketStreamOptions.ts deleted file mode 100644 index 9a1566c..0000000 --- a/src/serialization/resources/tts/types/WebSocketStreamOptions.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const WebSocketStreamOptions: core.serialization.ObjectSchema< - serializers.WebSocketStreamOptions.Raw, - Cartesia.WebSocketStreamOptions -> = core.serialization.object({ - timeout: core.serialization.number().optional(), -}); - -export declare namespace WebSocketStreamOptions { - interface Raw { - timeout?: number | null; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketTimestampsResponse.ts b/src/serialization/resources/tts/types/WebSocketTimestampsResponse.ts deleted file mode 100644 index 12408b0..0000000 --- a/src/serialization/resources/tts/types/WebSocketTimestampsResponse.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { WordTimestamps } from "./WordTimestamps"; -import { WebSocketBaseResponse } from "./WebSocketBaseResponse"; - -export const WebSocketTimestampsResponse: core.serialization.ObjectSchema< - serializers.WebSocketTimestampsResponse.Raw, - Cartesia.WebSocketTimestampsResponse -> = core.serialization - .object({ - wordTimestamps: core.serialization.property("word_timestamps", WordTimestamps.optional()), - }) - .extend(WebSocketBaseResponse); - -export declare namespace WebSocketTimestampsResponse { - interface Raw extends WebSocketBaseResponse.Raw { - word_timestamps?: WordTimestamps.Raw | null; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketTtsOutput.ts b/src/serialization/resources/tts/types/WebSocketTtsOutput.ts deleted file mode 100644 index c99916f..0000000 --- a/src/serialization/resources/tts/types/WebSocketTtsOutput.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { WordTimestamps } from "./WordTimestamps"; -import { ContextId } from "./ContextId"; - -export const WebSocketTtsOutput: core.serialization.ObjectSchema< - serializers.WebSocketTtsOutput.Raw, - Cartesia.WebSocketTtsOutput -> = core.serialization.object({ - wordTimestamps: core.serialization.property("word_timestamps", WordTimestamps.optional()), - audio: core.serialization.unknown().optional(), - contextId: core.serialization.property("context_id", ContextId.optional()), -}); - -export declare namespace WebSocketTtsOutput { - interface Raw { - word_timestamps?: WordTimestamps.Raw | null; - audio?: unknown | null; - context_id?: ContextId.Raw | null; - } -} diff --git a/src/serialization/resources/tts/types/WebSocketTtsRequest.ts b/src/serialization/resources/tts/types/WebSocketTtsRequest.ts deleted file mode 100644 index ce2e328..0000000 --- a/src/serialization/resources/tts/types/WebSocketTtsRequest.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { OutputFormat } from "./OutputFormat"; -import { TtsRequestVoiceSpecifier } from "./TtsRequestVoiceSpecifier"; - -export const WebSocketTtsRequest: core.serialization.ObjectSchema< - serializers.WebSocketTtsRequest.Raw, - Cartesia.WebSocketTtsRequest -> = core.serialization.object({ - modelId: core.serialization.property("model_id", core.serialization.string()), - outputFormat: core.serialization.property("output_format", OutputFormat.optional()), - transcript: core.serialization.string().optional(), - voice: TtsRequestVoiceSpecifier, - duration: core.serialization.number().optional(), - language: core.serialization.string().optional(), - addTimestamps: core.serialization.property("add_timestamps", core.serialization.boolean().optional()), - contextId: core.serialization.property("context_id", core.serialization.string().optional()), -}); - -export declare namespace WebSocketTtsRequest { - interface Raw { - model_id: string; - output_format?: OutputFormat.Raw | null; - transcript?: string | null; - voice: TtsRequestVoiceSpecifier.Raw; - duration?: number | null; - language?: string | null; - add_timestamps?: boolean | null; - context_id?: string | null; - } -} diff --git a/src/serialization/resources/tts/types/WordTimestamps.ts b/src/serialization/resources/tts/types/WordTimestamps.ts deleted file mode 100644 index 8f50ffe..0000000 --- a/src/serialization/resources/tts/types/WordTimestamps.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const WordTimestamps: core.serialization.ObjectSchema = - core.serialization.object({ - words: core.serialization.list(core.serialization.string()), - start: core.serialization.list(core.serialization.number()), - end: core.serialization.list(core.serialization.number()), - }); - -export declare namespace WordTimestamps { - interface Raw { - words: string[]; - start: number[]; - end: number[]; - } -} diff --git a/src/serialization/resources/tts/types/index.ts b/src/serialization/resources/tts/types/index.ts deleted file mode 100644 index 5212040..0000000 --- a/src/serialization/resources/tts/types/index.ts +++ /dev/null @@ -1,30 +0,0 @@ -export * from "./ContextId"; -export * from "./WebSocketBaseResponse"; -export * from "./WebSocketResponse"; -export * from "./WebSocketErrorResponse"; -export * from "./WebSocketChunkResponse"; -export * from "./WebSocketTimestampsResponse"; -export * from "./WebSocketTtsOutput"; -export * from "./WebSocketStreamOptions"; -export * from "./WordTimestamps"; -export * from "./WebSocketDoneResponse"; -export * from "./CancelContextRequest"; -export * from "./GenerationRequest"; -export * from "./WebSocketRawOutputFormat"; -export * from "./WebSocketRequest"; -export * from "./WebSocketTtsRequest"; -export * from "./TtsRequest"; -export * from "./SupportedLanguage"; -export * from "./OutputFormat"; -export * from "./RawOutputFormat"; -export * from "./RawEncoding"; -export * from "./WavOutputFormat"; -export * from "./Mp3OutputFormat"; -export * from "./TtsRequestVoiceSpecifier"; -export * from "./TtsRequestIdSpecifier"; -export * from "./TtsRequestEmbeddingSpecifier"; -export * from "./Controls"; -export * from "./Speed"; -export * from "./NumericalSpecifier"; -export * from "./NaturalSpecifier"; -export * from "./Emotion"; diff --git a/src/serialization/resources/voiceChanger/index.ts b/src/serialization/resources/voiceChanger/index.ts deleted file mode 100644 index eea524d..0000000 --- a/src/serialization/resources/voiceChanger/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./types"; diff --git a/src/serialization/resources/voiceChanger/types/OutputFormatContainer.ts b/src/serialization/resources/voiceChanger/types/OutputFormatContainer.ts deleted file mode 100644 index ad08730..0000000 --- a/src/serialization/resources/voiceChanger/types/OutputFormatContainer.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const OutputFormatContainer: core.serialization.Schema< - serializers.OutputFormatContainer.Raw, - Cartesia.OutputFormatContainer -> = core.serialization.enum_(["raw", "wav", "mp3"]); - -export declare namespace OutputFormatContainer { - type Raw = "raw" | "wav" | "mp3"; -} diff --git a/src/serialization/resources/voiceChanger/types/StreamingResponse.ts b/src/serialization/resources/voiceChanger/types/StreamingResponse.ts deleted file mode 100644 index 0629aad..0000000 --- a/src/serialization/resources/voiceChanger/types/StreamingResponse.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { WebSocketChunkResponse } from "../../tts/types/WebSocketChunkResponse"; -import { WebSocketDoneResponse } from "../../tts/types/WebSocketDoneResponse"; -import { WebSocketErrorResponse } from "../../tts/types/WebSocketErrorResponse"; - -export const StreamingResponse: core.serialization.Schema< - serializers.StreamingResponse.Raw, - Cartesia.StreamingResponse -> = core.serialization - .union("type", { - chunk: WebSocketChunkResponse, - done: WebSocketDoneResponse, - error: WebSocketErrorResponse, - }) - .transform({ - transform: (value) => value, - untransform: (value) => value, - }); - -export declare namespace StreamingResponse { - type Raw = StreamingResponse.Chunk | StreamingResponse.Done | StreamingResponse.Error; - - interface Chunk extends WebSocketChunkResponse.Raw { - type: "chunk"; - } - - interface Done extends WebSocketDoneResponse.Raw { - type: "done"; - } - - interface Error extends WebSocketErrorResponse.Raw { - type: "error"; - } -} diff --git a/src/serialization/resources/voiceChanger/types/index.ts b/src/serialization/resources/voiceChanger/types/index.ts deleted file mode 100644 index bc81bbd..0000000 --- a/src/serialization/resources/voiceChanger/types/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./OutputFormatContainer"; -export * from "./StreamingResponse"; diff --git a/src/serialization/resources/voices/client/index.ts b/src/serialization/resources/voices/client/index.ts deleted file mode 100644 index abbe30a..0000000 --- a/src/serialization/resources/voices/client/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * as list from "./list"; diff --git a/src/serialization/resources/voices/client/list.ts b/src/serialization/resources/voices/client/list.ts deleted file mode 100644 index 4cd4a34..0000000 --- a/src/serialization/resources/voices/client/list.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { Voice } from "../types/Voice"; - -export const Response: core.serialization.Schema = - core.serialization.list(Voice); - -export declare namespace Response { - type Raw = Voice.Raw[]; -} diff --git a/src/serialization/resources/voices/index.ts b/src/serialization/resources/voices/index.ts deleted file mode 100644 index c9240f8..0000000 --- a/src/serialization/resources/voices/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./types"; -export * from "./client"; diff --git a/src/serialization/resources/voices/types/BaseVoiceId.ts b/src/serialization/resources/voices/types/BaseVoiceId.ts deleted file mode 100644 index d4c5dd7..0000000 --- a/src/serialization/resources/voices/types/BaseVoiceId.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { VoiceId } from "./VoiceId"; - -export const BaseVoiceId: core.serialization.Schema = VoiceId; - -export declare namespace BaseVoiceId { - type Raw = VoiceId.Raw; -} diff --git a/src/serialization/resources/voices/types/CreateVoiceRequest.ts b/src/serialization/resources/voices/types/CreateVoiceRequest.ts deleted file mode 100644 index 3808006..0000000 --- a/src/serialization/resources/voices/types/CreateVoiceRequest.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { Embedding } from "../../embedding/types/Embedding"; -import { SupportedLanguage } from "../../tts/types/SupportedLanguage"; -import { BaseVoiceId } from "./BaseVoiceId"; - -export const CreateVoiceRequest: core.serialization.ObjectSchema< - serializers.CreateVoiceRequest.Raw, - Cartesia.CreateVoiceRequest -> = core.serialization.object({ - name: core.serialization.string(), - description: core.serialization.string(), - embedding: Embedding, - language: SupportedLanguage.optional(), - baseVoiceId: core.serialization.property("base_voice_id", BaseVoiceId.optional()), -}); - -export declare namespace CreateVoiceRequest { - interface Raw { - name: string; - description: string; - embedding: Embedding.Raw; - language?: SupportedLanguage.Raw | null; - base_voice_id?: BaseVoiceId.Raw | null; - } -} diff --git a/src/serialization/resources/voices/types/EmbeddingResponse.ts b/src/serialization/resources/voices/types/EmbeddingResponse.ts deleted file mode 100644 index e4470df..0000000 --- a/src/serialization/resources/voices/types/EmbeddingResponse.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { Embedding } from "../../embedding/types/Embedding"; - -export const EmbeddingResponse: core.serialization.ObjectSchema< - serializers.EmbeddingResponse.Raw, - Cartesia.EmbeddingResponse -> = core.serialization.object({ - embedding: Embedding, -}); - -export declare namespace EmbeddingResponse { - interface Raw { - embedding: Embedding.Raw; - } -} diff --git a/src/serialization/resources/voices/types/EmbeddingSpecifier.ts b/src/serialization/resources/voices/types/EmbeddingSpecifier.ts deleted file mode 100644 index 443c4f0..0000000 --- a/src/serialization/resources/voices/types/EmbeddingSpecifier.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { Embedding } from "../../embedding/types/Embedding"; -import { Weight } from "./Weight"; - -export const EmbeddingSpecifier: core.serialization.ObjectSchema< - serializers.EmbeddingSpecifier.Raw, - Cartesia.EmbeddingSpecifier -> = core.serialization.object({ - embedding: Embedding, - weight: Weight, -}); - -export declare namespace EmbeddingSpecifier { - interface Raw { - embedding: Embedding.Raw; - weight: Weight.Raw; - } -} diff --git a/src/serialization/resources/voices/types/Gender.ts b/src/serialization/resources/voices/types/Gender.ts deleted file mode 100644 index 68d24f1..0000000 --- a/src/serialization/resources/voices/types/Gender.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const Gender: core.serialization.Schema = core.serialization.enum_([ - "male", - "female", -]); - -export declare namespace Gender { - type Raw = "male" | "female"; -} diff --git a/src/serialization/resources/voices/types/IdSpecifier.ts b/src/serialization/resources/voices/types/IdSpecifier.ts deleted file mode 100644 index bd487ed..0000000 --- a/src/serialization/resources/voices/types/IdSpecifier.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { VoiceId } from "./VoiceId"; -import { Weight } from "./Weight"; - -export const IdSpecifier: core.serialization.ObjectSchema = - core.serialization.object({ - id: VoiceId, - weight: Weight, - }); - -export declare namespace IdSpecifier { - interface Raw { - id: VoiceId.Raw; - weight: Weight.Raw; - } -} diff --git a/src/serialization/resources/voices/types/LocalizeDialect.ts b/src/serialization/resources/voices/types/LocalizeDialect.ts deleted file mode 100644 index 8391ee4..0000000 --- a/src/serialization/resources/voices/types/LocalizeDialect.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const LocalizeDialect: core.serialization.Schema = - core.serialization.enum_(["au", "in", "so", "uk", "us"]); - -export declare namespace LocalizeDialect { - type Raw = "au" | "in" | "so" | "uk" | "us"; -} diff --git a/src/serialization/resources/voices/types/LocalizeTargetLanguage.ts b/src/serialization/resources/voices/types/LocalizeTargetLanguage.ts deleted file mode 100644 index 4c3c868..0000000 --- a/src/serialization/resources/voices/types/LocalizeTargetLanguage.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const LocalizeTargetLanguage: core.serialization.Schema< - serializers.LocalizeTargetLanguage.Raw, - Cartesia.LocalizeTargetLanguage -> = core.serialization.enum_([ - "en", - "de", - "es", - "fr", - "ja", - "pt", - "zh", - "hi", - "it", - "ko", - "nl", - "pl", - "ru", - "sv", - "tr", -]); - -export declare namespace LocalizeTargetLanguage { - type Raw = "en" | "de" | "es" | "fr" | "ja" | "pt" | "zh" | "hi" | "it" | "ko" | "nl" | "pl" | "ru" | "sv" | "tr"; -} diff --git a/src/serialization/resources/voices/types/LocalizeVoiceRequest.ts b/src/serialization/resources/voices/types/LocalizeVoiceRequest.ts deleted file mode 100644 index 1f08fb9..0000000 --- a/src/serialization/resources/voices/types/LocalizeVoiceRequest.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { Embedding } from "../../embedding/types/Embedding"; -import { LocalizeTargetLanguage } from "./LocalizeTargetLanguage"; -import { Gender } from "./Gender"; -import { LocalizeDialect } from "./LocalizeDialect"; - -export const LocalizeVoiceRequest: core.serialization.ObjectSchema< - serializers.LocalizeVoiceRequest.Raw, - Cartesia.LocalizeVoiceRequest -> = core.serialization.object({ - embedding: Embedding, - language: LocalizeTargetLanguage, - originalSpeakerGender: core.serialization.property("original_speaker_gender", Gender), - dialect: LocalizeDialect.optional(), -}); - -export declare namespace LocalizeVoiceRequest { - interface Raw { - embedding: Embedding.Raw; - language: LocalizeTargetLanguage.Raw; - original_speaker_gender: Gender.Raw; - dialect?: LocalizeDialect.Raw | null; - } -} diff --git a/src/serialization/resources/voices/types/MixVoiceSpecifier.ts b/src/serialization/resources/voices/types/MixVoiceSpecifier.ts deleted file mode 100644 index 594de8a..0000000 --- a/src/serialization/resources/voices/types/MixVoiceSpecifier.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { IdSpecifier } from "./IdSpecifier"; -import { EmbeddingSpecifier } from "./EmbeddingSpecifier"; - -export const MixVoiceSpecifier: core.serialization.Schema< - serializers.MixVoiceSpecifier.Raw, - Cartesia.MixVoiceSpecifier -> = core.serialization.undiscriminatedUnion([IdSpecifier, EmbeddingSpecifier]); - -export declare namespace MixVoiceSpecifier { - type Raw = IdSpecifier.Raw | EmbeddingSpecifier.Raw; -} diff --git a/src/serialization/resources/voices/types/MixVoicesRequest.ts b/src/serialization/resources/voices/types/MixVoicesRequest.ts deleted file mode 100644 index e1c9780..0000000 --- a/src/serialization/resources/voices/types/MixVoicesRequest.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { MixVoiceSpecifier } from "./MixVoiceSpecifier"; - -export const MixVoicesRequest: core.serialization.ObjectSchema< - serializers.MixVoicesRequest.Raw, - Cartesia.MixVoicesRequest -> = core.serialization.object({ - voices: core.serialization.list(MixVoiceSpecifier), -}); - -export declare namespace MixVoicesRequest { - interface Raw { - voices: MixVoiceSpecifier.Raw[]; - } -} diff --git a/src/serialization/resources/voices/types/UpdateVoiceRequest.ts b/src/serialization/resources/voices/types/UpdateVoiceRequest.ts deleted file mode 100644 index 4da8115..0000000 --- a/src/serialization/resources/voices/types/UpdateVoiceRequest.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const UpdateVoiceRequest: core.serialization.ObjectSchema< - serializers.UpdateVoiceRequest.Raw, - Cartesia.UpdateVoiceRequest -> = core.serialization.object({ - name: core.serialization.string(), - description: core.serialization.string(), -}); - -export declare namespace UpdateVoiceRequest { - interface Raw { - name: string; - description: string; - } -} diff --git a/src/serialization/resources/voices/types/Voice.ts b/src/serialization/resources/voices/types/Voice.ts deleted file mode 100644 index 185c729..0000000 --- a/src/serialization/resources/voices/types/Voice.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; -import { VoiceId } from "./VoiceId"; -import { Embedding } from "../../embedding/types/Embedding"; -import { SupportedLanguage } from "../../tts/types/SupportedLanguage"; -import { BaseVoiceId } from "./BaseVoiceId"; - -export const Voice: core.serialization.ObjectSchema = core.serialization.object({ - id: VoiceId, - userId: core.serialization.property("user_id", core.serialization.string().optional()), - isPublic: core.serialization.property("is_public", core.serialization.boolean()), - name: core.serialization.string(), - description: core.serialization.string(), - createdAt: core.serialization.property("created_at", core.serialization.date()), - embedding: Embedding, - language: SupportedLanguage, - baseVoiceId: core.serialization.property("base_voice_id", BaseVoiceId.optional()), -}); - -export declare namespace Voice { - interface Raw { - id: VoiceId.Raw; - user_id?: string | null; - is_public: boolean; - name: string; - description: string; - created_at: string; - embedding: Embedding.Raw; - language: SupportedLanguage.Raw; - base_voice_id?: BaseVoiceId.Raw | null; - } -} diff --git a/src/serialization/resources/voices/types/VoiceId.ts b/src/serialization/resources/voices/types/VoiceId.ts deleted file mode 100644 index 836e6bd..0000000 --- a/src/serialization/resources/voices/types/VoiceId.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const VoiceId: core.serialization.Schema = - core.serialization.string(); - -export declare namespace VoiceId { - type Raw = string; -} diff --git a/src/serialization/resources/voices/types/Weight.ts b/src/serialization/resources/voices/types/Weight.ts deleted file mode 100644 index 1a46618..0000000 --- a/src/serialization/resources/voices/types/Weight.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ - -import * as serializers from "../../../index"; -import * as Cartesia from "../../../../api/index"; -import * as core from "../../../../core"; - -export const Weight: core.serialization.Schema = core.serialization.number(); - -export declare namespace Weight { - type Raw = number; -} diff --git a/src/serialization/resources/voices/types/index.ts b/src/serialization/resources/voices/types/index.ts deleted file mode 100644 index 35b54d7..0000000 --- a/src/serialization/resources/voices/types/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -export * from "./VoiceId"; -export * from "./BaseVoiceId"; -export * from "./Voice"; -export * from "./CreateVoiceRequest"; -export * from "./UpdateVoiceRequest"; -export * from "./LocalizeTargetLanguage"; -export * from "./LocalizeDialect"; -export * from "./Gender"; -export * from "./LocalizeVoiceRequest"; -export * from "./EmbeddingResponse"; -export * from "./MixVoicesRequest"; -export * from "./Weight"; -export * from "./IdSpecifier"; -export * from "./EmbeddingSpecifier"; -export * from "./MixVoiceSpecifier"; diff --git a/src/version.ts b/src/version.ts index ee1c68e..0bf6d5b 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const SDK_VERSION = "1.3.1"; +export const SDK_VERSION = "2.0.0-alpha0"; diff --git a/tests/unit/zurg/bigint/bigint.test.ts b/tests/unit/zurg/bigint/bigint.test.ts deleted file mode 100644 index cf9935a..0000000 --- a/tests/unit/zurg/bigint/bigint.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { bigint } from "../../../../src/core/schemas/builders/bigint"; -import { itSchema } from "../utils/itSchema"; -import { itValidateJson, itValidateParse } from "../utils/itValidate"; - -describe("bigint", () => { - itSchema("converts between raw string and parsed bigint", bigint(), { - raw: "123456789012345678901234567890123456789012345678901234567890", - parsed: BigInt("123456789012345678901234567890123456789012345678901234567890"), - }); - - itValidateParse("non-string", bigint(), 42, [ - { - message: "Expected string. Received 42.", - path: [], - }, - ]); - - itValidateJson("non-bigint", bigint(), "hello", [ - { - message: 'Expected bigint. Received "hello".', - path: [], - }, - ]); -}); diff --git a/tests/unit/zurg/date/date.test.ts b/tests/unit/zurg/date/date.test.ts deleted file mode 100644 index 2790268..0000000 --- a/tests/unit/zurg/date/date.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { date } from "../../../../src/core/schemas/builders/date"; -import { itSchema } from "../utils/itSchema"; -import { itValidateJson, itValidateParse } from "../utils/itValidate"; - -describe("date", () => { - itSchema("converts between raw ISO string and parsed Date", date(), { - raw: "2022-09-29T05:41:21.939Z", - parsed: new Date("2022-09-29T05:41:21.939Z"), - }); - - itValidateParse("non-string", date(), 42, [ - { - message: "Expected string. Received 42.", - path: [], - }, - ]); - - itValidateParse("non-ISO", date(), "hello world", [ - { - message: 'Expected ISO 8601 date string. Received "hello world".', - path: [], - }, - ]); - - itValidateJson("non-Date", date(), "hello", [ - { - message: 'Expected Date object. Received "hello".', - path: [], - }, - ]); -}); diff --git a/tests/unit/zurg/enum/enum.test.ts b/tests/unit/zurg/enum/enum.test.ts deleted file mode 100644 index ab0df02..0000000 --- a/tests/unit/zurg/enum/enum.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { enum_ } from "../../../../src/core/schemas/builders/enum"; -import { itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("enum", () => { - itSchemaIdentity(enum_(["A", "B", "C"]), "A"); - - itSchemaIdentity(enum_(["A", "B", "C"]), "D" as any, { - opts: { allowUnrecognizedEnumValues: true }, - }); - - itValidate("invalid enum", enum_(["A", "B", "C"]), "D", [ - { - message: 'Expected enum. Received "D".', - path: [], - }, - ]); - - itValidate( - "non-string", - enum_(["A", "B", "C"]), - [], - [ - { - message: "Expected string. Received list.", - path: [], - }, - ] - ); -}); diff --git a/tests/unit/zurg/lazy/lazy.test.ts b/tests/unit/zurg/lazy/lazy.test.ts deleted file mode 100644 index 6906bf4..0000000 --- a/tests/unit/zurg/lazy/lazy.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { Schema } from "../../../../src/core/schemas/Schema"; -import { lazy, list, object, string } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; - -describe("lazy", () => { - it("doesn't run immediately", () => { - let wasRun = false; - lazy(() => { - wasRun = true; - return string(); - }); - expect(wasRun).toBe(false); - }); - - it("only runs first time", async () => { - let count = 0; - const schema = lazy(() => { - count++; - return string(); - }); - await schema.parse("hello"); - await schema.json("world"); - expect(count).toBe(1); - }); - - itSchemaIdentity( - lazy(() => object({})), - { foo: "hello" }, - { - title: "passes opts through", - opts: { unrecognizedObjectKeys: "passthrough" }, - } - ); - - itSchemaIdentity( - lazy(() => object({ foo: string() })), - { foo: "hello" } - ); - - // eslint-disable-next-line jest/expect-expect - it("self-referencial schema doesn't compile", () => { - () => { - // @ts-expect-error - const a = lazy(() => object({ foo: a })); - }; - }); - - // eslint-disable-next-line jest/expect-expect - it("self-referencial compiles with explicit type", () => { - () => { - interface TreeNode { - children: TreeNode[]; - } - const TreeNode: Schema = lazy(() => object({ children: list(TreeNode) })); - }; - }); -}); diff --git a/tests/unit/zurg/lazy/lazyObject.test.ts b/tests/unit/zurg/lazy/lazyObject.test.ts deleted file mode 100644 index 8813cc9..0000000 --- a/tests/unit/zurg/lazy/lazyObject.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { lazyObject, number, object, string } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; - -describe("lazy", () => { - itSchemaIdentity( - lazyObject(() => object({ foo: string() })), - { foo: "hello" } - ); - - itSchemaIdentity( - lazyObject(() => object({ foo: string() })).extend(object({ bar: number() })), - { - foo: "hello", - bar: 42, - }, - { title: "returned schema has object utils" } - ); -}); diff --git a/tests/unit/zurg/lazy/recursive/a.ts b/tests/unit/zurg/lazy/recursive/a.ts deleted file mode 100644 index 8b7d5e4..0000000 --- a/tests/unit/zurg/lazy/recursive/a.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { object } from "../../../../../src/core/schemas/builders/object"; -import { schemaB } from "./b"; - -// @ts-expect-error -export const schemaA = object({ - b: schemaB, -}); diff --git a/tests/unit/zurg/lazy/recursive/b.ts b/tests/unit/zurg/lazy/recursive/b.ts deleted file mode 100644 index fb219d5..0000000 --- a/tests/unit/zurg/lazy/recursive/b.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { object } from "../../../../../src/core/schemas/builders/object"; -import { optional } from "../../../../../src/core/schemas/builders/schema-utils"; -import { schemaA } from "./a"; - -// @ts-expect-error -export const schemaB = object({ - a: optional(schemaA), -}); diff --git a/tests/unit/zurg/list/list.test.ts b/tests/unit/zurg/list/list.test.ts deleted file mode 100644 index 424ed64..0000000 --- a/tests/unit/zurg/list/list.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { list, object, property, string } from "../../../../src/core/schemas/builders"; -import { itSchema, itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("list", () => { - itSchemaIdentity(list(string()), ["hello", "world"], { - title: "functions as identity when item type is primitive", - }); - - itSchema( - "converts objects correctly", - list( - object({ - helloWorld: property("hello_world", string()), - }) - ), - { - raw: [{ hello_world: "123" }], - parsed: [{ helloWorld: "123" }], - } - ); - - itValidate("not a list", list(string()), 42, [ - { - path: [], - message: "Expected list. Received 42.", - }, - ]); - - itValidate( - "invalid item type", - list(string()), - [42], - [ - { - path: ["[0]"], - message: "Expected string. Received 42.", - }, - ] - ); -}); diff --git a/tests/unit/zurg/literals/stringLiteral.test.ts b/tests/unit/zurg/literals/stringLiteral.test.ts deleted file mode 100644 index fa6c888..0000000 --- a/tests/unit/zurg/literals/stringLiteral.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { stringLiteral } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("stringLiteral", () => { - itSchemaIdentity(stringLiteral("A"), "A"); - - itValidate("incorrect string", stringLiteral("A"), "B", [ - { - path: [], - message: 'Expected "A". Received "B".', - }, - ]); - - itValidate("non-string", stringLiteral("A"), 42, [ - { - path: [], - message: 'Expected "A". Received 42.', - }, - ]); -}); diff --git a/tests/unit/zurg/object-like/withParsedProperties.test.ts b/tests/unit/zurg/object-like/withParsedProperties.test.ts deleted file mode 100644 index 9f5dd0e..0000000 --- a/tests/unit/zurg/object-like/withParsedProperties.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { object, property, string, stringLiteral } from "../../../../src/core/schemas/builders"; - -describe("withParsedProperties", () => { - it("Added properties included on parsed object", async () => { - const schema = object({ - foo: property("raw_foo", string()), - bar: stringLiteral("bar"), - }).withParsedProperties({ - printFoo: (parsed) => () => parsed.foo, - printHelloWorld: () => () => "Hello world", - helloWorld: "Hello world", - }); - - const parsed = await schema.parse({ raw_foo: "value of foo", bar: "bar" }); - if (!parsed.ok) { - throw new Error("Failed to parse"); - } - expect(parsed.value.printFoo()).toBe("value of foo"); - expect(parsed.value.printHelloWorld()).toBe("Hello world"); - expect(parsed.value.helloWorld).toBe("Hello world"); - }); - - it("Added property is removed on raw object", async () => { - const schema = object({ - foo: property("raw_foo", string()), - bar: stringLiteral("bar"), - }).withParsedProperties({ - printFoo: (parsed) => () => parsed.foo, - }); - - const original = { raw_foo: "value of foo", bar: "bar" } as const; - const parsed = await schema.parse(original); - if (!parsed.ok) { - throw new Error("Failed to parse()"); - } - - const raw = await schema.json(parsed.value); - - if (!raw.ok) { - throw new Error("Failed to json()"); - } - - expect(raw.value).toEqual(original); - }); - - describe("compile", () => { - // eslint-disable-next-line jest/expect-expect - it("doesn't compile with non-object schema", () => { - () => - object({ - foo: string(), - }) - // @ts-expect-error - .withParsedProperties(42); - }); - }); -}); diff --git a/tests/unit/zurg/object/extend.test.ts b/tests/unit/zurg/object/extend.test.ts deleted file mode 100644 index 54fc8c4..0000000 --- a/tests/unit/zurg/object/extend.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { boolean, object, property, string, stringLiteral } from "../../../../src/core/schemas/builders"; -import { itSchema, itSchemaIdentity } from "../utils/itSchema"; - -describe("extend", () => { - itSchemaIdentity( - object({ - foo: string(), - }).extend( - object({ - bar: stringLiteral("bar"), - }) - ), - { - foo: "", - bar: "bar", - } as const, - { - title: "extended properties are included in schema", - } - ); - - itSchemaIdentity( - object({ - foo: string(), - }) - .extend( - object({ - bar: stringLiteral("bar"), - }) - ) - .extend( - object({ - baz: boolean(), - }) - ), - { - foo: "", - bar: "bar", - baz: true, - } as const, - { - title: "extensions can be extended", - } - ); - - itSchema( - "converts nested object", - object({ - item: object({ - helloWorld: property("hello_world", string()), - }), - }).extend( - object({ - goodbye: property("goodbye_raw", string()), - }) - ), - { - raw: { item: { hello_world: "yo" }, goodbye_raw: "peace" }, - parsed: { item: { helloWorld: "yo" }, goodbye: "peace" }, - } - ); - - itSchema( - "extensions work with raw/parsed property name conversions", - object({ - item: property("item_raw", string()), - }).extend( - object({ - goodbye: property("goodbye_raw", string()), - }) - ), - { - raw: { item_raw: "hi", goodbye_raw: "peace" }, - parsed: { item: "hi", goodbye: "peace" }, - } - ); - - describe("compile", () => { - // eslint-disable-next-line jest/expect-expect - it("doesn't compile with non-object schema", () => { - () => - object({ - foo: string(), - }) - // @ts-expect-error - .extend([]); - }); - }); -}); diff --git a/tests/unit/zurg/object/object.test.ts b/tests/unit/zurg/object/object.test.ts deleted file mode 100644 index 0acf0e2..0000000 --- a/tests/unit/zurg/object/object.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import { any, number, object, property, string, stringLiteral, unknown } from "../../../../src/core/schemas/builders"; -import { itJson, itParse, itSchema, itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("object", () => { - itSchemaIdentity( - object({ - foo: string(), - bar: stringLiteral("bar"), - }), - { - foo: "", - bar: "bar", - }, - { - title: "functions as identity when values are primitives and property() isn't used", - } - ); - - itSchema( - "uses raw key from property()", - object({ - foo: property("raw_foo", string()), - bar: stringLiteral("bar"), - }), - { - raw: { raw_foo: "foo", bar: "bar" }, - parsed: { foo: "foo", bar: "bar" }, - } - ); - - itSchema( - "keys with unknown type can be omitted", - object({ - foo: unknown(), - }), - { - raw: {}, - parsed: {}, - } - ); - - itSchema( - "keys with any type can be omitted", - object({ - foo: any(), - }), - { - raw: {}, - parsed: {}, - } - ); - - describe("unrecognizedObjectKeys", () => { - describe("parse", () => { - itParse( - 'includes unknown values when unrecognizedObjectKeys === "passthrough"', - object({ - foo: property("raw_foo", string()), - bar: stringLiteral("bar"), - }), - { - raw: { - raw_foo: "foo", - bar: "bar", - // @ts-expect-error - baz: "yoyo", - }, - parsed: { - foo: "foo", - bar: "bar", - // @ts-expect-error - baz: "yoyo", - }, - opts: { - unrecognizedObjectKeys: "passthrough", - }, - } - ); - - itParse( - 'strips unknown values when unrecognizedObjectKeys === "strip"', - object({ - foo: property("raw_foo", string()), - bar: stringLiteral("bar"), - }), - { - raw: { - raw_foo: "foo", - bar: "bar", - // @ts-expect-error - baz: "yoyo", - }, - parsed: { - foo: "foo", - bar: "bar", - }, - opts: { - unrecognizedObjectKeys: "strip", - }, - } - ); - }); - - describe("json", () => { - itJson( - 'includes unknown values when unrecognizedObjectKeys === "passthrough"', - object({ - foo: property("raw_foo", string()), - bar: stringLiteral("bar"), - }), - { - raw: { - raw_foo: "foo", - bar: "bar", - // @ts-expect-error - baz: "yoyo", - }, - parsed: { - foo: "foo", - bar: "bar", - // @ts-expect-error - baz: "yoyo", - }, - opts: { - unrecognizedObjectKeys: "passthrough", - }, - } - ); - - itJson( - 'strips unknown values when unrecognizedObjectKeys === "strip"', - object({ - foo: property("raw_foo", string()), - bar: stringLiteral("bar"), - }), - { - raw: { - raw_foo: "foo", - bar: "bar", - }, - parsed: { - foo: "foo", - bar: "bar", - // @ts-expect-error - baz: "yoyo", - }, - opts: { - unrecognizedObjectKeys: "strip", - }, - } - ); - }); - }); - - describe("nullish properties", () => { - itSchema("missing properties are not added", object({ foo: property("raw_foo", string().optional()) }), { - raw: {}, - parsed: {}, - }); - - itSchema("undefined properties are not dropped", object({ foo: property("raw_foo", string().optional()) }), { - raw: { raw_foo: null }, - parsed: { foo: undefined }, - }); - - itSchema("null properties are not dropped", object({ foo: property("raw_foo", string().optional()) }), { - raw: { raw_foo: null }, - parsed: { foo: undefined }, - }); - - describe("extensions", () => { - itSchema( - "undefined properties are not dropped", - object({}).extend(object({ foo: property("raw_foo", string().optional()) })), - { - raw: { raw_foo: null }, - parsed: { foo: undefined }, - } - ); - - describe("parse()", () => { - itParse( - "null properties are not dropped", - object({}).extend(object({ foo: property("raw_foo", string().optional()) })), - { - raw: { raw_foo: null }, - parsed: { foo: undefined }, - } - ); - }); - }); - }); - - itValidate( - "missing property", - object({ - foo: string(), - bar: stringLiteral("bar"), - }), - { foo: "hello" }, - [ - { - path: [], - message: 'Missing required key "bar"', - }, - ] - ); - - itValidate( - "extra property", - object({ - foo: string(), - bar: stringLiteral("bar"), - }), - { foo: "hello", bar: "bar", baz: 42 }, - [ - { - path: ["baz"], - message: 'Unexpected key "baz"', - }, - ] - ); - - itValidate( - "not an object", - object({ - foo: string(), - bar: stringLiteral("bar"), - }), - [], - [ - { - path: [], - message: "Expected object. Received list.", - }, - ] - ); - - itValidate( - "nested validation error", - object({ - foo: object({ - bar: number(), - }), - }), - { foo: { bar: "hello" } }, - [ - { - path: ["foo", "bar"], - message: 'Expected number. Received "hello".', - }, - ] - ); -}); diff --git a/tests/unit/zurg/object/objectWithoutOptionalProperties.test.ts b/tests/unit/zurg/object/objectWithoutOptionalProperties.test.ts deleted file mode 100644 index d87a65f..0000000 --- a/tests/unit/zurg/object/objectWithoutOptionalProperties.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { objectWithoutOptionalProperties, string, stringLiteral } from "../../../../src/core/schemas/builders"; -import { itSchema } from "../utils/itSchema"; - -describe("objectWithoutOptionalProperties", () => { - itSchema( - "all properties are required", - objectWithoutOptionalProperties({ - foo: string(), - bar: stringLiteral("bar").optional(), - }), - { - raw: { - foo: "hello", - }, - // @ts-expect-error - parsed: { - foo: "hello", - }, - } - ); -}); diff --git a/tests/unit/zurg/primitives/any.test.ts b/tests/unit/zurg/primitives/any.test.ts deleted file mode 100644 index 1adbbe2..0000000 --- a/tests/unit/zurg/primitives/any.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { any } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; - -describe("any", () => { - itSchemaIdentity(any(), true); -}); diff --git a/tests/unit/zurg/primitives/boolean.test.ts b/tests/unit/zurg/primitives/boolean.test.ts deleted file mode 100644 index 897a829..0000000 --- a/tests/unit/zurg/primitives/boolean.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { boolean } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("boolean", () => { - itSchemaIdentity(boolean(), true); - - itValidate("non-boolean", boolean(), {}, [ - { - path: [], - message: "Expected boolean. Received object.", - }, - ]); -}); diff --git a/tests/unit/zurg/primitives/number.test.ts b/tests/unit/zurg/primitives/number.test.ts deleted file mode 100644 index 2d01415..0000000 --- a/tests/unit/zurg/primitives/number.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { number } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("number", () => { - itSchemaIdentity(number(), 42); - - itValidate("non-number", number(), "hello", [ - { - path: [], - message: 'Expected number. Received "hello".', - }, - ]); -}); diff --git a/tests/unit/zurg/primitives/string.test.ts b/tests/unit/zurg/primitives/string.test.ts deleted file mode 100644 index 57b2368..0000000 --- a/tests/unit/zurg/primitives/string.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { string } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("string", () => { - itSchemaIdentity(string(), "hello"); - - itValidate("non-string", string(), 42, [ - { - path: [], - message: "Expected string. Received 42.", - }, - ]); -}); diff --git a/tests/unit/zurg/primitives/unknown.test.ts b/tests/unit/zurg/primitives/unknown.test.ts deleted file mode 100644 index 4d17a7d..0000000 --- a/tests/unit/zurg/primitives/unknown.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { unknown } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; - -describe("unknown", () => { - itSchemaIdentity(unknown(), true); -}); diff --git a/tests/unit/zurg/record/record.test.ts b/tests/unit/zurg/record/record.test.ts deleted file mode 100644 index 7e4ba39..0000000 --- a/tests/unit/zurg/record/record.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { number, record, string } from "../../../../src/core/schemas/builders"; -import { itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("record", () => { - itSchemaIdentity(record(string(), string()), { hello: "world" }); - itSchemaIdentity(record(number(), string()), { 42: "world" }); - - itValidate( - "non-record", - record(number(), string()), - [], - [ - { - path: [], - message: "Expected object. Received list.", - }, - ] - ); - - itValidate("invalid key type", record(number(), string()), { hello: "world" }, [ - { - path: ["hello (key)"], - message: 'Expected number. Received "hello".', - }, - ]); - - itValidate("invalid value type", record(string(), number()), { hello: "world" }, [ - { - path: ["hello"], - message: 'Expected number. Received "world".', - }, - ]); -}); diff --git a/tests/unit/zurg/schema-utils/getSchemaUtils.test.ts b/tests/unit/zurg/schema-utils/getSchemaUtils.test.ts deleted file mode 100644 index da10086..0000000 --- a/tests/unit/zurg/schema-utils/getSchemaUtils.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { object, string } from "../../../../src/core/schemas/builders"; -import { itSchema } from "../utils/itSchema"; - -describe("getSchemaUtils", () => { - describe("optional()", () => { - itSchema("optional fields allow original schema", string().optional(), { - raw: "hello", - parsed: "hello", - }); - - itSchema("optional fields are not required", string().optional(), { - raw: null, - parsed: undefined, - }); - }); - - describe("transform()", () => { - itSchema( - "transorm and untransform run correctly", - string().transform({ - transform: (x) => x + "X", - untransform: (x) => (x as string).slice(0, -1), - }), - { - raw: "hello", - parsed: "helloX", - } - ); - }); - - describe("parseOrThrow()", () => { - it("parses valid value", async () => { - const value = string().parseOrThrow("hello"); - expect(value).toBe("hello"); - }); - - it("throws on invalid value", async () => { - const value = () => object({ a: string(), b: string() }).parseOrThrow({ a: 24 }); - expect(value).toThrowError(new Error('a: Expected string. Received 24.; Missing required key "b"')); - }); - }); - - describe("jsonOrThrow()", () => { - it("serializes valid value", async () => { - const value = string().jsonOrThrow("hello"); - expect(value).toBe("hello"); - }); - - it("throws on invalid value", async () => { - const value = () => object({ a: string(), b: string() }).jsonOrThrow({ a: 24 }); - expect(value).toThrowError(new Error('a: Expected string. Received 24.; Missing required key "b"')); - }); - }); - - describe("omitUndefined", () => { - it("serializes undefined as null", async () => { - const value = object({ - a: string().optional(), - b: string().optional(), - }).jsonOrThrow({ - a: "hello", - b: undefined, - }); - expect(value).toEqual({ a: "hello", b: null }); - }); - - it("omits undefined values", async () => { - const value = object({ - a: string().optional(), - b: string().optional(), - }).jsonOrThrow( - { - a: "hello", - b: undefined, - }, - { - omitUndefined: true, - } - ); - expect(value).toEqual({ a: "hello" }); - }); - }); -}); diff --git a/tests/unit/zurg/schema.test.ts b/tests/unit/zurg/schema.test.ts deleted file mode 100644 index 94089a9..0000000 --- a/tests/unit/zurg/schema.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { - boolean, - discriminant, - list, - number, - object, - string, - stringLiteral, - union, -} from "../../../src/core/schemas/builders"; -import { booleanLiteral } from "../../../src/core/schemas/builders/literals/booleanLiteral"; -import { property } from "../../../src/core/schemas/builders/object/property"; -import { itSchema } from "./utils/itSchema"; - -describe("Schema", () => { - itSchema( - "large nested object", - object({ - a: string(), - b: stringLiteral("b value"), - c: property( - "raw_c", - list( - object({ - animal: union(discriminant("type", "_type"), { - dog: object({ value: boolean() }), - cat: object({ value: property("raw_cat", number()) }), - }), - }) - ) - ), - d: property("raw_d", boolean()), - e: booleanLiteral(true), - }), - { - raw: { - a: "hello", - b: "b value", - raw_c: [ - { - animal: { - _type: "dog", - value: true, - }, - }, - { - animal: { - _type: "cat", - raw_cat: 42, - }, - }, - ], - raw_d: false, - e: true, - }, - parsed: { - a: "hello", - b: "b value", - c: [ - { - animal: { - type: "dog", - value: true, - }, - }, - { - animal: { - type: "cat", - value: 42, - }, - }, - ], - d: false, - e: true, - }, - } - ); -}); diff --git a/tests/unit/zurg/set/set.test.ts b/tests/unit/zurg/set/set.test.ts deleted file mode 100644 index e17f908..0000000 --- a/tests/unit/zurg/set/set.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { set, string } from "../../../../src/core/schemas/builders"; -import { itSchema } from "../utils/itSchema"; -import { itValidateJson, itValidateParse } from "../utils/itValidate"; - -describe("set", () => { - itSchema("converts between raw list and parsed Set", set(string()), { - raw: ["A", "B"], - parsed: new Set(["A", "B"]), - }); - - itValidateParse("not a list", set(string()), 42, [ - { - path: [], - message: "Expected list. Received 42.", - }, - ]); - - itValidateJson( - "not a Set", - set(string()), - [], - [ - { - path: [], - message: "Expected Set. Received list.", - }, - ] - ); - - itValidateParse( - "invalid item type", - set(string()), - [42], - [ - { - path: ["[0]"], - message: "Expected string. Received 42.", - }, - ] - ); - - itValidateJson("invalid item type", set(string()), new Set([42]), [ - { - path: ["[0]"], - message: "Expected string. Received 42.", - }, - ]); -}); diff --git a/tests/unit/zurg/skipValidation.test.ts b/tests/unit/zurg/skipValidation.test.ts deleted file mode 100644 index 5dc8809..0000000 --- a/tests/unit/zurg/skipValidation.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* eslint-disable no-console */ - -import { boolean, number, object, property, string, undiscriminatedUnion } from "../../../src/core/schemas/builders"; - -describe("skipValidation", () => { - it("allows data that doesn't conform to the schema", async () => { - const warningLogs: string[] = []; - const originalConsoleWarn = console.warn; - console.warn = (...args) => warningLogs.push(args.join(" ")); - - const schema = object({ - camelCase: property("snake_case", string()), - numberProperty: number(), - requiredProperty: boolean(), - anyPrimitive: undiscriminatedUnion([string(), number(), boolean()]), - }); - - const parsed = await schema.parse( - { - snake_case: "hello", - numberProperty: "oops", - anyPrimitive: true, - }, - { - skipValidation: true, - } - ); - - expect(parsed).toEqual({ - ok: true, - value: { - camelCase: "hello", - numberProperty: "oops", - anyPrimitive: true, - }, - }); - - expect(warningLogs).toEqual([ - `Failed to validate. - - numberProperty: Expected number. Received "oops".`, - ]); - - console.warn = originalConsoleWarn; - }); -}); diff --git a/tests/unit/zurg/undiscriminated-union/undiscriminatedUnion.test.ts b/tests/unit/zurg/undiscriminated-union/undiscriminatedUnion.test.ts deleted file mode 100644 index 0e66433..0000000 --- a/tests/unit/zurg/undiscriminated-union/undiscriminatedUnion.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { number, object, property, string, undiscriminatedUnion } from "../../../../src/core/schemas/builders"; -import { itSchema, itSchemaIdentity } from "../utils/itSchema"; - -describe("undiscriminatedUnion", () => { - itSchemaIdentity(undiscriminatedUnion([string(), number()]), "hello world"); - - itSchemaIdentity(undiscriminatedUnion([object({ hello: string() }), object({ goodbye: string() })]), { - goodbye: "foo", - }); - - itSchema( - "Correctly transforms", - undiscriminatedUnion([object({ hello: string() }), object({ helloWorld: property("hello_world", string()) })]), - { - raw: { hello_world: "foo " }, - parsed: { helloWorld: "foo " }, - } - ); - - it("Returns errors for all variants", async () => { - const result = await undiscriminatedUnion([string(), number()]).parse(true); - if (result.ok) { - throw new Error("Unexpectedly passed validation"); - } - expect(result.errors).toEqual([ - { - message: "[Variant 0] Expected string. Received true.", - path: [], - }, - { - message: "[Variant 1] Expected number. Received true.", - path: [], - }, - ]); - }); - - describe("compile", () => { - // eslint-disable-next-line jest/expect-expect - it("doesn't compile with zero members", () => { - // @ts-expect-error - () => undiscriminatedUnion([]); - }); - }); -}); diff --git a/tests/unit/zurg/union/union.test.ts b/tests/unit/zurg/union/union.test.ts deleted file mode 100644 index 7901846..0000000 --- a/tests/unit/zurg/union/union.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { boolean, discriminant, number, object, string, union } from "../../../../src/core/schemas/builders"; -import { itSchema, itSchemaIdentity } from "../utils/itSchema"; -import { itValidate } from "../utils/itValidate"; - -describe("union", () => { - itSchemaIdentity( - union("type", { - lion: object({ - meows: boolean(), - }), - giraffe: object({ - heightInInches: number(), - }), - }), - { type: "lion", meows: true }, - { title: "doesn't transform discriminant when it's a string" } - ); - - itSchema( - "transforms discriminant when it's a discriminant()", - union(discriminant("type", "_type"), { - lion: object({ meows: boolean() }), - giraffe: object({ heightInInches: number() }), - }), - { - raw: { _type: "lion", meows: true }, - parsed: { type: "lion", meows: true }, - } - ); - - describe("allowUnrecognizedUnionMembers", () => { - itSchema( - "transforms discriminant & passes through values when discriminant value is unrecognized", - union(discriminant("type", "_type"), { - lion: object({ meows: boolean() }), - giraffe: object({ heightInInches: number() }), - }), - { - // @ts-expect-error - raw: { _type: "moose", isAMoose: true }, - // @ts-expect-error - parsed: { type: "moose", isAMoose: true }, - opts: { - allowUnrecognizedUnionMembers: true, - }, - } - ); - }); - - describe("withParsedProperties", () => { - it("Added property is included on parsed object", async () => { - const schema = union("type", { - lion: object({}), - tiger: object({ value: string() }), - }).withParsedProperties({ - printType: (parsed) => () => parsed.type, - }); - - const parsed = await schema.parse({ type: "lion" }); - if (!parsed.ok) { - throw new Error("Failed to parse"); - } - expect(parsed.value.printType()).toBe("lion"); - }); - }); - - itValidate( - "non-object", - union("type", { - lion: object({}), - tiger: object({ value: string() }), - }), - [], - [ - { - path: [], - message: "Expected object. Received list.", - }, - ] - ); - - itValidate( - "missing discriminant", - union("type", { - lion: object({}), - tiger: object({ value: string() }), - }), - {}, - [ - { - path: [], - message: 'Missing discriminant ("type")', - }, - ] - ); - - itValidate( - "unrecognized discriminant value", - union("type", { - lion: object({}), - tiger: object({ value: string() }), - }), - { - type: "bear", - }, - [ - { - path: ["type"], - message: 'Expected enum. Received "bear".', - }, - ] - ); -}); diff --git a/tests/unit/zurg/utils/itSchema.ts b/tests/unit/zurg/utils/itSchema.ts deleted file mode 100644 index 67b6c92..0000000 --- a/tests/unit/zurg/utils/itSchema.ts +++ /dev/null @@ -1,78 +0,0 @@ -/* eslint-disable jest/no-export */ -import { Schema, SchemaOptions } from "../../../../src/core/schemas/Schema"; - -export function itSchemaIdentity( - schema: Schema, - value: T, - { title = "functions as identity", opts }: { title?: string; opts?: SchemaOptions } = {} -): void { - itSchema(title, schema, { raw: value, parsed: value, opts }); -} - -export function itSchema( - title: string, - schema: Schema, - { - raw, - parsed, - opts, - only = false, - }: { - raw: Raw; - parsed: Parsed; - opts?: SchemaOptions; - only?: boolean; - } -): void { - // eslint-disable-next-line jest/valid-title - (only ? describe.only : describe)(title, () => { - itParse("parse()", schema, { raw, parsed, opts }); - itJson("json()", schema, { raw, parsed, opts }); - }); -} - -export function itParse( - title: string, - schema: Schema, - { - raw, - parsed, - opts, - }: { - raw: Raw; - parsed: Parsed; - opts?: SchemaOptions; - } -): void { - // eslint-disable-next-line jest/valid-title - it(title, () => { - const maybeValid = schema.parse(raw, opts); - if (!maybeValid.ok) { - throw new Error("Failed to parse() " + JSON.stringify(maybeValid.errors, undefined, 4)); - } - expect(maybeValid.value).toStrictEqual(parsed); - }); -} - -export function itJson( - title: string, - schema: Schema, - { - raw, - parsed, - opts, - }: { - raw: Raw; - parsed: Parsed; - opts?: SchemaOptions; - } -): void { - // eslint-disable-next-line jest/valid-title - it(title, () => { - const maybeValid = schema.json(parsed, opts); - if (!maybeValid.ok) { - throw new Error("Failed to json() " + JSON.stringify(maybeValid.errors, undefined, 4)); - } - expect(maybeValid.value).toStrictEqual(raw); - }); -} diff --git a/tests/unit/zurg/utils/itValidate.ts b/tests/unit/zurg/utils/itValidate.ts deleted file mode 100644 index 75b2c08..0000000 --- a/tests/unit/zurg/utils/itValidate.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* eslint-disable jest/no-export */ -import { Schema, SchemaOptions, ValidationError } from "../../../../src/core/schemas/Schema"; - -export function itValidate( - title: string, - schema: Schema, - input: unknown, - errors: ValidationError[], - opts?: SchemaOptions -): void { - // eslint-disable-next-line jest/valid-title - describe("parse()", () => { - itValidateParse(title, schema, input, errors, opts); - }); - describe("json()", () => { - itValidateJson(title, schema, input, errors, opts); - }); -} - -export function itValidateParse( - title: string, - schema: Schema, - raw: unknown, - errors: ValidationError[], - opts?: SchemaOptions -): void { - describe("parse", () => { - // eslint-disable-next-line jest/valid-title - it(title, async () => { - const maybeValid = await schema.parse(raw, opts); - if (maybeValid.ok) { - throw new Error("Value passed validation"); - } - expect(maybeValid.errors).toStrictEqual(errors); - }); - }); -} - -export function itValidateJson( - title: string, - schema: Schema, - parsed: unknown, - errors: ValidationError[], - opts?: SchemaOptions -): void { - describe("json", () => { - // eslint-disable-next-line jest/valid-title - it(title, async () => { - const maybeValid = await schema.json(parsed, opts); - if (maybeValid.ok) { - throw new Error("Value passed validation"); - } - expect(maybeValid.errors).toStrictEqual(errors); - }); - }); -} diff --git a/yarn.lock b/yarn.lock index d27bab1..e940807 100644 --- a/yarn.lock +++ b/yarn.lock @@ -663,9 +663,9 @@ form-data "^4.0.0" "@types/node@*": - version "22.10.0" - resolved "https://registry.yarnpkg.com/@types/node/-/node-22.10.0.tgz#89bfc9e82496b9c7edea3382583fa94f75896e81" - integrity sha512-XC70cRZVElFHfIUB40FgZOBbgJYFKKMa5nb9lxcwYstFG/Mi+/Y0bGS+rs6Dmhmkpq4pnNiLiuZAbc02YCOnmA== + version "22.10.1" + resolved "https://registry.yarnpkg.com/@types/node/-/node-22.10.1.tgz#41ffeee127b8975a05f8c4f83fb89bcb2987d766" + integrity sha512-qKgsUwfHZV2WCWLAnVP1JqnpE6Im6h3Y0+fYgMTasNQ7V++CBX5OT1as0g0f+OyubbFqhf6XVNIsmN4IIhEgGQ== dependencies: undici-types "~6.20.0" @@ -702,13 +702,6 @@ resolved "https://registry.yarnpkg.com/@types/url-join/-/url-join-4.0.1.tgz#4989c97f969464647a8586c7252d97b449cdc045" integrity sha512-wDXw9LEEUHyV+7UWy7U315nrJGJ7p1BzaCxDpEoLr789Dk1WDVMMlf3iBfbG2F8NdWnYyFbtTxUn2ZNbm1Q4LQ== -"@types/ws@^8.5.13": - version "8.5.13" - resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.13.tgz#6414c280875e2691d0d1e080b05addbf5cb91e20" - integrity sha512-osM/gWBTPKgHV8XkTunnegTRIsvF6owmf5w+JtAfOw472dptdm0dlGv4xCt6GwQRcC2XVOvvRE/0bAoQcL2QkA== - dependencies: - "@types/node" "*" - "@types/yargs-parser@*": version "21.0.3" resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-21.0.3.tgz#815e30b786d2e8f0dcd85fd5bcf5e1a04d008f15" @@ -1294,20 +1287,15 @@ domexception@^4.0.0: webidl-conversions "^7.0.0" electron-to-chromium@^1.5.41: - version "1.5.65" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.65.tgz#e2b9d84d31e187a847e3ccdcfb415ddd4a3d1ea7" - integrity sha512-PWVzBjghx7/wop6n22vS2MLU8tKGd4Q91aCEGhG/TYmW6PP5OcSXcdnxTe1NNt0T66N8D6jxh4kC8UsdzOGaIw== + version "1.5.67" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.67.tgz#66ebd2be4a77469ac2760ef5e9e460ba9a43a845" + integrity sha512-nz88NNBsD7kQSAGGJyp8hS6xSPtWwqNogA0mjtc2nUYeEf3nURK9qpV18TuBdDmEDgVWotS8Wkzf+V52dSQ/LQ== emittery@^0.13.1: version "0.13.1" resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.13.1.tgz#c04b8c3457490e0847ae51fced3af52d338e3dad" integrity sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ== -emittery@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/emittery/-/emittery-1.0.3.tgz#c9d2a9c689870f15251bb13b31c67715c26d69ac" - integrity sha512-tJdCJitoy2lrC2ldJcqN4vkqJ00lT+tOWNT1hBJjO/3FDMJa5TTIiYGCKGkn/WfCyOzUMObeohbVTj00fhiLiA== - emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" @@ -1659,11 +1647,6 @@ https-proxy-agent@^5.0.1: agent-base "6" debug "4" -human-id@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/human-id/-/human-id-4.1.1.tgz#2801fbd61b9a5c1c9170f332802db6408a39a4b0" - integrity sha512-3gKm/gCSUipeLsRYZbbdA1BD83lBoWUkZ7G9VFrhWPAU76KwYo5KR8V28bpoPm/ygy0x5/GCbpRQdY7VLYCoIg== - human-signals@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" @@ -2544,9 +2527,9 @@ prompts@^2.0.1: sisteransi "^1.0.5" psl@^1.1.33: - version "1.13.0" - resolved "https://registry.yarnpkg.com/psl/-/psl-1.13.0.tgz#8b2357f13ef3cf546af3f52de00543a94da86cfa" - integrity sha512-BFwmFXiJoFqlUpZ5Qssolv15DMyc84gTBds1BjsV1BfXEo1UyyD7GsmN67n7J77uRhoSNW1AXtXKPLcBFQn9Aw== + version "1.14.0" + resolved "https://registry.yarnpkg.com/psl/-/psl-1.14.0.tgz#f6ccbbd63e4e663f830ca39eeea08feb3caceaaf" + integrity sha512-Syk1bnf6fRZ9wQs03AtKJHcM12cKbOLo9L8JtCCdYj5/DTsHmTyXM4BK5ouWeG2P6kZ4nmFvuNTdtaqfobCOCg== dependencies: punycode "^2.3.1" @@ -3146,7 +3129,7 @@ write-file-atomic@^4.0.2: imurmurhash "^0.1.4" signal-exit "^3.0.7" -ws@^8.11.0, ws@^8.14.2: +ws@^8.11.0: version "8.18.0" resolved "https://registry.yarnpkg.com/ws/-/ws-8.18.0.tgz#0d7505a6eafe2b0e712d232b42279f53bc289bbc" integrity sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==