@ai-sdk/topaz 0.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/topaz-error.ts","../src/topaz-image-model-options.ts","../src/topaz-image-settings.ts","../src/topaz-image-model.ts","../src/topaz-video-model-options.ts","../src/topaz-video-settings.ts","../src/version.ts","../src/topaz-video-model.ts","../src/topaz-provider.ts"],"sourcesContent":["import { createJsonErrorResponseHandler } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n/**\n * The image API reports errors as `{ \"message\": ... }` and the video API as\n * `{ \"message\": ..., \"errorCode\": ... }`. `detail` (a message or FastAPI's\n * array of validation issues) and `error` are accepted as well because a few\n * endpoints use them instead.\n */\nexport const topazErrorDataSchema = z.object({\n detail: z\n .union([\n z.string(),\n z.array(z.object({ msg: z.string().nullish() }).loose()),\n ])\n .nullish(),\n message: z.string().nullish(),\n error: z.string().nullish(),\n errorCode: z.string().nullish(),\n errors: z.array(z.object({ msg: z.string().nullish() }).loose()).nullish(),\n});\n\nexport type TopazErrorData = z.infer<typeof topazErrorDataSchema>;\n\nexport function topazErrorToMessage(data: TopazErrorData): string {\n const message = baseErrorMessage(data);\n const withCode =\n data.errorCode != null ? `${message} (${data.errorCode})` : message;\n\n // The video API lists field validation failures separately.\n const issues = (data.errors ?? [])\n .map(issue => issue.msg)\n .filter((msg): msg is string => msg != null);\n\n return issues.length > 0 ? `${withCode}: ${issues.join('; ')}` : withCode;\n}\n\nfunction baseErrorMessage(data: TopazErrorData): string {\n const { detail } = data;\n\n if (typeof detail === 'string') {\n return detail;\n }\n\n if (Array.isArray(detail)) {\n const messages = detail\n .map(issue => issue.msg)\n .filter((msg): msg is string => msg != null);\n\n if (messages.length > 0) {\n return messages.join('; ');\n }\n }\n\n return data.message ?? data.error ?? 'Unknown Topaz API error';\n}\n\nexport const topazFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: topazErrorDataSchema,\n errorToMessage: topazErrorToMessage,\n});\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n/**\n * Provider options for Topaz generative image models (Wonder 3.5).\n *\n * The documented request schema fields are sent in snake_case\n * (`output_width`, `output_format`, ...); model-specific settings are sent in\n * camelCase, matching the Topaz model reference.\n *\n * @see https://developer.topazlabs.com/image-models/wonder/wonder-3.5-new\n */\nexport const topazImageModelOptionsSchema = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * How aggressively the model enhances the image. Defaults to `high`.\n */\n enhancementStrength: z.enum(['low', 'medium', 'high']).optional(),\n\n /**\n * Whether to add grain to the output. Defaults to `false`.\n */\n grain: z.boolean().optional(),\n\n /**\n * Grain intensity, 0.0 to 1.0. Defaults to 0.5.\n */\n grainDensity: z.number().min(0).max(1).optional(),\n\n /**\n * Grain model. Defaults to `silver`.\n */\n grainModel: z.enum(['silver', 'gaussian', 'grey']).optional(),\n\n /**\n * Grain particle size, 1 to 5. Defaults to 1.\n */\n grainSize: z.number().min(1).max(5).optional(),\n\n /**\n * Grain effect strength, 0.0 to 1.0. Defaults to 0.5.\n */\n grainStrength: z.number().min(0).max(1).optional(),\n\n /**\n * Width of the input image in pixels. Topaz infers this from the upload when\n * omitted.\n */\n inputWidth: z.number().int().positive().optional(),\n\n /**\n * Height of the input image in pixels. Topaz infers this from the upload\n * when omitted.\n */\n inputHeight: z.number().int().positive().optional(),\n\n /**\n * Width of the output image in pixels, 1 to 32000. Takes precedence over the\n * width derived from the `size` call option.\n */\n outputWidth: z.number().int().min(1).max(32000).optional(),\n\n /**\n * Height of the output image in pixels, 1 to 32000. Takes precedence over\n * the height derived from the `size` call option.\n */\n outputHeight: z.number().int().min(1).max(32000).optional(),\n\n /**\n * Output image format. Defaults to the Topaz API default.\n */\n outputFormat: z.enum(['jpeg', 'jpg', 'png', 'tiff', 'tif']).optional(),\n\n /**\n * Whether to crop the output to fill the requested dimensions. Defaults to\n * `false`.\n */\n cropToFill: z.boolean().optional(),\n\n /**\n * URL to receive job-status webhooks.\n */\n webhookUrl: z.string().optional(),\n\n /**\n * How often to poll the Topaz status endpoint, in milliseconds. Defaults to\n * 2000.\n */\n pollIntervalMillis: z.number().int().positive().optional(),\n\n /**\n * How long to wait for the job to finish before failing, in milliseconds.\n * Defaults to 600000 (10 minutes).\n */\n pollTimeoutMillis: z.number().int().positive().optional(),\n }),\n ),\n);\n\nexport type TopazImageModelOptions = InferSchema<\n typeof topazImageModelOptionsSchema\n>;\n","/**\n * Topaz image model ids.\n *\n * The AI SDK exposes a readable id that is mapped onto the name the Topaz API\n * expects in the `model` form field (see `topazImageApiModelIds`). Passing a\n * raw Topaz name such as `Wonder 3.5` also works - unknown ids are forwarded\n * to the API unchanged.\n */\nexport type TopazImageModelId = 'wonder-3.5' | (string & {});\n\n/**\n * Maps AI SDK image model ids onto Topaz API model names.\n *\n * @see https://developer.topazlabs.com/image-models/wonder/wonder-3.5-new\n */\nexport const topazImageApiModelIds: Record<string, string> = {\n 'wonder-3.5': 'Wonder 3.5',\n};\n\nexport function resolveTopazImageApiModelId(modelId: string): string {\n return topazImageApiModelIds[modelId] ?? modelId;\n}\n","import {\n AISDKError,\n InvalidArgumentError,\n InvalidResponseDataError,\n type ImageModelV4,\n type ImageModelV4CallOptions,\n type ImageModelV4Result,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n combineHeaders,\n convertBase64ToUint8Array,\n createBinaryResponseHandler,\n createJsonResponseHandler,\n delay,\n getFromApi,\n mediaTypeToExtension,\n parseProviderOptions,\n postFormDataToApi,\n removeUndefinedEntries,\n resolve,\n serializeModelOptions,\n WORKFLOW_DESERIALIZE,\n WORKFLOW_SERIALIZE,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { TopazConfig } from './topaz-config';\nimport { topazFailedResponseHandler } from './topaz-error';\nimport {\n topazImageModelOptionsSchema,\n type TopazImageModelOptions,\n} from './topaz-image-model-options';\nimport {\n resolveTopazImageApiModelId,\n type TopazImageModelId,\n} from './topaz-image-settings';\n\nconst DEFAULT_POLL_INTERVAL_MILLIS = 2000;\nconst DEFAULT_POLL_TIMEOUT_MILLIS = 600_000;\n\n/**\n * Topaz enhances an image that the caller supplies, so `files` is required and\n * exactly one image is processed per call.\n */\nexport class TopazImageModel implements ImageModelV4 {\n readonly specificationVersion = 'v4';\n readonly maxImagesPerCall = 1;\n readonly supportsFileInputs = true;\n readonly supportsMaskInputs = false;\n\n get provider(): string {\n return this.config.provider;\n }\n\n static [WORKFLOW_SERIALIZE](model: TopazImageModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: TopazImageModelId;\n config: TopazConfig;\n }) {\n return new TopazImageModel(options.modelId, options.config);\n }\n\n constructor(\n readonly modelId: TopazImageModelId,\n private readonly config: TopazConfig,\n ) {}\n\n async doGenerate(\n options: ImageModelV4CallOptions,\n ): Promise<ImageModelV4Result> {\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n const warnings: SharedV4Warning[] = [];\n\n const topazOptions = await parseProviderOptions({\n provider: 'topaz',\n providerOptions: options.providerOptions,\n schema: topazImageModelOptionsSchema,\n });\n const headers = combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n );\n\n this.addUnsupportedWarnings(options, warnings);\n\n const formData = await this.buildFormData(options, topazOptions, warnings);\n\n const { value: submitResponse } = await postFormDataToApi({\n url: `${this.config.baseURL}/image/v1/enhance-gen/async`,\n headers,\n formData,\n successfulResponseHandler: createJsonResponseHandler(\n topazImageSubmitResponseSchema,\n ),\n failedResponseHandler: topazFailedResponseHandler,\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const processId = submitResponse.process_id;\n if (processId == null) {\n throw new InvalidResponseDataError({\n data: submitResponse,\n message: 'Topaz did not return a process_id for the enhance request.',\n });\n }\n\n let status: TopazImageStatusResponse;\n try {\n status = await this.waitForCompletion({\n processId,\n headers,\n abortSignal: options.abortSignal,\n pollIntervalMillis:\n topazOptions?.pollIntervalMillis ?? DEFAULT_POLL_INTERVAL_MILLIS,\n pollTimeoutMillis:\n topazOptions?.pollTimeoutMillis ?? DEFAULT_POLL_TIMEOUT_MILLIS,\n });\n } catch (error) {\n // Topaz charges on completion, so a job nobody will download should not\n // be left running after the caller aborts.\n if (options.abortSignal?.aborted) {\n await this.cancelQuietly(processId, headers);\n }\n throw error;\n }\n\n const { image, responseHeaders } = await this.download({\n processId,\n headers,\n abortSignal: options.abortSignal,\n });\n\n return {\n images: [image],\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n },\n providerMetadata: {\n topaz: {\n images: [\n {\n processId,\n // Topaz bills exactly the credits reported on the completed job.\n ...(status.credits != null ? { credits: status.credits } : {}),\n ...(status.output_width != null\n ? { width: status.output_width }\n : {}),\n ...(status.output_height != null\n ? { height: status.output_height }\n : {}),\n ...(status.output_format != null\n ? { format: status.output_format }\n : {}),\n },\n ],\n },\n },\n };\n }\n\n private addUnsupportedWarnings(\n options: ImageModelV4CallOptions,\n warnings: SharedV4Warning[],\n ): void {\n if (options.prompt != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'prompt',\n details:\n 'Topaz image models enhance an existing image and do not take a text prompt. ' +\n 'The prompt was ignored.',\n });\n }\n\n if (options.aspectRatio != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'aspectRatio',\n details:\n 'Topaz image models do not support aspectRatio. Use `size`, or the ' +\n '`outputWidth` / `outputHeight` provider options, to set output dimensions.',\n });\n }\n\n if (options.seed != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'seed',\n details: 'Topaz image models do not support seed.',\n });\n }\n\n if (options.mask != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'mask',\n details:\n 'Topaz image models do not support masks. The mask was ignored.',\n });\n }\n\n if (options.n > 1) {\n warnings.push({\n type: 'unsupported',\n feature: 'n',\n details:\n 'Topaz image models enhance one image per call. Only 1 image will be returned.',\n });\n }\n }\n\n private async buildFormData(\n options: ImageModelV4CallOptions,\n topazOptions: TopazImageModelOptions | undefined,\n warnings: SharedV4Warning[],\n ): Promise<FormData> {\n const file = options.files?.[0];\n\n if (file == null) {\n throw new InvalidArgumentError({\n argument: 'files',\n message:\n 'Topaz image models enhance an existing image. Pass the input image via ' +\n '`prompt.images`.',\n });\n }\n\n if (options.files != null && options.files.length > 1) {\n warnings.push({\n type: 'unsupported',\n feature: 'files',\n details:\n 'Topaz image models enhance one image per call. Only the first file was used.',\n });\n }\n\n const formData = new FormData();\n formData.append('model', resolveTopazImageApiModelId(this.modelId));\n\n if (file.type === 'url') {\n // Topaz fetches the source itself when given a URL, so the bytes never\n // need to pass through the SDK.\n formData.append('source_url', file.url);\n } else {\n const bytes =\n typeof file.data === 'string'\n ? convertBase64ToUint8Array(file.data)\n : file.data;\n const extension = mediaTypeToExtension(file.mediaType) ?? 'png';\n\n formData.append(\n 'image',\n new File([bytes as BlobPart], `image.${extension}`, {\n type: file.mediaType,\n }),\n );\n }\n\n const { width, height } = parseSize(options.size);\n\n appendIfDefined(\n formData,\n 'output_width',\n topazOptions?.outputWidth ?? width,\n );\n appendIfDefined(\n formData,\n 'output_height',\n topazOptions?.outputHeight ?? height,\n );\n appendIfDefined(formData, 'output_format', topazOptions?.outputFormat);\n appendIfDefined(formData, 'crop_to_fill', topazOptions?.cropToFill);\n appendIfDefined(formData, 'webhook_url', topazOptions?.webhookUrl);\n\n // Model-specific settings use camelCase, unlike the request schema fields\n // above.\n appendIfDefined(\n formData,\n 'enhancementStrength',\n topazOptions?.enhancementStrength,\n );\n appendIfDefined(formData, 'grain', topazOptions?.grain);\n appendIfDefined(formData, 'grainDensity', topazOptions?.grainDensity);\n appendIfDefined(formData, 'grainModel', topazOptions?.grainModel);\n appendIfDefined(formData, 'grainSize', topazOptions?.grainSize);\n appendIfDefined(formData, 'grainStrength', topazOptions?.grainStrength);\n appendIfDefined(formData, 'inputWidth', topazOptions?.inputWidth);\n appendIfDefined(formData, 'inputHeight', topazOptions?.inputHeight);\n\n return formData;\n }\n\n private async waitForCompletion({\n processId,\n headers,\n abortSignal,\n pollIntervalMillis,\n pollTimeoutMillis,\n }: {\n processId: string;\n headers: Record<string, string | undefined> | undefined;\n abortSignal: AbortSignal | undefined;\n pollIntervalMillis: number;\n pollTimeoutMillis: number;\n }): Promise<TopazImageStatusResponse> {\n const deadline = Date.now() + pollTimeoutMillis;\n\n while (true) {\n const { value: status } = await getFromApi({\n url: `${this.config.baseURL}/image/v1/status/${processId}`,\n // Built from the configured baseURL, not from response data.\n validateUrl: false,\n headers,\n successfulResponseHandler: createJsonResponseHandler(\n topazImageStatusResponseSchema,\n ),\n failedResponseHandler: topazFailedResponseHandler,\n abortSignal,\n fetch: this.config.fetch,\n });\n\n if (status.status === 'Completed') {\n return status;\n }\n\n if (status.status === 'Failed' || status.status === 'Cancelled') {\n throw new AISDKError({\n name: 'TOPAZ_IMAGE_ENHANCEMENT_FAILED',\n message: `Topaz image enhancement ${status.status.toLowerCase()} for process ${processId}.`,\n });\n }\n\n if (Date.now() + pollIntervalMillis > deadline) {\n await this.cancelQuietly(processId, headers ?? {});\n throw new AISDKError({\n name: 'TOPAZ_IMAGE_ENHANCEMENT_TIMEOUT',\n message:\n `Topaz image enhancement did not finish within ${pollTimeoutMillis}ms ` +\n `(process ${processId}, last status ${status.status ?? 'unknown'}). ` +\n 'Increase the `pollTimeoutMillis` provider option if the job needs longer.',\n });\n }\n\n await delay(pollIntervalMillis, { abortSignal });\n }\n }\n\n private async cancelQuietly(\n processId: string,\n headers: Record<string, string | undefined>,\n ): Promise<void> {\n const fetchImpl = this.config.fetch ?? globalThis.fetch;\n\n try {\n // Deliberately not tied to the caller's abort signal, which may be the\n // reason polling stopped.\n await fetchImpl(`${this.config.baseURL}/image/v1/cancel/${processId}`, {\n method: 'DELETE',\n headers: removeUndefinedEntries(headers),\n });\n } catch {\n // Best effort: the original error is more useful to the caller.\n }\n }\n\n private async download({\n processId,\n headers,\n abortSignal,\n }: {\n processId: string;\n headers: Record<string, string | undefined> | undefined;\n abortSignal: AbortSignal | undefined;\n }): Promise<{\n image: Uint8Array;\n responseHeaders: Record<string, string> | undefined;\n }> {\n const { value: downloadResponse } = await getFromApi({\n url: `${this.config.baseURL}/image/v1/download/${processId}`,\n // Built from the configured baseURL, not from response data.\n validateUrl: false,\n headers,\n successfulResponseHandler: createJsonResponseHandler(\n topazImageDownloadResponseSchema,\n ),\n failedResponseHandler: topazFailedResponseHandler,\n abortSignal,\n fetch: this.config.fetch,\n });\n\n const downloadUrl = downloadResponse.download_url;\n if (downloadUrl == null) {\n throw new InvalidResponseDataError({\n data: downloadResponse,\n message: `Topaz did not return a download URL for process ${processId}.`,\n });\n }\n\n const { value: image, responseHeaders } = await getFromApi({\n url: downloadUrl,\n // Comes from the Topaz response body and normally points at object\n // storage, so it is validated and the API key is withheld off-origin.\n validateUrl: true,\n credentialedOrigin: this.config.baseURL,\n trustedOrigin: this.config.baseURL,\n headers,\n successfulResponseHandler: createBinaryResponseHandler(),\n failedResponseHandler: topazFailedResponseHandler,\n abortSignal,\n fetch: this.config.fetch,\n });\n\n return { image, responseHeaders };\n }\n}\n\nfunction parseSize(size: `${number}x${number}` | undefined): {\n width: number | undefined;\n height: number | undefined;\n} {\n if (size == null) {\n return { width: undefined, height: undefined };\n }\n\n const [width, height] = size.split('x').map(Number);\n return { width, height };\n}\n\nfunction appendIfDefined(\n formData: FormData,\n key: string,\n value: string | number | boolean | undefined,\n): void {\n if (value !== undefined) {\n formData.append(key, String(value));\n }\n}\n\nconst topazImageSubmitResponseSchema = z.object({\n process_id: z.string().nullish(),\n});\n\nconst topazImageStatusResponseSchema = z.object({\n // Documented values are Pending, Processing, Completed, Cancelled and Failed.\n // Unknown values keep polling rather than failing the parse.\n status: z.string().nullish(),\n credits: z.number().nullish(),\n output_width: z.number().nullish(),\n output_height: z.number().nullish(),\n output_format: z.string().nullish(),\n});\n\ntype TopazImageStatusResponse = z.infer<typeof topazImageStatusResponseSchema>;\n\nconst topazImageDownloadResponseSchema = z.object({\n download_url: z.string().nullish(),\n});\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n/**\n * Containers Topaz accepts for the input video.\n */\nexport const topazSourceContainers = [\n '3gp',\n 'avi',\n 'dv',\n 'flv',\n 'm1v',\n 'm2t',\n 'm2ts',\n 'm2v',\n 'm4v',\n 'mkv',\n 'mov',\n 'mp4',\n 'mpeg',\n 'mpg',\n 'mts',\n 'mxf',\n 'ser',\n 'ts',\n 'vob',\n 'webm',\n 'wmv',\n] as const;\n\n/**\n * Containers Topaz can produce for the enhanced video.\n */\nexport const topazOutputContainers = [\n 'mp4',\n 'mov',\n 'mkv',\n 'avi',\n 'webm',\n] as const;\n\n/**\n * Metadata about the input video.\n *\n * Starlight models require `width`, `height`, `duration` and `frameRate`\n * (Topaz prices them from these values), and for other models they let Topaz\n * estimate the cost before it has the video. The AI SDK does not inspect\n * media files, so the values come from the caller. Setting any of them\n * requires all four.\n */\nexport const topazVideoSourceSchema = z.object({\n /**\n * Width of the input video in pixels.\n */\n width: z.number().int().positive().optional(),\n\n /**\n * Height of the input video in pixels.\n */\n height: z.number().int().positive().optional(),\n\n /**\n * Duration of the input video in seconds.\n */\n duration: z.number().positive().optional(),\n\n /**\n * Frame rate of the input video.\n */\n frameRate: z.number().positive().optional(),\n\n /**\n * Total number of frames in the input video. Derived from\n * `duration * frameRate` when omitted, which is only correct for\n * constant-frame-rate input, so set it explicitly for variable-frame-rate\n * sources.\n */\n frameCount: z.number().int().positive().optional(),\n\n /**\n * Container of the input video. Detected from the input file's media type\n * or URL extension when omitted.\n */\n container: z.enum(topazSourceContainers).optional(),\n});\n\nexport type TopazVideoSource = z.infer<typeof topazVideoSourceSchema>;\n\n/**\n * Output settings for the enhanced video.\n */\nexport const topazVideoOutputSchema = z.object({\n /**\n * Width of the output video in pixels. Takes precedence over the\n * `resolution` call option.\n */\n width: z.number().int().positive().optional(),\n\n /**\n * Height of the output video in pixels. Takes precedence over the\n * `resolution` call option.\n */\n height: z.number().int().positive().optional(),\n\n /**\n * Frame rate of the output video. Takes precedence over the `fps` call\n * option. Topaz only changes the frame rate when a frame-interpolation\n * filter is present.\n */\n frameRate: z.number().positive().optional(),\n\n /**\n * Audio codec of the output video. Defaults to `AAC`.\n */\n audioCodec: z.enum(['AAC', 'AC3', 'PCM']).optional(),\n\n /**\n * Audio bitrate, e.g. `192k`. Topaz uses the codec default when omitted.\n */\n audioBitrate: z.string().optional(),\n\n /**\n * How to handle the input audio track. Defaults to `Copy`.\n */\n audioTransfer: z.enum(['Copy', 'Convert', 'None']).optional(),\n\n /**\n * Video encoder. Topaz defaults to `H265`. `ProRes` forces a `mov`\n * container, `AV1` and `VP9` force `mp4`.\n */\n videoEncoder: z.enum(['AV1', 'H264', 'H265', 'ProRes', 'VP9']).optional(),\n\n /**\n * Encoder profile, e.g. `Main10` for H265 or `422 HQ` for ProRes. Topaz uses\n * the encoder's default profile when omitted.\n */\n videoProfile: z.string().optional(),\n\n /**\n * Constant bitrate, e.g. `20m`. Required for `VP9`. Mutually exclusive with\n * `dynamicCompressionLevel`.\n */\n videoBitrate: z.string().optional(),\n\n /**\n * Automatic constant-quality compression level. Topaz defaults to `High`\n * unless `videoBitrate` is set.\n */\n dynamicCompressionLevel: z.enum(['Low', 'Mid', 'High']).optional(),\n\n /**\n * Center-crop to fit the output dimensions.\n */\n cropToFit: z.boolean().optional(),\n\n /**\n * Container of the output video. Defaults to the input container when Topaz\n * can produce it, otherwise `mp4`.\n */\n container: z.enum(topazOutputContainers).optional(),\n});\n\nexport type TopazVideoOutput = z.infer<typeof topazVideoOutputSchema>;\n\n/**\n * Provider options for Topaz video models.\n *\n * @see https://developer.topazlabs.com/video-models/proteus/proteus-1\n * @see https://developer.topazlabs.com/video-models/starlight/starlight-precise-2.6\n */\nexport const topazVideoModelOptionsSchema = lazySchema(() =>\n zodSchema(\n z.object({\n source: topazVideoSourceSchema.optional(),\n output: topazVideoOutputSchema.optional(),\n\n /**\n * Extra `filters[]` entries to send alongside the model's own filter, e.g. a\n * frame-interpolation filter. Each entry must include a `model` key.\n */\n additionalFilters: z.array(z.record(z.string(), z.unknown())).optional(),\n\n /**\n * Escape hatch for filter settings this package does not model yet. Merged\n * into the model's filter entry, taking precedence over the typed options\n * below.\n */\n filter: z.record(z.string(), z.unknown()).optional(),\n\n // ---------------------------------------------------------------------------\n // Proteus (`proteus`)\n // ---------------------------------------------------------------------------\n\n /** Proteus: how the input frames are encoded. */\n videoType: z\n .enum(['Progressive', 'Interlaced', 'ProgressiveInterlaced'])\n .optional(),\n\n /** Proteus: parameter estimation mode. */\n auto: z.enum(['Auto', 'Manual', 'Relative']).optional(),\n\n /** Proteus: field order for interlaced input. */\n fieldOrder: z.enum(['TopFirst', 'BottomFirst', 'Auto']).optional(),\n\n /** Proteus: focus-fix strength. */\n focusFixLevel: z.enum(['None', 'Normal', 'Strong']).optional(),\n\n /** Proteus: compression artifact removal, -1 to 1. */\n compression: z.number().min(-1).max(1).optional(),\n\n /** Proteus: detail recovery, -1 to 1. */\n details: z.number().min(-1).max(1).optional(),\n\n /** Proteus: pre-processing noise reduction, 0 to 0.1. */\n prenoise: z.number().min(0).max(0.1).optional(),\n\n /** Proteus: noise reduction, -1 to 1. */\n noise: z.number().min(-1).max(1).optional(),\n\n /** Proteus: halo suppression, -1 to 1. */\n halo: z.number().min(-1).max(1).optional(),\n\n /** Proteus: pre-processing blur, -1 to 1. */\n preblur: z.number().min(-1).max(1).optional(),\n\n /** Proteus: sharpening, -1 to 1. */\n blur: z.number().min(-1).max(1).optional(),\n\n /** Proteus: grain amount, 0 to 0.1. */\n grain: z.number().min(0).max(0.1).optional(),\n\n /** Proteus: grain sigma, 0 to 1. */\n grainSigma: z.number().min(0).max(1).optional(),\n\n /** Proteus: grain size, 0 to 5. */\n grainSize: z.number().min(0).max(5).optional(),\n\n /** Proteus: grain model. */\n grainType: z.enum(['silver_rich', 'gaussian', 'grey']).optional(),\n\n /** Proteus: original detail recovery, 0 to 1. */\n recoverOriginalDetailValue: z.number().min(0).max(1).optional(),\n\n // ---------------------------------------------------------------------------\n // Starlight Precise (`starlight-precise-2.6`)\n // ---------------------------------------------------------------------------\n\n /** Starlight: sharpening applied to the output, 1.0 to 5.0. Defaults to 5.0. */\n sharpness: z.number().min(1).max(5).optional(),\n\n /** Starlight: output bit depth. */\n videoBitDepth: z.number().int().positive().optional(),\n\n /** Starlight: output video codec. */\n videoCodec: z.enum(['ffv1', 'prores', 'vp9']).optional(),\n\n /** Starlight: output chroma subsampling profile. */\n videoProfile: z.enum(['420', '422', '444']).optional(),\n\n /** Starlight: whether to watermark the output. Defaults to `false`. */\n watermark: z.boolean().optional(),\n }),\n ),\n);\n\nexport type TopazVideoModelOptions = InferSchema<\n typeof topazVideoModelOptionsSchema\n>;\n\n/**\n * Option keys that are structural rather than filter settings, so they are not\n * forwarded into the `filters[]` entry.\n */\nexport const TOPAZ_NON_FILTER_OPTION_KEYS = [\n 'source',\n 'output',\n 'additionalFilters',\n 'filter',\n] as const satisfies ReadonlyArray<keyof TopazVideoModelOptions>;\n","/**\n * Topaz video model ids.\n *\n * The AI SDK exposes readable ids that are mapped onto the short names the\n * Topaz API expects in the `filters[].model` field (see\n * `topazVideoApiModelIds`). Passing a raw Topaz name such as `slp-2.6` also\n * works - unknown ids are forwarded to the API unchanged.\n */\nexport type TopazVideoModelId =\n | 'proteus'\n | 'starlight-precise-2.6'\n | (string & {});\n\n/**\n * Maps AI SDK video model ids onto Topaz API model names.\n *\n * @see https://developer.topazlabs.com/video-models/proteus/proteus-1\n * @see https://developer.topazlabs.com/video-models/starlight/starlight-precise-2.6\n */\nexport const topazVideoApiModelIds: Record<string, string> = {\n proteus: 'prob-4',\n 'starlight-precise-2.6': 'slp-2.6',\n};\n\nexport function resolveTopazVideoApiModelId(modelId: string): string {\n return topazVideoApiModelIds[modelId] ?? modelId;\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n APICallError,\n InvalidArgumentError,\n InvalidResponseDataError,\n type Experimental_VideoModelV4 as VideoModelV4,\n type Experimental_VideoModelV4File as VideoModelV4File,\n type Experimental_VideoModelV4OperationStartResult as VideoModelV4OperationStartResult,\n type Experimental_VideoModelV4OperationStatusResult as VideoModelV4OperationStatusResult,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n combineHeaders,\n convertBase64ToUint8Array,\n createJsonResponseHandler,\n getFromApi,\n isSameOrigin,\n parseProviderOptions,\n postJsonToApi,\n removeUndefinedEntries,\n resolve,\n serializeModelOptions,\n validateDownloadUrl,\n withUserAgentSuffix,\n WORKFLOW_DESERIALIZE,\n WORKFLOW_SERIALIZE,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { TopazConfig } from './topaz-config';\nimport { topazFailedResponseHandler } from './topaz-error';\nimport {\n TOPAZ_NON_FILTER_OPTION_KEYS,\n type topazOutputContainers,\n topazSourceContainers,\n topazVideoModelOptionsSchema,\n type TopazVideoModelOptions,\n} from './topaz-video-model-options';\nimport {\n resolveTopazVideoApiModelId,\n type TopazVideoModelId,\n} from './topaz-video-settings';\nimport { VERSION } from './version';\n\ntype TopazSourceContainer = (typeof topazSourceContainers)[number];\ntype TopazOutputContainer = (typeof topazOutputContainers)[number];\n\nconst mediaTypeContainers: Record<string, TopazSourceContainer> = {\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'video/mov': 'mov',\n 'video/x-matroska': 'mkv',\n 'video/matroska': 'mkv',\n 'video/webm': 'webm',\n 'video/x-msvideo': 'avi',\n 'video/avi': 'avi',\n 'video/mpeg': 'mpeg',\n 'video/mp2t': 'ts',\n 'video/x-ms-wmv': 'wmv',\n 'video/x-flv': 'flv',\n 'video/3gpp': '3gp',\n 'video/x-m4v': 'm4v',\n 'application/mxf': 'mxf',\n};\n\nconst extensionContainers: Record<string, TopazSourceContainer> = {\n ...Object.fromEntries(topazSourceContainers.map(c => [c, c])),\n qt: 'mov',\n};\n\nconst containerMediaTypes: Record<string, string> = {\n mp4: 'video/mp4',\n m4v: 'video/mp4',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mpeg: 'video/mpeg',\n mpg: 'video/mpeg',\n ts: 'video/mp2t',\n wmv: 'video/x-ms-wmv',\n flv: 'video/x-flv',\n '3gp': 'video/3gpp',\n mxf: 'application/mxf',\n};\n\n/**\n * Topaz video models enhance a video the caller supplies, passed through\n * `inputReferences`. `doStart` creates an express request: Topaz fetches URL\n * inputs itself, and file inputs are uploaded to the returned URL. Processing\n * starts once Topaz has the video, and `doStatus` polls.\n */\nexport class TopazVideoModel implements VideoModelV4 {\n readonly specificationVersion = 'v4';\n readonly maxVideosPerCall = 1;\n\n get provider(): string {\n return this.config.provider;\n }\n\n static [WORKFLOW_SERIALIZE](model: TopazVideoModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: TopazVideoModelId;\n config: TopazConfig;\n }) {\n return new TopazVideoModel(options.modelId, options.config);\n }\n\n constructor(\n readonly modelId: TopazVideoModelId,\n private readonly config: TopazConfig,\n ) {}\n\n async doStart(\n options: Parameters<NonNullable<VideoModelV4['doStart']>>[0],\n ): Promise<VideoModelV4OperationStartResult> {\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n const warnings: SharedV4Warning[] = [];\n\n const topazOptions = await parseProviderOptions({\n provider: 'topaz',\n providerOptions: options.providerOptions,\n schema: topazVideoModelOptionsSchema,\n });\n const headers = combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n );\n\n this.addUnsupportedWarnings(options, warnings);\n\n const input = this.selectInputVideo(options, warnings);\n const container = resolveContainer(input, topazOptions?.source?.container);\n const source = resolveSource(topazOptions, container);\n const output = buildOutput({ options, topazOptions, source });\n const filters = [\n buildFilter(this.modelId, topazOptions),\n ...(topazOptions?.additionalFilters ?? []),\n ];\n const contentType =\n containerMediaTypes[source.container] ?? 'application/octet-stream';\n\n const metadata = source.metadata;\n const bytes = input.type === 'file' ? fileBytes(input) : undefined;\n let requestId: string | undefined;\n\n try {\n const { value: created, responseHeaders } = await postJsonToApi({\n url: `${this.config.baseURL}/video/express`,\n headers,\n body: {\n source: {\n container: source.container,\n ...(metadata != null\n ? {\n duration: metadata.duration,\n frameCount: metadata.frameCount,\n frameRate: metadata.frameRate,\n resolution: {\n width: metadata.width,\n height: metadata.height,\n },\n }\n : {}),\n ...(input.type === 'url'\n ? // Topaz fetches URL inputs itself, so, like other providers,\n // the SDK never downloads them.\n { external: { provider: 's3', presignedUrl: input.url } }\n : { size: bytes?.byteLength }),\n },\n output,\n filters,\n },\n successfulResponseHandler: createJsonResponseHandler(\n topazVideoExpressResponseSchema,\n ),\n failedResponseHandler: topazFailedResponseHandler,\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n requestId = requireRequestId(created.requestId);\n\n if (bytes != null) {\n await this.uploadVideo({\n requestId,\n bytes,\n urls: created.uploadUrls,\n contentType,\n abortSignal: options.abortSignal,\n });\n }\n\n return {\n // The output container travels with the operation so `doStatus` can\n // report the right media type without re-deriving it.\n operation: { requestId, outputContainer: output.container },\n warnings,\n providerMetadata: {\n topaz: {\n requestId,\n // Preliminary: Topaz estimates up front only when it gets source\n // metadata, and the completed status carries the billed value.\n ...(created.estimates?.cost != null\n ? { estimatedCredits: created.estimates.cost }\n : {}),\n },\n },\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n },\n };\n } catch (error) {\n // Canceling before processing starts refunds any reserved credits.\n if (requestId != null) {\n await this.cancelQuietly(requestId, headers);\n }\n throw error;\n }\n }\n\n async doStatus(\n options: Parameters<NonNullable<VideoModelV4['doStatus']>>[0],\n ): Promise<VideoModelV4OperationStatusResult> {\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n const { requestId, outputContainer } = options.operation as {\n requestId: string;\n outputContainer?: string;\n };\n\n const { value: status, responseHeaders } = await getFromApi({\n url: `${this.config.baseURL}/video/${requestId}/status`,\n // Built from the configured baseURL, not from response data.\n validateUrl: false,\n headers: combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n ),\n successfulResponseHandler: createJsonResponseHandler(\n topazVideoStatusResponseSchema,\n ),\n failedResponseHandler: topazFailedResponseHandler,\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const response = {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n };\n\n if (status.status === 'complete') {\n // Topaz confirmed it invoices the lower bound of `estimates.cost`, which\n // it recomputes once the source upload has been received.\n const credits = lowerBoundCredits(status.estimates?.cost);\n\n const url = status.download?.url;\n if (url == null) {\n throw new InvalidResponseDataError({\n data: status,\n message: `Topaz reported request ${requestId} complete but returned no download URL.`,\n });\n }\n\n return {\n status: 'completed',\n videos: [\n {\n type: 'url',\n url,\n mediaType:\n (outputContainer != null\n ? containerMediaTypes[outputContainer]\n : undefined) ?? 'video/mp4',\n },\n ],\n warnings: [],\n response,\n providerMetadata: {\n topaz: {\n requestId,\n ...(credits != null ? { credits } : {}),\n ...(status.estimates?.cost != null\n ? { estimatedCredits: status.estimates.cost }\n : {}),\n ...(status.outputSize != null\n ? { outputSize: status.outputSize }\n : {}),\n ...(status.download?.expiresAt != null\n ? { expiresAt: status.download.expiresAt }\n : {}),\n },\n },\n };\n }\n\n if (status.status === 'failed' || status.status === 'canceled') {\n return {\n status: 'error',\n error:\n `Topaz video request ${requestId} ${status.status}` +\n (status.errorCode != null ? ` (${status.errorCode})` : '') +\n (status.message != null ? `: ${status.message}` : '.'),\n providerMetadata: {\n topaz: {\n requestId,\n ...(status.errorCode != null\n ? { errorCode: status.errorCode }\n : {}),\n },\n },\n response,\n };\n }\n\n // Documented in-progress values are requested, accepted, initializing,\n // preprocessing, processing, postprocessing and canceling. Anything else\n // keeps polling too, so a newly added state cannot break running jobs.\n return { status: 'pending', response };\n }\n\n private addUnsupportedWarnings(\n options: Parameters<NonNullable<VideoModelV4['doStart']>>[0],\n warnings: SharedV4Warning[],\n ): void {\n // `generateVideo` requires a prompt, so an empty one is the expected way\n // to call an enhancement model and does not warrant a warning.\n if (options.prompt != null && options.prompt.trim() !== '') {\n warnings.push({\n type: 'unsupported',\n feature: 'prompt',\n details:\n 'Topaz video models enhance an existing video and do not take a text prompt. ' +\n 'The prompt was ignored.',\n });\n }\n\n if (options.aspectRatio != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'aspectRatio',\n details:\n 'Topaz video models do not support aspectRatio. Use `resolution`, or the ' +\n '`output` provider option, to set the output dimensions.',\n });\n }\n\n if (options.seed != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'seed',\n details: 'Topaz video models do not support seed.',\n });\n }\n\n if (options.duration != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'duration',\n details:\n 'Topaz video models enhance the whole input video, so duration was ignored. ' +\n 'Pass the input duration via the `source.duration` provider option instead.',\n });\n }\n\n if (options.generateAudio != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'generateAudio',\n details:\n 'Topaz video models do not generate audio. Use the `output.audioTransfer` ' +\n 'provider option to control how the input audio track is carried over.',\n });\n }\n\n if (options.frameImages != null && options.frameImages.length > 0) {\n warnings.push({\n type: 'unsupported',\n feature: 'frameImages',\n details:\n 'Topaz video models do not support first/last frame generation. The frame ' +\n 'images were ignored.',\n });\n }\n\n if (options.n > 1) {\n warnings.push({\n type: 'unsupported',\n feature: 'n',\n details:\n 'Topaz video models enhance one video per call. Only 1 video will be produced.',\n });\n }\n }\n\n private selectInputVideo(\n options: Parameters<NonNullable<VideoModelV4['doStart']>>[0],\n warnings: SharedV4Warning[],\n ): VideoModelV4File {\n const references = options.inputReferences ?? [];\n const videos = references.filter(isVideoReference);\n\n if (videos.length === 0) {\n if (options.image != null) {\n throw new InvalidArgumentError({\n argument: 'image',\n message:\n 'Topaz video models enhance an existing video, not a still image. Pass the ' +\n 'input video via `inputReferences`.',\n });\n }\n\n throw new InvalidArgumentError({\n argument: 'inputReferences',\n message:\n 'Topaz video models require an input video. Pass it via `inputReferences`, ' +\n 'e.g. `inputReferences: [{ type: \"file\", mediaType: \"video/mp4\", data: bytes }]`. ' +\n 'For URL references, include `mediaType` so the reference is recognized as a video.',\n });\n }\n\n if (references.length > 1) {\n warnings.push({\n type: 'unsupported',\n feature: 'inputReferences',\n details:\n 'Topaz video models enhance a single video. Only the first video reference was used.',\n });\n }\n\n return videos[0];\n }\n\n private async uploadVideo({\n requestId,\n bytes,\n urls,\n contentType,\n abortSignal,\n }: {\n requestId: string;\n bytes: Uint8Array;\n urls: string[] | null | undefined;\n contentType: string;\n abortSignal: AbortSignal | undefined;\n }): Promise<void> {\n const url = urls?.[0];\n if (url == null) {\n throw new InvalidResponseDataError({\n data: urls,\n message: `Topaz returned no upload URL for request ${requestId}.`,\n });\n }\n\n // The upload URL comes from the Topaz response body. `getFromApi` cannot\n // be used for a PUT, so the same trust decision is made explicitly here:\n // validate unless the URL points back at the configured base URL, and\n // never attach the API key (presigned URLs carry their own credentials).\n if (!isSameOrigin(url, this.config.baseURL)) {\n validateDownloadUrl(url);\n }\n\n const fetchImpl = this.config.fetch ?? globalThis.fetch;\n const response = await fetchImpl(url, {\n method: 'PUT',\n headers: withUserAgentSuffix(\n { 'Content-Type': contentType },\n `ai-sdk-topaz/${VERSION}`,\n ) as HeadersInit,\n body: bytes as BodyInit,\n signal: abortSignal,\n });\n\n if (!response.ok) {\n throw new APICallError({\n message: `Uploading the input video failed with status ${response.status}.`,\n url,\n requestBodyValues: {},\n statusCode: response.status,\n responseHeaders: Object.fromEntries(response.headers.entries()),\n responseBody: await response.text(),\n });\n }\n }\n\n private async cancelQuietly(\n requestId: string,\n headers: Record<string, string | undefined>,\n ): Promise<void> {\n const fetchImpl = this.config.fetch ?? globalThis.fetch;\n\n try {\n // Deliberately not tied to the caller's abort signal, which may be the\n // reason the start failed.\n await fetchImpl(`${this.config.baseURL}/video/${requestId}`, {\n method: 'DELETE',\n headers: removeUndefinedEntries(headers),\n });\n } catch {\n // Best effort: the original error is more useful to the caller.\n }\n }\n}\n\nfunction lowerBoundCredits(\n cost: number[] | null | undefined,\n): number | undefined {\n return cost != null && cost.length > 0 ? Math.min(...cost) : undefined;\n}\n\nfunction fileBytes(\n input: Extract<VideoModelV4File, { type: 'file' }>,\n): Uint8Array {\n return typeof input.data === 'string'\n ? convertBase64ToUint8Array(input.data)\n : input.data;\n}\n\nfunction resolveContainer(\n input: VideoModelV4File,\n declaredContainer: TopazSourceContainer | undefined,\n): TopazSourceContainer {\n if (declaredContainer != null) {\n return declaredContainer;\n }\n\n if (input.type === 'file') {\n const container = mediaTypeContainers[input.mediaType.toLowerCase()];\n\n if (container == null) {\n throw new InvalidArgumentError({\n argument: 'inputReferences',\n message:\n `Could not map the media type \"${input.mediaType}\" onto a Topaz container. ` +\n 'Set the `source.container` provider option explicitly.',\n });\n }\n\n return container;\n }\n\n const container =\n (input.mediaType != null\n ? mediaTypeContainers[input.mediaType.toLowerCase()]\n : undefined) ?? containerFromUrl(input.url);\n\n if (container == null) {\n throw new InvalidArgumentError({\n argument: 'inputReferences',\n message:\n `Could not determine the container of the input video at \"${input.url}\". Set ` +\n 'the `source.container` provider option, or pass `mediaType` on the reference.',\n });\n }\n\n return container;\n}\n\nfunction isVideoReference(reference: VideoModelV4File): boolean {\n if (reference.type === 'file') {\n return reference.mediaType.toLowerCase().startsWith('video/');\n }\n\n if (reference.mediaType != null) {\n return reference.mediaType.toLowerCase().startsWith('video/');\n }\n\n return containerFromUrl(reference.url) != null;\n}\n\nfunction containerFromUrl(url: string): TopazSourceContainer | undefined {\n const withoutQuery = url.split(/[?#]/)[0];\n const extension = withoutQuery.split('.').pop()?.toLowerCase();\n return extension != null ? extensionContainers[extension] : undefined;\n}\n\ntype SourceMetadata = {\n duration: number;\n frameRate: number;\n frameCount: number;\n width: number;\n height: number;\n};\n\ntype ResolvedSource = {\n container: TopazSourceContainer;\n metadata: SourceMetadata | undefined;\n};\n\n/**\n * Reads the optional source metadata, which is all or nothing. Starlight\n * models require it, and it lets Topaz estimate the cost up front. Nothing is\n * read out of the video bytes: no provider package inspects media files.\n */\nfunction resolveSource(\n topazOptions: TopazVideoModelOptions | undefined,\n container: TopazSourceContainer,\n): ResolvedSource {\n const source = topazOptions?.source;\n const { width, height, duration, frameRate } = source ?? {};\n\n if (\n width == null &&\n height == null &&\n duration == null &&\n frameRate == null &&\n source?.frameCount == null\n ) {\n return { container, metadata: undefined };\n }\n\n const frameCount =\n source?.frameCount ??\n (duration != null && frameRate != null\n ? Math.round(duration * frameRate)\n : undefined);\n\n const missing = [\n width == null ? 'source.width' : undefined,\n height == null ? 'source.height' : undefined,\n duration == null ? 'source.duration' : undefined,\n frameRate == null ? 'source.frameRate' : undefined,\n ].filter(field => field != null);\n\n if (\n width == null ||\n height == null ||\n duration == null ||\n frameRate == null ||\n frameCount == null\n ) {\n throw new InvalidArgumentError({\n argument: 'providerOptions.topaz.source',\n message: `Source metadata must be complete. Missing: ${missing.join(', ')}.`,\n });\n }\n\n return {\n container,\n metadata: { duration, frameRate, frameCount, width, height },\n };\n}\n\nfunction parseResolution(resolution: `${number}x${number}` | undefined): {\n width: number | undefined;\n height: number | undefined;\n} {\n if (resolution == null) {\n return { width: undefined, height: undefined };\n }\n\n const [width, height] = resolution.split('x').map(Number);\n return { width, height };\n}\n\nfunction buildOutput({\n options,\n topazOptions,\n source,\n}: {\n options: Parameters<NonNullable<VideoModelV4['doStart']>>[0];\n topazOptions: TopazVideoModelOptions | undefined;\n source: ResolvedSource;\n}): Record<string, unknown> & { container: TopazOutputContainer } {\n const output = topazOptions?.output;\n const resolution = parseResolution(options.resolution);\n\n const width = output?.width ?? resolution.width ?? source.metadata?.width;\n const height = output?.height ?? resolution.height ?? source.metadata?.height;\n\n if (width == null || height == null) {\n throw new InvalidArgumentError({\n argument: 'resolution',\n message:\n 'Topaz needs the output resolution. Set the `resolution` call option or the ' +\n '`output.width` / `output.height` provider options.',\n });\n }\n\n const frameRate =\n output?.frameRate ?? options.fps ?? source.metadata?.frameRate;\n const audioTransfer = output?.audioTransfer ?? 'Copy';\n\n return {\n resolution: { width, height },\n ...(frameRate != null ? { frameRate } : {}),\n audioTransfer,\n ...(audioTransfer !== 'None'\n ? { audioCodec: output?.audioCodec ?? 'AAC' }\n : output?.audioCodec != null\n ? { audioCodec: output.audioCodec }\n : {}),\n ...(output?.audioBitrate != null\n ? { audioBitrate: output.audioBitrate }\n : {}),\n ...(output?.videoEncoder != null\n ? { videoEncoder: output.videoEncoder }\n : {}),\n ...(output?.videoProfile != null\n ? { videoProfile: output.videoProfile }\n : {}),\n ...(output?.videoBitrate != null\n ? { videoBitrate: output.videoBitrate }\n : {}),\n ...(output?.dynamicCompressionLevel != null\n ? { dynamicCompressionLevel: output.dynamicCompressionLevel }\n : {}),\n ...(output?.cropToFit != null ? { cropToFit: output.cropToFit } : {}),\n container: resolveOutputContainer(output, source.container),\n };\n}\n\n/**\n * Mirrors Topaz's container rules so `doStatus` can report the media type of\n * the file Topaz will actually produce.\n */\nfunction resolveOutputContainer(\n output: TopazVideoModelOptions['output'],\n sourceContainer: TopazSourceContainer,\n): TopazOutputContainer {\n switch (output?.videoEncoder) {\n case 'ProRes':\n return 'mov';\n case 'AV1':\n case 'VP9':\n return 'mp4';\n }\n\n if (output?.container != null) {\n return output.container;\n }\n\n // The default H265 encoder only writes mp4, mov and mkv.\n return sourceContainer === 'mov' || sourceContainer === 'mkv'\n ? sourceContainer\n : 'mp4';\n}\n\nfunction requireRequestId(requestId: string | null | undefined): string {\n if (requestId == null) {\n throw new InvalidResponseDataError({\n data: requestId,\n message: 'Topaz did not return a requestId for the video request.',\n });\n }\n\n return requestId;\n}\n\nfunction buildFilter(\n modelId: string,\n topazOptions: TopazVideoModelOptions | undefined,\n): Record<string, unknown> {\n const filter: Record<string, unknown> = {\n model: resolveTopazVideoApiModelId(modelId),\n };\n\n if (topazOptions != null) {\n const nonFilterKeys = new Set<string>(TOPAZ_NON_FILTER_OPTION_KEYS);\n\n for (const [key, value] of Object.entries(topazOptions)) {\n if (!nonFilterKeys.has(key) && value !== undefined) {\n filter[key] = value;\n }\n }\n\n Object.assign(filter, topazOptions.filter ?? {});\n }\n\n return filter;\n}\n\n// `cost` (credits) and `time` (seconds) are [lowerBound, upperBound] pairs.\nconst topazVideoEstimatesSchema = z\n .object({\n cost: z.array(z.number()).nullish(),\n time: z.array(z.number()).nullish(),\n })\n .nullish();\n\nconst topazVideoExpressResponseSchema = z.object({\n requestId: z.string().nullish(),\n uploadUrls: z.array(z.string()).nullish(),\n estimates: topazVideoEstimatesSchema,\n});\n\nconst topazVideoStatusResponseSchema = z.object({\n status: z.string().nullish(),\n message: z.string().nullish(),\n errorCode: z.string().nullish(),\n // Documented as a string, accepted as a number too.\n outputSize: z.union([z.string(), z.number()]).nullish(),\n estimates: topazVideoEstimatesSchema,\n download: z\n .object({\n url: z.string().nullish(),\n expiresAt: z.union([z.string(), z.number()]).nullish(),\n })\n .nullish(),\n});\n","import {\n NoSuchModelError,\n type Experimental_VideoModelV4 as VideoModelV4,\n type ImageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { TopazImageModel } from './topaz-image-model';\nimport type { TopazImageModelId } from './topaz-image-settings';\nimport { TopazVideoModel } from './topaz-video-model';\nimport type { TopazVideoModelId } from './topaz-video-settings';\nimport { VERSION } from './version';\n\nexport interface TopazProviderSettings {\n /**\n * Topaz Labs API key. Default value is taken from the `TOPAZ_API_KEY`\n * environment variable.\n *\n * @see https://developer.topazlabs.com/getting-started/api-key-setup\n */\n apiKey?: string;\n\n /**\n * Base URL for the API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept\n * requests, or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n}\n\nexport interface TopazProvider extends ProviderV4 {\n /**\n * Creates a model for image enhancement.\n */\n image(modelId: TopazImageModelId): ImageModelV4;\n\n /**\n * Creates a model for image enhancement.\n */\n imageModel(modelId: TopazImageModelId): ImageModelV4;\n\n /**\n * Creates a model for video enhancement.\n */\n video(modelId: TopazVideoModelId): VideoModelV4;\n\n /**\n * Creates a model for video enhancement.\n */\n videoModel(modelId: TopazVideoModelId): VideoModelV4;\n}\n\nconst defaultBaseURL = 'https://api.topazlabs.com';\n\n/**\n * Create a Topaz Labs provider instance.\n */\nexport function createTopaz(\n options: TopazProviderSettings = {},\n): TopazProvider {\n const baseURL =\n withoutTrailingSlash(options.baseURL ?? defaultBaseURL) ?? defaultBaseURL;\n\n const getHeaders = () =>\n withUserAgentSuffix(\n {\n 'X-API-Key': loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: 'TOPAZ_API_KEY',\n description: 'Topaz Labs',\n }),\n accept: 'application/json',\n ...options.headers,\n },\n `ai-sdk-topaz/${VERSION}`,\n );\n\n const createImageModel = (modelId: TopazImageModelId): ImageModelV4 =>\n new TopazImageModel(modelId, {\n provider: 'topaz.image',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const createVideoModel = (modelId: TopazVideoModelId): VideoModelV4 =>\n new TopazVideoModel(modelId, {\n provider: 'topaz.video',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const noSuchModel = (\n modelId: string,\n modelType:\n | 'languageModel'\n | 'embeddingModel'\n | 'transcriptionModel'\n | 'speechModel'\n | 'rerankingModel',\n ): never => {\n throw new NoSuchModelError({ modelId, modelType });\n };\n\n const provider: TopazProvider = {\n specificationVersion: 'v4' as const,\n image: createImageModel,\n imageModel: createImageModel,\n video: createVideoModel,\n videoModel: createVideoModel,\n languageModel: (modelId: string) => noSuchModel(modelId, 'languageModel'),\n embeddingModel: (modelId: string) => noSuchModel(modelId, 'embeddingModel'),\n };\n\n return provider;\n}\n\n/**\n * Default Topaz Labs provider instance.\n */\nexport const topaz = createTopaz();\n"],"mappings":";;;;;;;;;;AASA,MAAa,uBAAuB,EAAE,OAAO;CAC3C,QAAQ,EACL,MAAM,CACL,EAAE,OAAO,GACT,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CACzD,CAAC,CAAC,CACD,QAAQ;CACX,SAAS,EAAE,OAAO,CAAC,CAAC,QAAQ;CAC5B,OAAO,EAAE,OAAO,CAAC,CAAC,QAAQ;CAC1B,WAAW,EAAE,OAAO,CAAC,CAAC,QAAQ;CAC9B,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ;AAC3E,CAAC;AAID,SAAgB,oBAAoB,MAA8B;CAChE,MAAM,UAAU,iBAAiB,IAAI;CACrC,MAAM,WACJ,KAAK,aAAa,OAAO,GAAG,QAAQ,IAAI,KAAK,UAAU,KAAK;CAG9D,MAAM,UAAU,KAAK,UAAU,CAAC,EAAA,CAC7B,KAAI,UAAS,MAAM,GAAG,CAAC,CACvB,QAAQ,QAAuB,OAAO,IAAI;CAE7C,OAAO,OAAO,SAAS,IAAI,GAAG,SAAS,IAAI,OAAO,KAAK,IAAI,MAAM;AACnE;AAEA,SAAS,iBAAiB,MAA8B;CACtD,MAAM,EAAE,WAAW;CAEnB,IAAI,OAAO,WAAW,UACpB,OAAO;CAGT,IAAI,MAAM,QAAQ,MAAM,GAAG;EACzB,MAAM,WAAW,OACd,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UACJ,qBAAqB,QAAQ,WAAW,cAAc,KAAK;CAE7D,MAAM,mBACJ,oBACE;EACE,aAAa,WAAW;GACtB,QAAQ,QAAQ;GAChB,yBAAyB;GACzB,aAAa;EACf,CAAC;EACD,QAAQ;EACR,GAAG,QAAQ;CACb,GACA,gBAAgB,SAClB;CAEF,MAAM,oBAAoB,YACxB,IAAI,gBAAgB,SAAS;EAC3B,UAAU;EACV;EACA,SAAS;EACT,OAAO,QAAQ;CACjB,CAAC;CAEH,MAAM,oBAAoB,YACxB,IAAI,gBAAgB,SAAS;EAC3B,UAAU;EACV;EACA,SAAS;EACT,OAAO,QAAQ;CACjB,CAAC;CAEH,MAAM,eACJ,SACA,cAMU;EACV,MAAM,IAAI,iBAAiB;GAAE;GAAS;EAAU,CAAC;CACnD;CAYA,OAAO;EATL,sBAAsB;EACtB,OAAO;EACP,YAAY;EACZ,OAAO;EACP,YAAY;EACZ,gBAAgB,YAAoB,YAAY,SAAS,eAAe;EACxE,iBAAiB,YAAoB,YAAY,SAAS,gBAAgB;CAG9D;AAChB;;;;AAKA,MAAa,QAAQ,YAAY"}
@@ -0,0 +1,259 @@
1
+ ---
2
+ title: Topaz Labs
3
+ description: Learn how to use the Topaz Labs provider for the AI SDK.
4
+ ---
5
+
6
+ # Topaz Labs Provider
7
+
8
+ The [Topaz Labs](https://www.topazlabs.com/) provider contains support for Topaz Labs' image and video enhancement models.
9
+
10
+ Topaz models **enhance media you supply**. They upscale, denoise, sharpen and restore an existing image or video. They do not generate media from a text prompt, so the input file is the required part of the request and a text prompt is ignored.
11
+
12
+ ## Setup
13
+
14
+ The Topaz Labs provider is available in the `@ai-sdk/topaz` module. You can install it with
15
+
16
+ <InstallPackages packages="@ai-sdk/topaz" />
17
+
18
+ ## Provider Instance
19
+
20
+ You can import the default provider instance `topaz` from `@ai-sdk/topaz`:
21
+
22
+ ```ts
23
+ import { topaz } from '@ai-sdk/topaz';
24
+ ```
25
+
26
+ If you need a customized setup, you can import `createTopaz` and create a provider instance with your settings:
27
+
28
+ ```ts
29
+ import { createTopaz } from '@ai-sdk/topaz';
30
+
31
+ const topaz = createTopaz({
32
+ apiKey: process.env.TOPAZ_API_KEY,
33
+ });
34
+ ```
35
+
36
+ You can use the following optional settings to customize the Topaz Labs provider instance:
37
+
38
+ - **apiKey** _string_
39
+
40
+ API key that is being sent as the `X-API-Key` header.
41
+ It defaults to the `TOPAZ_API_KEY` environment variable.
42
+
43
+ - **baseURL** _string_
44
+
45
+ Use a different URL prefix for API calls, e.g. to use proxy servers.
46
+ The default prefix is `https://api.topazlabs.com`.
47
+
48
+ - **headers** _Record&lt;string, string&gt;_
49
+
50
+ Custom headers to include in the requests.
51
+
52
+ - **fetch** _(input: RequestInfo, init?: RequestInit) => Promise&lt;Response&gt;_
53
+
54
+ Custom [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) implementation.
55
+
56
+ ## Image Models
57
+
58
+ You can create Topaz image models using `topaz.image()`:
59
+
60
+ ```ts
61
+ import { topaz } from '@ai-sdk/topaz';
62
+ import { generateImage } from 'ai';
63
+
64
+ const { images } = await generateImage({
65
+ model: topaz.image('wonder-3.5'),
66
+ prompt: {
67
+ images: ['https://example.com/photo.jpg'],
68
+ },
69
+ });
70
+ ```
71
+
72
+ The image to enhance (JPEG, PNG or TIFF) is passed through the prompt's `images`. The Topaz image API is asynchronous: the provider submits the job, polls until it finishes, and downloads the result, so `generateImage` resolves with the enhanced image.
73
+
74
+ ### Model Capabilities
75
+
76
+ | Model | Topaz model | Description |
77
+ | ------------ | ------------ | ---------------------------------------- |
78
+ | `wonder-3.5` | `Wonder 3.5` | Generative upscaling and detail recovery |
79
+
80
+ Passing a raw Topaz model name (for example `Wonder 3.5`) also works, and unknown ids are forwarded to the API unchanged.
81
+
82
+ ### Image Provider Options
83
+
84
+ ```ts
85
+ import { topaz, type TopazImageModelOptions } from '@ai-sdk/topaz';
86
+ import { generateImage } from 'ai';
87
+
88
+ const { images } = await generateImage({
89
+ model: topaz.image('wonder-3.5'),
90
+ prompt: {
91
+ images: ['https://example.com/photo.jpg'],
92
+ },
93
+ size: '4096x4096',
94
+ providerOptions: {
95
+ topaz: {
96
+ enhancementStrength: 'high',
97
+ grain: true,
98
+ grainDensity: 0.3,
99
+ outputFormat: 'png',
100
+ } satisfies TopazImageModelOptions,
101
+ },
102
+ });
103
+ ```
104
+
105
+ - **enhancementStrength** _'low' | 'medium' | 'high'_: how aggressively to enhance. Defaults to `high`.
106
+ - **grain** _boolean_: add grain to the output. Defaults to `false`.
107
+ - **grainDensity** _number_: grain intensity, 0 to 1. Defaults to 0.5.
108
+ - **grainModel** _'silver' | 'gaussian' | 'grey'_: grain model. Defaults to `silver`.
109
+ - **grainSize** _number_: grain particle size, 1 to 5. Defaults to 1.
110
+ - **grainStrength** _number_: grain effect strength, 0 to 1. Defaults to 0.5.
111
+ - **inputWidth** / **inputHeight** _number_: input dimensions in pixels. Topaz infers these from the upload when omitted.
112
+ - **outputWidth** / **outputHeight** _number_: output dimensions in pixels, 1 to 32000. These take precedence over the dimensions derived from `size`.
113
+ - **outputFormat** _'jpeg' | 'jpg' | 'png' | 'tiff' | 'tif'_: output format. Topaz defaults to `jpeg`.
114
+ - **cropToFill** _boolean_: crop the output to fill the requested dimensions. Defaults to `false`.
115
+ - **webhookUrl** _string_: URL to receive job-status webhooks.
116
+ - **pollIntervalMillis** _number_: status poll interval. Defaults to 2000.
117
+ - **pollTimeoutMillis** _number_: maximum time to wait for the job. Defaults to 600000. The provider cancels the Topaz job when this runs out or the call is aborted, since Topaz charges on completion.
118
+
119
+ `aspectRatio`, `seed`, `mask` and `n` greater than 1 are not supported and produce warnings.
120
+
121
+ ### Image Provider Metadata
122
+
123
+ `providerMetadata.topaz.images[]` on the result contains, for each image:
124
+
125
+ - **processId** _string_: the Topaz job id.
126
+ - **credits** _number_: the credits Topaz charged for the job.
127
+ - **width** / **height** _number_: the output dimensions.
128
+ - **format** _string_: the output format.
129
+
130
+ ## Video Models
131
+
132
+ You can create Topaz video models using `topaz.video()`:
133
+
134
+ ```ts
135
+ import { topaz } from '@ai-sdk/topaz';
136
+ import { experimental_generateVideo as generateVideo } from 'ai';
137
+
138
+ const { videos } = await generateVideo({
139
+ model: topaz.video('proteus'),
140
+ prompt: '',
141
+ inputReferences: ['https://example.com/clip.mp4'],
142
+ resolution: '3840x2160',
143
+ });
144
+ ```
145
+
146
+ The video to enhance is passed through `inputReferences`, and `resolution` sets the output resolution. Starlight models also need [source metadata](#source-metadata). `generateVideo` requires a `prompt`, so pass an empty string: Topaz ignores text, and a non-empty prompt produces a warning.
147
+
148
+ ### Model Capabilities
149
+
150
+ | Model | Topaz model | Description |
151
+ | ----------------------- | ----------- | --------------------------------------------- |
152
+ | `proteus` | `prob-4` | Detail-preserving upscaling with fine control |
153
+ | `starlight-precise-2.6` | `slp-2.6` | Generative upscaling with high fidelity |
154
+
155
+ Passing a raw Topaz filter model name (for example `slp-2.5`) also works, and unknown ids are forwarded to the API unchanged.
156
+
157
+ ### Input Video
158
+
159
+ A URL input is handed to Topaz, which fetches it itself. A file input is uploaded to Topaz. Either way processing starts once Topaz has the video, and the only required setting is the output resolution (from `resolution` or `output.width` / `output.height`).
160
+
161
+ ### Source Metadata
162
+
163
+ The `source` provider option describes the input video. The AI SDK does not inspect media files, so the values come from your side:
164
+
165
+ - **Starlight models require it.** Topaz rejects Starlight requests without it and prices them from these values, so they must describe the real video.
166
+ - **For other models it is optional.** When it is set, Topaz returns a cost estimate as soon as the request is created.
167
+
168
+ Setting any of `width`, `height`, `duration` or `frameRate` requires all four. The output resolution and frame rate default to the source values.
169
+
170
+ | Field | Where it comes from |
171
+ | ------------ | ------------------------------------------------------------------ |
172
+ | `resolution` | `source.width` and `source.height`. |
173
+ | `duration` | `source.duration`. |
174
+ | `frameRate` | `source.frameRate`. |
175
+ | `frameCount` | `source.frameCount`, or `duration * frameRate` when it is omitted. |
176
+ | `container` | `source.container`, or the input's media type or URL extension. |
177
+ | `size` | The input bytes (file inputs only). |
178
+
179
+ ```ts
180
+ const { videos } = await generateVideo({
181
+ model: topaz.video('starlight-precise-2.6'),
182
+ prompt: '',
183
+ inputReferences: ['https://example.com/clip.mp4'],
184
+ resolution: '3840x2160',
185
+ providerOptions: {
186
+ topaz: {
187
+ source: {
188
+ width: 1920,
189
+ height: 1080,
190
+ duration: 10,
191
+ frameRate: 30,
192
+ frameCount: 300,
193
+ },
194
+ },
195
+ },
196
+ });
197
+ ```
198
+
199
+ <Note>
200
+ Set `source.frameCount` explicitly for variable-frame-rate input, where
201
+ `duration * frameRate` is not exact.
202
+ </Note>
203
+
204
+ ### Video Provider Options
205
+
206
+ Structural options:
207
+
208
+ - **source** _object_: input video metadata, `width`, `height`, `duration`, `frameRate`, `frameCount` and `container`. See [Source Metadata](#source-metadata).
209
+ - **output** _object_: output settings.
210
+ - `width` / `height`: output dimensions. These take precedence over `resolution`.
211
+ - `frameRate`: output frame rate, taking precedence over `fps`. Topaz only changes the frame rate when a frame-interpolation filter is present.
212
+ - `audioTransfer` (`'Copy' | 'Convert' | 'None'`, default `Copy`), `audioCodec` (`'AAC' | 'AC3' | 'PCM'`, default `AAC`), `audioBitrate`.
213
+ - `videoEncoder` (`'AV1' | 'H264' | 'H265' | 'ProRes' | 'VP9'`, Topaz defaults to `H265`), `videoProfile`, `videoBitrate`, `dynamicCompressionLevel` (`'Low' | 'Mid' | 'High'`).
214
+ - `container` (`'mp4' | 'mov' | 'mkv' | 'avi' | 'webm'`): defaults to the input container when it is `mov` or `mkv`, otherwise `mp4`. `ProRes` always produces `mov`, `AV1` and `VP9` always produce `mp4`.
215
+ - `cropToFit`: center-crop to the output dimensions.
216
+ - **additionalFilters** _Array&lt;Record&lt;string, unknown&gt;&gt;_: extra `filters[]` entries, e.g. a frame-interpolation filter. Each entry must include a `model` key.
217
+ - **filter** _Record&lt;string, unknown&gt;_: escape hatch merged into the model's filter entry, overriding the typed options below.
218
+
219
+ Proteus filter settings: `videoType`, `auto`, `fieldOrder`, `focusFixLevel`, `compression`, `details`, `prenoise`, `noise`, `halo`, `preblur`, `blur`, `grain`, `grainSigma`, `grainSize`, `grainType`, `recoverOriginalDetailValue`.
220
+
221
+ Starlight Precise filter settings: `sharpness`, `videoBitDepth`, `videoCodec`, `videoProfile`, `watermark`.
222
+
223
+ See the [Proteus](https://developer.topazlabs.com/video-models/proteus/proteus-1) and [Starlight Precise 2.6](https://developer.topazlabs.com/video-models/starlight/starlight-precise-2.6) references for the accepted ranges, and [Create Video Request](https://developer.topazlabs.com/reference/video/create-request/create-video-request) for the accepted encoder and profile combinations.
224
+
225
+ A non-empty `prompt`, `aspectRatio`, `seed`, `duration`, `generateAudio`, `frameImages` and `n` greater than 1 are not supported and produce warnings.
226
+
227
+ ### Long-Running Operations
228
+
229
+ Video enhancement takes minutes, so Topaz video models implement the AI SDK's async operation protocol. `generateVideo` polls to completion, and long clips can exceed its default 10 minute timeout, so raise `poll.timeoutMs` when needed. Use `experimental_startVideo` when you would rather persist the operation and check its status later:
230
+
231
+ ```ts
232
+ import { topaz } from '@ai-sdk/topaz';
233
+ import { experimental_startVideo as startVideo } from 'ai';
234
+
235
+ const operation = await startVideo({
236
+ model: topaz.video('proteus'),
237
+ prompt: '',
238
+ inputReferences: ['https://example.com/clip.mp4'],
239
+ resolution: '3840x2160',
240
+ });
241
+ ```
242
+
243
+ If the upload fails after the request is created, the provider cancels the Topaz request so any reserved credits are refunded.
244
+
245
+ ### Video Provider Metadata
246
+
247
+ Topaz estimates the cost of a video request in credits as a `[lowerBound, upperBound]` range and bills the lower bound.
248
+
249
+ The start result's `providerMetadata.topaz` contains the `requestId` and, when Topaz could estimate the cost at request time, `estimatedCredits`. Topaz can do that when source metadata is set. It is informational only: the completed status carries the billed value.
250
+
251
+ The completed status's `providerMetadata.topaz` contains:
252
+
253
+ - **requestId** _string_: the Topaz request id.
254
+ - **credits** _number_: the credits Topaz bills for the request (the lower bound of its final estimate).
255
+ - **estimatedCredits** _[number, number]_: the final cost range.
256
+ - **outputSize** _string_: the size of the enhanced video.
257
+ - **expiresAt** _number_: when the download URL expires, in milliseconds since the Unix epoch.
258
+
259
+ A failed request reports Topaz's `errorCode` (for example `CREDIT_DIFFERENCE` when Topaz's estimate after reading the video diverged from the first one, in which case it refunds the credits) in both the error message and `providerMetadata.topaz.errorCode`.
package/package.json CHANGED
@@ -1,22 +1,76 @@
1
1
  {
2
2
  "name": "@ai-sdk/topaz",
3
- "version": "0.0.0",
4
- "description": "Seed for @ai-sdk/topaz, provisioned by the npm provisioning control plane.",
3
+ "version": "3.0.0",
5
4
  "type": "module",
6
- "main": "./index.js",
7
- "exports": {
8
- ".": "./index.js"
9
- },
5
+ "license": "Apache-2.0",
6
+ "sideEffects": false,
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
10
9
  "files": [
11
- "index.js",
10
+ "dist/**/*",
11
+ "docs/**/*",
12
+ "src",
13
+ "!src/**/*.test.ts",
14
+ "!src/**/*.test-d.ts",
15
+ "!src/**/__snapshots__",
16
+ "!src/**/__fixtures__",
17
+ "CHANGELOG.md",
12
18
  "README.md"
13
19
  ],
20
+ "directories": {
21
+ "doc": "./docs"
22
+ },
23
+ "exports": {
24
+ "./package.json": "./package.json",
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "dependencies": {
32
+ "@ai-sdk/provider": "4.0.21",
33
+ "@ai-sdk/provider-utils": "5.0.53"
34
+ },
35
+ "devDependencies": {
36
+ "@ai-sdk/test-server": "2.0.3",
37
+ "@types/node": "22.19.19",
38
+ "@vercel/ai-tsconfig": "0.0.0",
39
+ "tsdown": "^0.23.0",
40
+ "typescript": "5.8.3",
41
+ "zod": "3.25.76"
42
+ },
43
+ "peerDependencies": {
44
+ "zod": "^3.25.76 || ^4.1.8"
45
+ },
46
+ "engines": {
47
+ "node": ">=22"
48
+ },
14
49
  "publishConfig": {
15
50
  "access": "public",
16
- "registry": "https://registry.npmjs.org/"
51
+ "provenance": true
17
52
  },
53
+ "homepage": "https://ai-sdk.dev/docs",
18
54
  "repository": {
19
55
  "type": "git",
20
- "url": "https://github.com/vercel/ai.git"
56
+ "url": "https://github.com/vercel/ai",
57
+ "directory": "packages/topaz"
58
+ },
59
+ "bugs": {
60
+ "url": "https://github.com/vercel/ai/issues"
61
+ },
62
+ "keywords": [
63
+ "ai"
64
+ ],
65
+ "scripts": {
66
+ "build": "pnpm clean && tsdown",
67
+ "build:watch": "pnpm clean && tsdown --watch",
68
+ "clean": "del-cli docs *.tsbuildinfo",
69
+ "type-check": "tsc --build",
70
+ "test": "pnpm test:node && pnpm test:edge",
71
+ "test:update": "pnpm test:node -u",
72
+ "test:watch": "vitest --config vitest.node.config.js",
73
+ "test:edge": "vitest --config vitest.edge.config.js --run",
74
+ "test:node": "vitest --config vitest.node.config.js --run"
21
75
  }
22
- }
76
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ export { createTopaz, topaz } from './topaz-provider';
2
+ export type { TopazProvider, TopazProviderSettings } from './topaz-provider';
3
+ export type { TopazImageModelId } from './topaz-image-settings';
4
+ export type { TopazVideoModelId } from './topaz-video-settings';
5
+ export type { TopazImageModelOptions } from './topaz-image-model-options';
6
+ export type {
7
+ TopazVideoModelOptions,
8
+ TopazVideoOutput,
9
+ TopazVideoSource,
10
+ } from './topaz-video-model-options';
11
+ export { VERSION } from './version';
@@ -0,0 +1,11 @@
1
+ import type { FetchFunction, Resolvable } from '@ai-sdk/provider-utils';
2
+
3
+ export type TopazConfig = {
4
+ provider: string;
5
+ baseURL: string;
6
+ headers?: Resolvable<Record<string, string | undefined>>;
7
+ fetch?: FetchFunction;
8
+ _internal?: {
9
+ currentDate?: () => Date;
10
+ };
11
+ };
@@ -0,0 +1,61 @@
1
+ import { createJsonErrorResponseHandler } from '@ai-sdk/provider-utils';
2
+ import { z } from 'zod/v4';
3
+
4
+ /**
5
+ * The image API reports errors as `{ "message": ... }` and the video API as
6
+ * `{ "message": ..., "errorCode": ... }`. `detail` (a message or FastAPI's
7
+ * array of validation issues) and `error` are accepted as well because a few
8
+ * endpoints use them instead.
9
+ */
10
+ export const topazErrorDataSchema = z.object({
11
+ detail: z
12
+ .union([
13
+ z.string(),
14
+ z.array(z.object({ msg: z.string().nullish() }).loose()),
15
+ ])
16
+ .nullish(),
17
+ message: z.string().nullish(),
18
+ error: z.string().nullish(),
19
+ errorCode: z.string().nullish(),
20
+ errors: z.array(z.object({ msg: z.string().nullish() }).loose()).nullish(),
21
+ });
22
+
23
+ export type TopazErrorData = z.infer<typeof topazErrorDataSchema>;
24
+
25
+ export function topazErrorToMessage(data: TopazErrorData): string {
26
+ const message = baseErrorMessage(data);
27
+ const withCode =
28
+ data.errorCode != null ? `${message} (${data.errorCode})` : message;
29
+
30
+ // The video API lists field validation failures separately.
31
+ const issues = (data.errors ?? [])
32
+ .map(issue => issue.msg)
33
+ .filter((msg): msg is string => msg != null);
34
+
35
+ return issues.length > 0 ? `${withCode}: ${issues.join('; ')}` : withCode;
36
+ }
37
+
38
+ function baseErrorMessage(data: TopazErrorData): string {
39
+ const { detail } = data;
40
+
41
+ if (typeof detail === 'string') {
42
+ return detail;
43
+ }
44
+
45
+ if (Array.isArray(detail)) {
46
+ const messages = detail
47
+ .map(issue => issue.msg)
48
+ .filter((msg): msg is string => msg != null);
49
+
50
+ if (messages.length > 0) {
51
+ return messages.join('; ');
52
+ }
53
+ }
54
+
55
+ return data.message ?? data.error ?? 'Unknown Topaz API error';
56
+ }
57
+
58
+ export const topazFailedResponseHandler = createJsonErrorResponseHandler({
59
+ errorSchema: topazErrorDataSchema,
60
+ errorToMessage: topazErrorToMessage,
61
+ });