@tanstack/ai 0.31.0 → 0.32.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.
- package/dist/esm/activities/generateImage/adapter.d.ts +8 -4
- package/dist/esm/activities/generateImage/adapter.js.map +1 -1
- package/dist/esm/activities/generateImage/index.d.ts +19 -3
- package/dist/esm/activities/generateImage/index.js +12 -1
- package/dist/esm/activities/generateImage/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/adapter.d.ts +65 -6
- package/dist/esm/activities/generateVideo/adapter.js +14 -0
- package/dist/esm/activities/generateVideo/adapter.js.map +1 -1
- package/dist/esm/activities/generateVideo/index.d.ts +31 -5
- package/dist/esm/activities/generateVideo/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/snap.d.ts +14 -0
- package/dist/esm/activities/generateVideo/snap.js +54 -0
- package/dist/esm/activities/generateVideo/snap.js.map +1 -0
- package/dist/esm/activities/index.d.ts +3 -2
- package/dist/esm/activities/index.js +2 -0
- package/dist/esm/activities/index.js.map +1 -1
- package/dist/esm/client.d.ts +1 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/types.d.ts +96 -7
- package/dist/esm/utilities/media-prompt.d.ts +35 -0
- package/dist/esm/utilities/media-prompt.js +43 -0
- package/dist/esm/utilities/media-prompt.js.map +1 -0
- package/package.json +2 -2
- package/skills/ai-core/media-generation/SKILL.md +173 -3
- package/src/activities/generateImage/adapter.ts +16 -3
- package/src/activities/generateImage/index.ts +48 -4
- package/src/activities/generateVideo/adapter.ts +80 -4
- package/src/activities/generateVideo/index.ts +53 -4
- package/src/activities/generateVideo/snap.ts +100 -0
- package/src/activities/index.ts +4 -0
- package/src/client.ts +4 -0
- package/src/index.ts +4 -0
- package/src/types.ts +119 -6
- package/src/utilities/media-prompt.ts +86 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ImageGenerationOptions, ImageGenerationResult } from '../../types.js';
|
|
1
|
+
import { ImageGenerationOptions, ImageGenerationResult, ModelInputModalitiesByName } from '../../types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Resolve the size type for a model from the model-size map.
|
|
4
4
|
* If the map has an index signature (i.e. no explicit keys), falls back to string.
|
|
@@ -26,8 +26,10 @@ export interface ImageAdapterConfig {
|
|
|
26
26
|
* - TProviderOptions: Base provider-specific options (already resolved)
|
|
27
27
|
* - TModelProviderOptionsByName: Map from model name to its specific provider options
|
|
28
28
|
* - TModelSizeByName: Map from model name to its supported sizes
|
|
29
|
+
* - TModelInputModalitiesByName: Map from model name to the non-text prompt
|
|
30
|
+
* modalities it accepts (constrains the `prompt` part types at compile time)
|
|
29
31
|
*/
|
|
30
|
-
export interface ImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string
|
|
32
|
+
export interface ImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>, TModelInputModalitiesByName extends ModelInputModalitiesByName = ModelInputModalitiesByName> {
|
|
31
33
|
/** Discriminator for adapter kind - used by generate() to determine API shape */
|
|
32
34
|
readonly kind: 'image';
|
|
33
35
|
/** Adapter name identifier */
|
|
@@ -41,6 +43,7 @@ export interface ImageAdapter<TModel extends string = string, TProviderOptions e
|
|
|
41
43
|
providerOptions: TProviderOptions;
|
|
42
44
|
modelProviderOptionsByName: TModelProviderOptionsByName;
|
|
43
45
|
modelSizeByName: TModelSizeByName;
|
|
46
|
+
modelInputModalitiesByName: TModelInputModalitiesByName;
|
|
44
47
|
};
|
|
45
48
|
/**
|
|
46
49
|
* Generate images from a prompt
|
|
@@ -51,14 +54,14 @@ export interface ImageAdapter<TModel extends string = string, TProviderOptions e
|
|
|
51
54
|
* An ImageAdapter with any/unknown type parameters.
|
|
52
55
|
* Useful as a constraint in generic functions and interfaces.
|
|
53
56
|
*/
|
|
54
|
-
export type AnyImageAdapter = ImageAdapter<any, any, any, any>;
|
|
57
|
+
export type AnyImageAdapter = ImageAdapter<any, any, any, any, any>;
|
|
55
58
|
/**
|
|
56
59
|
* Abstract base class for image generation adapters.
|
|
57
60
|
* Extend this class to implement an image adapter for a specific provider.
|
|
58
61
|
*
|
|
59
62
|
* Generic parameters match ImageAdapter - all pre-resolved by the provider function.
|
|
60
63
|
*/
|
|
61
|
-
export declare abstract class BaseImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string
|
|
64
|
+
export declare abstract class BaseImageAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>, TModelInputModalitiesByName extends ModelInputModalitiesByName = ModelInputModalitiesByName> implements ImageAdapter<TModel, TProviderOptions, TModelProviderOptionsByName, TModelSizeByName, TModelInputModalitiesByName> {
|
|
62
65
|
readonly kind: "image";
|
|
63
66
|
abstract readonly name: string;
|
|
64
67
|
readonly model: TModel;
|
|
@@ -66,6 +69,7 @@ export declare abstract class BaseImageAdapter<TModel extends string = string, T
|
|
|
66
69
|
providerOptions: TProviderOptions;
|
|
67
70
|
modelProviderOptionsByName: TModelProviderOptionsByName;
|
|
68
71
|
modelSizeByName: TModelSizeByName;
|
|
72
|
+
modelInputModalitiesByName: TModelInputModalitiesByName;
|
|
69
73
|
};
|
|
70
74
|
protected config: ImageAdapterConfig;
|
|
71
75
|
constructor(model: TModel, config?: ImageAdapterConfig);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","sources":["../../../../src/activities/generateImage/adapter.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"adapter.js","sources":["../../../../src/activities/generateImage/adapter.ts"],"sourcesContent":["import type {\n ImageGenerationOptions,\n ImageGenerationResult,\n ModelInputModalitiesByName,\n} from '../../types'\n\n/**\n * Resolve the size type for a model from the model-size map.\n * If the map has an index signature (i.e. no explicit keys), falls back to string.\n * If the model is an explicit key, uses its mapped size type.\n * Otherwise falls back to string.\n */\n\n/**\n * Configuration for image adapter instances\n */\nexport interface ImageAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Image adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'dall-e-3')\n * - TProviderOptions: Base provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n * - TModelInputModalitiesByName: Map from model name to the non-text prompt\n * modalities it accepts (constrains the `prompt` part types at compile time)\n */\nexport interface ImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n> {\n /** Discriminator for adapter kind - used by generate() to determine API shape */\n readonly kind: 'image'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n }\n\n /**\n * Generate images from a prompt\n */\n generateImages: (\n options: ImageGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>,\n ) => Promise<ImageGenerationResult>\n}\n\n/**\n * An ImageAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyImageAdapter = ImageAdapter<any, any, any, any, any>\n\n/**\n * Abstract base class for image generation adapters.\n * Extend this class to implement an image adapter for a specific provider.\n *\n * Generic parameters match ImageAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseImageAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n> implements ImageAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName,\n TModelInputModalitiesByName\n> {\n readonly kind = 'image' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n }\n\n protected config: ImageAdapterConfig\n\n constructor(model: TModel, config: ImageAdapterConfig = {}) {\n this.config = config\n this.model = model\n }\n\n abstract generateImages(\n options: ImageGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>,\n ): Promise<ImageGenerationResult>\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"names":[],"mappings":"AAsFO,MAAe,iBAgBpB;AAAA,EACS,OAAO;AAAA,EAEP;AAAA,EAUC;AAAA,EAEV,YAAY,OAAe,SAA6B,IAAI;AAC1D,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,EACf;AAAA,EAMU,aAAqB;AAC7B,WAAO,GAAG,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,UAAU,CAAC,CAAC;AAAA,EAC9E;AACF;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DebugOption } from '../../logger/types.js';
|
|
2
2
|
import { ImageAdapter } from './adapter.js';
|
|
3
|
-
import { ImageGenerationResult, StreamChunk } from '../../types.js';
|
|
3
|
+
import { ImageGenerationResult, MediaPrompt, MediaPromptFor, StreamChunk } from '../../types.js';
|
|
4
4
|
/** The adapter kind this activity handles */
|
|
5
5
|
export declare const kind: "image";
|
|
6
6
|
/**
|
|
@@ -14,6 +14,14 @@ export type ImageProviderOptionsForModel<TAdapter, TModel extends string> = TAda
|
|
|
14
14
|
* If the model has specific sizes defined, use those; otherwise fall back to string.
|
|
15
15
|
*/
|
|
16
16
|
export type ImageSizeForModel<TAdapter, TModel extends string> = TAdapter extends ImageAdapter<any, any, any, infer SizeByName> ? string extends keyof SizeByName ? string : TModel extends keyof SizeByName ? SizeByName[TModel] : string : string;
|
|
17
|
+
/**
|
|
18
|
+
* Extract the prompt type a model accepts from an ImageAdapter via ~types.
|
|
19
|
+
* Adapters declare a per-model input-modality map; models in the map get a
|
|
20
|
+
* `prompt` narrowed to text + their supported part types (text-only models
|
|
21
|
+
* accept `string | Array<TextPart>`), so unsupported media parts fail at
|
|
22
|
+
* compile time. Adapters without a map fall back to the full MediaPrompt.
|
|
23
|
+
*/
|
|
24
|
+
export type ImagePromptForModel<TAdapter, TModel extends string> = TAdapter extends ImageAdapter<any, any, any, any, infer ModsByName> ? string extends keyof ModsByName ? MediaPrompt : TModel extends keyof ModsByName ? MediaPromptFor<ModsByName[TModel][number]> : MediaPrompt : MediaPrompt;
|
|
17
25
|
/**
|
|
18
26
|
* Options for the image activity.
|
|
19
27
|
* The model is extracted from the adapter's model property.
|
|
@@ -26,8 +34,16 @@ export type ImageActivityOptions<TAdapter extends ImageAdapter<string, any, any,
|
|
|
26
34
|
adapter: TAdapter & {
|
|
27
35
|
kind: typeof kind;
|
|
28
36
|
};
|
|
29
|
-
/**
|
|
30
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Description of the desired image(s). Either a plain string, or — for
|
|
39
|
+
* models that support image-conditioned generation — an ordered array of
|
|
40
|
+
* content parts interleaving text with image inputs (image-to-image,
|
|
41
|
+
* reference-guided, edit, multi-reference). Media parts may carry
|
|
42
|
+
* `metadata.role` (`'reference' | 'mask' | 'control' | 'character'`) to
|
|
43
|
+
* disambiguate intent. The accepted part types are narrowed per model via
|
|
44
|
+
* the adapter's input-modality map.
|
|
45
|
+
*/
|
|
46
|
+
prompt: ImagePromptForModel<TAdapter, TAdapter['model']>;
|
|
31
47
|
/** Number of images to generate (default: 1) */
|
|
32
48
|
numberOfImages?: number;
|
|
33
49
|
/** Image size in WIDTHxHEIGHT format (e.g., "1024x1024") */
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { aiEventClient } from "@tanstack/ai-event-client";
|
|
2
2
|
import { streamGenerationResult } from "../stream-generation-result.js";
|
|
3
3
|
import { resolveDebugOption } from "../../logger/resolve.js";
|
|
4
|
+
import { resolveMediaPrompt } from "../../utilities/media-prompt.js";
|
|
4
5
|
const kind = "image";
|
|
5
6
|
function createId(prefix) {
|
|
6
7
|
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
@@ -19,13 +20,23 @@ async function runGenerateImage(options) {
|
|
|
19
20
|
const requestId = createId("image");
|
|
20
21
|
const startTime = Date.now();
|
|
21
22
|
const logger = resolveDebugOption(options.debug);
|
|
23
|
+
const resolved = resolveMediaPrompt(rest.prompt);
|
|
22
24
|
aiEventClient.emit("image:request:started", {
|
|
23
25
|
requestId,
|
|
24
26
|
provider: adapter.name,
|
|
25
27
|
model,
|
|
26
|
-
prompt:
|
|
28
|
+
prompt: resolved.text,
|
|
27
29
|
numberOfImages: rest.numberOfImages,
|
|
28
30
|
size: rest.size,
|
|
31
|
+
...resolved.images.length > 0 && {
|
|
32
|
+
imageInputCount: resolved.images.length
|
|
33
|
+
},
|
|
34
|
+
...resolved.videos.length > 0 && {
|
|
35
|
+
videoInputCount: resolved.videos.length
|
|
36
|
+
},
|
|
37
|
+
...resolved.audios.length > 0 && {
|
|
38
|
+
audioInputCount: resolved.audios.length
|
|
39
|
+
},
|
|
29
40
|
modelOptions: rest.modelOptions,
|
|
30
41
|
timestamp: startTime
|
|
31
42
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateImage/index.ts"],"sourcesContent":["/**\n * Image Activity\n *\n * Generates images from text prompts.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { streamGenerationResult } from '../stream-generation-result.js'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { ImageAdapter } from './adapter'\nimport type { ImageGenerationResult, StreamChunk } from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'image' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract model-specific provider options from an ImageAdapter via ~types.\n * If the model has specific options defined in ModelProviderOptions (and not just via index signature),\n * use those; otherwise fall back to base provider options.\n */\nexport type ImageProviderOptionsForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any>\n ? string extends keyof ModelOptions\n ? // ModelOptions is Record<string, unknown> or has index signature - use BaseOptions\n BaseOptions\n : // ModelOptions has explicit keys - check if TModel is one of them\n TModel extends keyof ModelOptions\n ? ModelOptions[TModel]\n : BaseOptions\n : object\n\n/**\n * Extract model-specific size options from an ImageAdapter via ~types.\n * If the model has specific sizes defined, use those; otherwise fall back to string.\n */\nexport type ImageSizeForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, infer SizeByName>\n ? string extends keyof SizeByName\n ? // SizeByName has index signature - fall back to string\n string\n : // SizeByName has explicit keys - check if TModel is one of them\n TModel extends keyof SizeByName\n ? SizeByName[TModel]\n : string\n : string\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the image activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The image adapter type\n * @template TStream - Whether to stream the output\n */\nexport type ImageActivityOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = {\n /** The image adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /** Text description of the desired image(s) */\n prompt: string\n /** Number of images to generate (default: 1) */\n numberOfImages?: number\n /** Image size in WIDTHxHEIGHT format (e.g., \"1024x1024\") */\n size?: ImageSizeForModel<TAdapter, TAdapter['model']>\n /**\n * Whether to stream the image generation result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<ImageGenerationResult>.\n *\n * @default false\n */\n stream?: TStream\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n} & ({} extends ImageProviderOptionsForModel<TAdapter, TAdapter['model']>\n ? {\n /** Provider-specific options for image generation */ modelOptions?: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n }\n : {\n /** Provider-specific options for image generation */ modelOptions: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n })\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the image activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<ImageGenerationResult>\n */\nexport type ImageActivityResult<TStream extends boolean = false> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<ImageGenerationResult>\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Image activity - generates images from text prompts.\n *\n * Uses AI image generation models to create images based on natural language descriptions.\n *\n * @example Generate a single image\n * ```ts\n * import { generateImage } from '@tanstack/ai'\n * import { openaiImage } from '@tanstack/ai-openai'\n *\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A serene mountain landscape at sunset'\n * })\n *\n * console.log(result.images[0].url)\n * ```\n *\n * @example Generate multiple images\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-2'),\n * prompt: 'A cute robot mascot',\n * numberOfImages: 4,\n * size: '512x512'\n * })\n *\n * result.images.forEach((image, i) => {\n * console.log(`Image ${i + 1}: ${image.url}`)\n * })\n * ```\n *\n * @example With provider-specific options\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A professional headshot photo',\n * size: '1024x1024',\n * modelOptions: {\n * quality: 'hd',\n * style: 'natural'\n * }\n * })\n * ```\n */\nexport function generateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityResult<TStream> {\n if (options.stream) {\n return streamGenerationResult(() =>\n runGenerateImage(options),\n ) as ImageActivityResult<TStream>\n }\n\n return runGenerateImage(options) as ImageActivityResult<TStream>\n}\n\n/**\n * Internal implementation of image generation (always non-streaming).\n * Contains all devtools event emission logic.\n */\nasync function runGenerateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n>(\n options: ImageActivityOptions<TAdapter, boolean>,\n): Promise<ImageGenerationResult> {\n const { adapter, stream: _stream, debug: _debug, ...rest } = options\n const model = adapter.model\n const requestId = createId('image')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n\n aiEventClient.emit('image:request:started', {\n requestId,\n provider: adapter.name,\n model,\n prompt: rest.prompt,\n numberOfImages: rest.numberOfImages,\n size: rest.size,\n modelOptions: rest.modelOptions,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateImage provider=${adapter.name}`, {\n provider: adapter.name,\n model,\n })\n\n try {\n const result = await adapter.generateImages({ ...rest, model, logger })\n const duration = Date.now() - startTime\n\n aiEventClient.emit('image:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n // GeneratedImage is a discriminated `{ url } | { b64Json }` union, but the\n // wire shape on the devtools event is a plain optional pair. Use\n // conditional spreads so the emitted record only sets the field actually\n // present — `exactOptionalPropertyTypes` rejects `field: undefined`\n // against `field?: string` targets.\n images: result.images.map((image) => ({\n url: image.url,\n b64Json: image.b64Json,\n })),\n duration,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n\n if (result.usage) {\n aiEventClient.emit('image:usage', {\n requestId,\n model,\n usage: result.usage,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n }\n\n logger.output(`activity=generateImage count=${result.images.length}`, {\n count: result.images.length,\n })\n\n return result\n } catch (error) {\n logger.errors('generateImage activity failed', {\n error,\n source: 'generateImage',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateImage() function without executing.\n */\nexport function createImageOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n ImageAdapter,\n ImageAdapterConfig,\n AnyImageAdapter,\n} from './adapter'\nexport { BaseImageAdapter } from './adapter'\n"],"names":[],"mappings":";;;AAoBO,MAAM,OAAO;AAsGpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AAmDO,SAAS,cAId,SAC8B;AAC9B,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MAAuB,MAC5B,iBAAiB,OAAO;AAAA,IAAA;AAAA,EAE5B;AAEA,SAAO,iBAAiB,OAAO;AACjC;AAMA,eAAe,iBAGb,SACgC;AAChC,QAAM,EAAE,SAAS,QAAQ,SAAS,OAAO,QAAQ,GAAG,SAA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AAA,CACT;AACD,UAAM;AAAA,EACR;AACF;AASO,SAAS,mBAId,SACyC;AACzC,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateImage/index.ts"],"sourcesContent":["/**\n * Image Activity\n *\n * Generates images from text prompts.\n * This is a self-contained module with implementation, types, and JSDoc.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { streamGenerationResult } from '../stream-generation-result.js'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport { resolveMediaPrompt } from '../../utilities/media-prompt'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { ImageAdapter } from './adapter'\nimport type {\n ImageGenerationResult,\n MediaPrompt,\n MediaPromptFor,\n StreamChunk,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'image' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract model-specific provider options from an ImageAdapter via ~types.\n * If the model has specific options defined in ModelProviderOptions (and not just via index signature),\n * use those; otherwise fall back to base provider options.\n */\nexport type ImageProviderOptionsForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, infer BaseOptions, infer ModelOptions, any>\n ? string extends keyof ModelOptions\n ? // ModelOptions is Record<string, unknown> or has index signature - use BaseOptions\n BaseOptions\n : // ModelOptions has explicit keys - check if TModel is one of them\n TModel extends keyof ModelOptions\n ? ModelOptions[TModel]\n : BaseOptions\n : object\n\n/**\n * Extract model-specific size options from an ImageAdapter via ~types.\n * If the model has specific sizes defined, use those; otherwise fall back to string.\n */\nexport type ImageSizeForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, infer SizeByName>\n ? string extends keyof SizeByName\n ? // SizeByName has index signature - fall back to string\n string\n : // SizeByName has explicit keys - check if TModel is one of them\n TModel extends keyof SizeByName\n ? SizeByName[TModel]\n : string\n : string\n\n/**\n * Extract the prompt type a model accepts from an ImageAdapter via ~types.\n * Adapters declare a per-model input-modality map; models in the map get a\n * `prompt` narrowed to text + their supported part types (text-only models\n * accept `string | Array<TextPart>`), so unsupported media parts fail at\n * compile time. Adapters without a map fall back to the full MediaPrompt.\n */\nexport type ImagePromptForModel<TAdapter, TModel extends string> =\n TAdapter extends ImageAdapter<any, any, any, any, infer ModsByName>\n ? string extends keyof ModsByName\n ? // No explicit map - accept the full union\n MediaPrompt\n : TModel extends keyof ModsByName\n ? MediaPromptFor<ModsByName[TModel][number]>\n : MediaPrompt\n : MediaPrompt\n\n// ===========================\n// Activity Options Type\n// ===========================\n\n/**\n * Options for the image activity.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The image adapter type\n * @template TStream - Whether to stream the output\n */\nexport type ImageActivityOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = {\n /** The image adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n /**\n * Description of the desired image(s). Either a plain string, or — for\n * models that support image-conditioned generation — an ordered array of\n * content parts interleaving text with image inputs (image-to-image,\n * reference-guided, edit, multi-reference). Media parts may carry\n * `metadata.role` (`'reference' | 'mask' | 'control' | 'character'`) to\n * disambiguate intent. The accepted part types are narrowed per model via\n * the adapter's input-modality map.\n */\n prompt: ImagePromptForModel<TAdapter, TAdapter['model']>\n /** Number of images to generate (default: 1) */\n numberOfImages?: number\n /** Image size in WIDTHxHEIGHT format (e.g., \"1024x1024\") */\n size?: ImageSizeForModel<TAdapter, TAdapter['model']>\n /**\n * Whether to stream the image generation result.\n * When true, returns an AsyncIterable<StreamChunk> for streaming transport.\n * When false or not provided, returns a Promise<ImageGenerationResult>.\n *\n * @default false\n */\n stream?: TStream\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n} & ({} extends ImageProviderOptionsForModel<TAdapter, TAdapter['model']>\n ? {\n /** Provider-specific options for image generation */ modelOptions?: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n }\n : {\n /** Provider-specific options for image generation */ modelOptions: ImageProviderOptionsForModel<\n TAdapter,\n TAdapter['model']\n >\n })\n\n// ===========================\n// Activity Result Type\n// ===========================\n\n/**\n * Result type for the image activity.\n * - If stream is true: AsyncIterable<StreamChunk>\n * - Otherwise: Promise<ImageGenerationResult>\n */\nexport type ImageActivityResult<TStream extends boolean = false> =\n TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<ImageGenerationResult>\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Image activity - generates images from text prompts.\n *\n * Uses AI image generation models to create images based on natural language descriptions.\n *\n * @example Generate a single image\n * ```ts\n * import { generateImage } from '@tanstack/ai'\n * import { openaiImage } from '@tanstack/ai-openai'\n *\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A serene mountain landscape at sunset'\n * })\n *\n * console.log(result.images[0].url)\n * ```\n *\n * @example Generate multiple images\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-2'),\n * prompt: 'A cute robot mascot',\n * numberOfImages: 4,\n * size: '512x512'\n * })\n *\n * result.images.forEach((image, i) => {\n * console.log(`Image ${i + 1}: ${image.url}`)\n * })\n * ```\n *\n * @example With provider-specific options\n * ```ts\n * const result = await generateImage({\n * adapter: openaiImage('dall-e-3'),\n * prompt: 'A professional headshot photo',\n * size: '1024x1024',\n * modelOptions: {\n * quality: 'hd',\n * style: 'natural'\n * }\n * })\n * ```\n */\nexport function generateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityResult<TStream> {\n if (options.stream) {\n return streamGenerationResult(() =>\n runGenerateImage(options),\n ) as ImageActivityResult<TStream>\n }\n\n return runGenerateImage(options) as ImageActivityResult<TStream>\n}\n\n/**\n * Internal implementation of image generation (always non-streaming).\n * Contains all devtools event emission logic.\n */\nasync function runGenerateImage<\n TAdapter extends ImageAdapter<string, any, any, any>,\n>(\n options: ImageActivityOptions<TAdapter, boolean>,\n): Promise<ImageGenerationResult> {\n const { adapter, stream: _stream, debug: _debug, ...rest } = options\n const model = adapter.model\n const requestId = createId('image')\n const startTime = Date.now()\n const logger: InternalLogger = resolveDebugOption(options.debug)\n\n // Devtools events carry the flattened prompt text plus media-part counts —\n // the wire payload stays `prompt: string` regardless of the prompt shape.\n const resolved = resolveMediaPrompt(rest.prompt)\n\n aiEventClient.emit('image:request:started', {\n requestId,\n provider: adapter.name,\n model,\n prompt: resolved.text,\n numberOfImages: rest.numberOfImages,\n size: rest.size,\n ...(resolved.images.length > 0 && {\n imageInputCount: resolved.images.length,\n }),\n ...(resolved.videos.length > 0 && {\n videoInputCount: resolved.videos.length,\n }),\n ...(resolved.audios.length > 0 && {\n audioInputCount: resolved.audios.length,\n }),\n modelOptions: rest.modelOptions,\n timestamp: startTime,\n })\n\n logger.request(`activity=generateImage provider=${adapter.name}`, {\n provider: adapter.name,\n model,\n })\n\n try {\n const result = await adapter.generateImages({ ...rest, model, logger })\n const duration = Date.now() - startTime\n\n aiEventClient.emit('image:request:completed', {\n requestId,\n provider: adapter.name,\n model,\n // GeneratedImage is a discriminated `{ url } | { b64Json }` union, but the\n // wire shape on the devtools event is a plain optional pair. Use\n // conditional spreads so the emitted record only sets the field actually\n // present — `exactOptionalPropertyTypes` rejects `field: undefined`\n // against `field?: string` targets.\n images: result.images.map((image) => ({\n url: image.url,\n b64Json: image.b64Json,\n })),\n duration,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n\n if (result.usage) {\n aiEventClient.emit('image:usage', {\n requestId,\n model,\n usage: result.usage,\n modelOptions: rest.modelOptions,\n timestamp: Date.now(),\n })\n }\n\n logger.output(`activity=generateImage count=${result.images.length}`, {\n count: result.images.length,\n })\n\n return result\n } catch (error) {\n logger.errors('generateImage activity failed', {\n error,\n source: 'generateImage',\n })\n throw error\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateImage() function without executing.\n */\nexport function createImageOptions<\n TAdapter extends ImageAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: ImageActivityOptions<TAdapter, TStream>,\n): ImageActivityOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n ImageAdapter,\n ImageAdapterConfig,\n AnyImageAdapter,\n} from './adapter'\nexport { BaseImageAdapter } from './adapter'\n"],"names":[],"mappings":";;;;AA0BO,MAAM,OAAO;AA+HpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AAmDO,SAAS,cAId,SAC8B;AAC9B,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MAAuB,MAC5B,iBAAiB,OAAO;AAAA,IAAA;AAAA,EAE5B;AAEA,SAAO,iBAAiB,OAAO;AACjC;AAMA,eAAe,iBAGb,SACgC;AAChC,QAAM,EAAE,SAAS,QAAQ,SAAS,OAAO,QAAQ,GAAG,SAAS;AAC7D,QAAM,QAAQ,QAAQ;AACtB,QAAM,YAAY,SAAS,OAAO;AAClC,QAAM,YAAY,KAAK,IAAA;AACvB,QAAM,SAAyB,mBAAmB,QAAQ,KAAK;AAI/D,QAAM,WAAW,mBAAmB,KAAK,MAAM;AAE/C,gBAAc,KAAK,yBAAyB;AAAA,IAC1C;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB;AAAA,IACA,QAAQ,SAAS;AAAA,IACjB,gBAAgB,KAAK;AAAA,IACrB,MAAM,KAAK;AAAA,IACX,GAAI,SAAS,OAAO,SAAS,KAAK;AAAA,MAChC,iBAAiB,SAAS,OAAO;AAAA,IAAA;AAAA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
1
|
-
import { VideoGenerationOptions, VideoJobResult, VideoStatusResult, VideoUrlResult } from '../../types.js';
|
|
1
|
+
import { ModelInputModalitiesByName, VideoGenerationOptions, VideoJobResult, VideoStatusResult, VideoUrlResult } from '../../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Structured description of the durations a video model accepts.
|
|
4
|
+
*
|
|
5
|
+
* Tagged union so the same shape can express discrete enums (OpenAI Sora,
|
|
6
|
+
* Veo), continuous ranges, mixed shapes, and models with no duration field.
|
|
7
|
+
* Consumed by `VideoAdapter.availableDurations()`.
|
|
8
|
+
*
|
|
9
|
+
* @experimental Video generation is an experimental feature and may change.
|
|
10
|
+
*/
|
|
11
|
+
export type DurationOptions<T extends string | number | undefined> = {
|
|
12
|
+
kind: 'discrete';
|
|
13
|
+
values: ReadonlyArray<NonNullable<T>>;
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'range';
|
|
16
|
+
min: number;
|
|
17
|
+
max: number;
|
|
18
|
+
step?: number;
|
|
19
|
+
unit: 'seconds';
|
|
20
|
+
} | {
|
|
21
|
+
kind: 'mixed';
|
|
22
|
+
values: ReadonlyArray<NonNullable<T>>;
|
|
23
|
+
range?: {
|
|
24
|
+
min: number;
|
|
25
|
+
max: number;
|
|
26
|
+
step?: number;
|
|
27
|
+
};
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'none';
|
|
30
|
+
};
|
|
2
31
|
/**
|
|
3
32
|
* Configuration for video adapter instances
|
|
4
33
|
*
|
|
@@ -24,8 +53,13 @@ export interface VideoAdapterConfig {
|
|
|
24
53
|
* - TProviderOptions: Provider-specific options (already resolved)
|
|
25
54
|
* - TModelProviderOptionsByName: Map from model name to its specific provider options
|
|
26
55
|
* - TModelSizeByName: Map from model name to its supported sizes
|
|
56
|
+
* - TModelInputModalitiesByName: Map from model name to the non-text prompt
|
|
57
|
+
* modalities it accepts (constrains the `prompt` part types at compile time)
|
|
58
|
+
* - TModelDurationByName: Map from model name to its supported duration
|
|
59
|
+
* union. Defaults to `Record<string, number>` so adapters that haven't
|
|
60
|
+
* declared a map keep today's `duration?: number` typing.
|
|
27
61
|
*/
|
|
28
|
-
export interface VideoAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>> {
|
|
62
|
+
export interface VideoAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>, TModelInputModalitiesByName extends ModelInputModalitiesByName = ModelInputModalitiesByName, TModelDurationByName extends Record<string, string | number | undefined> = Record<string, number>> {
|
|
29
63
|
/** Discriminator for adapter kind - used to determine API shape */
|
|
30
64
|
readonly kind: 'video';
|
|
31
65
|
/** Adapter name identifier */
|
|
@@ -39,12 +73,14 @@ export interface VideoAdapter<TModel extends string = string, TProviderOptions e
|
|
|
39
73
|
providerOptions: TProviderOptions;
|
|
40
74
|
modelProviderOptionsByName: TModelProviderOptionsByName;
|
|
41
75
|
modelSizeByName: TModelSizeByName;
|
|
76
|
+
modelInputModalitiesByName: TModelInputModalitiesByName;
|
|
77
|
+
modelDurationByName: TModelDurationByName;
|
|
42
78
|
};
|
|
43
79
|
/**
|
|
44
80
|
* Create a new video generation job.
|
|
45
81
|
* Returns a job ID that can be used to poll for status and retrieve the video.
|
|
46
82
|
*/
|
|
47
|
-
createVideoJob: (options: VideoGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>) => Promise<VideoJobResult>;
|
|
83
|
+
createVideoJob: (options: VideoGenerationOptions<TProviderOptions, TModelSizeByName[TModel], TModelDurationByName[TModel]>) => Promise<VideoJobResult>;
|
|
48
84
|
/**
|
|
49
85
|
* Get the current status of a video generation job.
|
|
50
86
|
*/
|
|
@@ -54,12 +90,23 @@ export interface VideoAdapter<TModel extends string = string, TProviderOptions e
|
|
|
54
90
|
* Should only be called after status is 'completed'.
|
|
55
91
|
*/
|
|
56
92
|
getVideoUrl: (jobId: string) => Promise<VideoUrlResult>;
|
|
93
|
+
/**
|
|
94
|
+
* Describe the durations this adapter's model accepts. Returns a tagged
|
|
95
|
+
* union so consumers can render UI / coerce input without provider-specific
|
|
96
|
+
* knowledge.
|
|
97
|
+
*/
|
|
98
|
+
availableDurations: () => DurationOptions<TModelDurationByName[TModel]>;
|
|
99
|
+
/**
|
|
100
|
+
* Coerce a raw seconds value to the closest valid duration for this model.
|
|
101
|
+
* Returns `undefined` for models with no duration field.
|
|
102
|
+
*/
|
|
103
|
+
snapDuration: (seconds: number) => TModelDurationByName[TModel] | undefined;
|
|
57
104
|
}
|
|
58
105
|
/**
|
|
59
106
|
* A VideoAdapter with any/unknown type parameters.
|
|
60
107
|
* Useful as a constraint in generic functions and interfaces.
|
|
61
108
|
*/
|
|
62
|
-
export type AnyVideoAdapter = VideoAdapter<any, any, any, any>;
|
|
109
|
+
export type AnyVideoAdapter = VideoAdapter<any, any, any, any, any, any>;
|
|
63
110
|
/**
|
|
64
111
|
* Abstract base class for video generation adapters.
|
|
65
112
|
* Extend this class to implement a video adapter for a specific provider.
|
|
@@ -68,7 +115,7 @@ export type AnyVideoAdapter = VideoAdapter<any, any, any, any>;
|
|
|
68
115
|
*
|
|
69
116
|
* Generic parameters match VideoAdapter - all pre-resolved by the provider function.
|
|
70
117
|
*/
|
|
71
|
-
export declare abstract class BaseVideoAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>> implements VideoAdapter<TModel, TProviderOptions, TModelProviderOptionsByName, TModelSizeByName> {
|
|
118
|
+
export declare abstract class BaseVideoAdapter<TModel extends string = string, TProviderOptions extends object = Record<string, unknown>, TModelProviderOptionsByName extends Record<string, any> = Record<string, any>, TModelSizeByName extends Record<string, string | undefined> = Record<string, string>, TModelInputModalitiesByName extends ModelInputModalitiesByName = ModelInputModalitiesByName, TModelDurationByName extends Record<string, string | number | undefined> = Record<string, number>> implements VideoAdapter<TModel, TProviderOptions, TModelProviderOptionsByName, TModelSizeByName, TModelInputModalitiesByName, TModelDurationByName> {
|
|
72
119
|
readonly kind: "video";
|
|
73
120
|
abstract readonly name: string;
|
|
74
121
|
readonly model: TModel;
|
|
@@ -76,11 +123,23 @@ export declare abstract class BaseVideoAdapter<TModel extends string = string, T
|
|
|
76
123
|
providerOptions: TProviderOptions;
|
|
77
124
|
modelProviderOptionsByName: TModelProviderOptionsByName;
|
|
78
125
|
modelSizeByName: TModelSizeByName;
|
|
126
|
+
modelInputModalitiesByName: TModelInputModalitiesByName;
|
|
127
|
+
modelDurationByName: TModelDurationByName;
|
|
79
128
|
};
|
|
80
129
|
protected config: VideoAdapterConfig;
|
|
81
130
|
constructor(config: VideoAdapterConfig | undefined, model: TModel);
|
|
82
|
-
abstract createVideoJob(options: VideoGenerationOptions<TProviderOptions, TModelSizeByName[TModel]>): Promise<VideoJobResult>;
|
|
131
|
+
abstract createVideoJob(options: VideoGenerationOptions<TProviderOptions, TModelSizeByName[TModel], TModelDurationByName[TModel]>): Promise<VideoJobResult>;
|
|
83
132
|
abstract getVideoStatus(jobId: string): Promise<VideoStatusResult>;
|
|
84
133
|
abstract getVideoUrl(jobId: string): Promise<VideoUrlResult>;
|
|
134
|
+
/**
|
|
135
|
+
* Default implementation returns `{ kind: 'none' }`. Adapters that have
|
|
136
|
+
* declared their per-model duration map should override this.
|
|
137
|
+
*/
|
|
138
|
+
availableDurations(): DurationOptions<TModelDurationByName[TModel]>;
|
|
139
|
+
/**
|
|
140
|
+
* Default implementation returns `undefined`. Adapters that have declared
|
|
141
|
+
* their per-model duration map should override.
|
|
142
|
+
*/
|
|
143
|
+
snapDuration(_seconds: number): TModelDurationByName[TModel] | undefined;
|
|
85
144
|
protected generateId(): string;
|
|
86
145
|
}
|
|
@@ -6,6 +6,20 @@ class BaseVideoAdapter {
|
|
|
6
6
|
this.config = config;
|
|
7
7
|
this.model = model;
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Default implementation returns `{ kind: 'none' }`. Adapters that have
|
|
11
|
+
* declared their per-model duration map should override this.
|
|
12
|
+
*/
|
|
13
|
+
availableDurations() {
|
|
14
|
+
return { kind: "none" };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Default implementation returns `undefined`. Adapters that have declared
|
|
18
|
+
* their per-model duration map should override.
|
|
19
|
+
*/
|
|
20
|
+
snapDuration(_seconds) {
|
|
21
|
+
return void 0;
|
|
22
|
+
}
|
|
9
23
|
generateId() {
|
|
10
24
|
return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
|
|
11
25
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","sources":["../../../../src/activities/generateVideo/adapter.ts"],"sourcesContent":["import type {\n VideoGenerationOptions,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n/**\n * Configuration for video adapter instances\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Video adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'sora-2')\n * - TProviderOptions: Provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n */\nexport interface VideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n> {\n /** Discriminator for adapter kind - used to determine API shape */\n readonly kind: 'video'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n }\n\n /**\n * Create a new video generation job.\n * Returns a job ID that can be used to poll for status and retrieve the video.\n */\n createVideoJob: (\n options: VideoGenerationOptions
|
|
1
|
+
{"version":3,"file":"adapter.js","sources":["../../../../src/activities/generateVideo/adapter.ts"],"sourcesContent":["import type {\n ModelInputModalitiesByName,\n VideoGenerationOptions,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n/**\n * Structured description of the durations a video model accepts.\n *\n * Tagged union so the same shape can express discrete enums (OpenAI Sora,\n * Veo), continuous ranges, mixed shapes, and models with no duration field.\n * Consumed by `VideoAdapter.availableDurations()`.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type DurationOptions<T extends string | number | undefined> =\n | { kind: 'discrete'; values: ReadonlyArray<NonNullable<T>> }\n | { kind: 'range'; min: number; max: number; step?: number; unit: 'seconds' }\n | {\n kind: 'mixed'\n values: ReadonlyArray<NonNullable<T>>\n range?: { min: number; max: number; step?: number }\n }\n | { kind: 'none' }\n\n/**\n * Configuration for video adapter instances\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoAdapterConfig {\n apiKey?: string\n baseUrl?: string\n timeout?: number\n maxRetries?: number\n headers?: Record<string, string>\n}\n\n/**\n * Video adapter interface with pre-resolved generics.\n *\n * An adapter is created by a provider function: `provider('model')` → `adapter`\n * All type resolution happens at the provider call site, not in this interface.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * Generic parameters:\n * - TModel: The specific model name (e.g., 'sora-2')\n * - TProviderOptions: Provider-specific options (already resolved)\n * - TModelProviderOptionsByName: Map from model name to its specific provider options\n * - TModelSizeByName: Map from model name to its supported sizes\n * - TModelInputModalitiesByName: Map from model name to the non-text prompt\n * modalities it accepts (constrains the `prompt` part types at compile time)\n * - TModelDurationByName: Map from model name to its supported duration\n * union. Defaults to `Record<string, number>` so adapters that haven't\n * declared a map keep today's `duration?: number` typing.\n */\nexport interface VideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n TModelDurationByName extends Record<string, string | number | undefined> =\n Record<string, number>,\n> {\n /** Discriminator for adapter kind - used to determine API shape */\n readonly kind: 'video'\n /** Adapter name identifier */\n readonly name: string\n /** The model this adapter is configured for */\n readonly model: TModel\n\n /**\n * @internal Type-only properties for inference. Not assigned at runtime.\n */\n '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n modelDurationByName: TModelDurationByName\n }\n\n /**\n * Create a new video generation job.\n * Returns a job ID that can be used to poll for status and retrieve the video.\n */\n createVideoJob: (\n options: VideoGenerationOptions<\n TProviderOptions,\n TModelSizeByName[TModel],\n TModelDurationByName[TModel]\n >,\n ) => Promise<VideoJobResult>\n\n /**\n * Get the current status of a video generation job.\n */\n getVideoStatus: (jobId: string) => Promise<VideoStatusResult>\n\n /**\n * Get the URL to download/view the generated video.\n * Should only be called after status is 'completed'.\n */\n getVideoUrl: (jobId: string) => Promise<VideoUrlResult>\n\n /**\n * Describe the durations this adapter's model accepts. Returns a tagged\n * union so consumers can render UI / coerce input without provider-specific\n * knowledge.\n */\n availableDurations: () => DurationOptions<TModelDurationByName[TModel]>\n\n /**\n * Coerce a raw seconds value to the closest valid duration for this model.\n * Returns `undefined` for models with no duration field.\n */\n snapDuration: (seconds: number) => TModelDurationByName[TModel] | undefined\n}\n\n/**\n * A VideoAdapter with any/unknown type parameters.\n * Useful as a constraint in generic functions and interfaces.\n */\nexport type AnyVideoAdapter = VideoAdapter<any, any, any, any, any, any>\n\n/**\n * Abstract base class for video generation adapters.\n * Extend this class to implement a video adapter for a specific provider.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * Generic parameters match VideoAdapter - all pre-resolved by the provider function.\n */\nexport abstract class BaseVideoAdapter<\n TModel extends string = string,\n TProviderOptions extends object = Record<string, unknown>,\n TModelProviderOptionsByName extends Record<string, any> = Record<string, any>,\n TModelSizeByName extends Record<string, string | undefined> = Record<\n string,\n string\n >,\n TModelInputModalitiesByName extends ModelInputModalitiesByName =\n ModelInputModalitiesByName,\n TModelDurationByName extends Record<string, string | number | undefined> =\n Record<string, number>,\n> implements VideoAdapter<\n TModel,\n TProviderOptions,\n TModelProviderOptionsByName,\n TModelSizeByName,\n TModelInputModalitiesByName,\n TModelDurationByName\n> {\n readonly kind = 'video' as const\n abstract readonly name: string\n readonly model: TModel\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: TProviderOptions\n modelProviderOptionsByName: TModelProviderOptionsByName\n modelSizeByName: TModelSizeByName\n modelInputModalitiesByName: TModelInputModalitiesByName\n modelDurationByName: TModelDurationByName\n }\n\n protected config: VideoAdapterConfig\n\n constructor(config: VideoAdapterConfig = {}, model: TModel) {\n this.config = config\n this.model = model\n }\n\n abstract createVideoJob(\n options: VideoGenerationOptions<\n TProviderOptions,\n TModelSizeByName[TModel],\n TModelDurationByName[TModel]\n >,\n ): Promise<VideoJobResult>\n\n abstract getVideoStatus(jobId: string): Promise<VideoStatusResult>\n\n abstract getVideoUrl(jobId: string): Promise<VideoUrlResult>\n\n /**\n * Default implementation returns `{ kind: 'none' }`. Adapters that have\n * declared their per-model duration map should override this.\n */\n availableDurations(): DurationOptions<TModelDurationByName[TModel]> {\n return { kind: 'none' }\n }\n\n /**\n * Default implementation returns `undefined`. Adapters that have declared\n * their per-model duration map should override.\n */\n snapDuration(_seconds: number): TModelDurationByName[TModel] | undefined {\n return undefined\n }\n\n protected generateId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`\n }\n}\n"],"names":[],"mappings":"AA6IO,MAAe,iBAmBpB;AAAA,EACS,OAAO;AAAA,EAEP;AAAA,EAWC;AAAA,EAEV,YAAY,SAA6B,CAAA,GAAI,OAAe;AAC1D,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,qBAAoE;AAClE,WAAO,EAAE,MAAM,OAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAa,UAA4D;AACvE,WAAO;AAAA,EACT;AAAA,EAEU,aAAqB;AAC7B,WAAO,GAAG,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,UAAU,CAAC,CAAC;AAAA,EAC9E;AACF;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DebugOption } from '../../logger/types.js';
|
|
2
2
|
import { VideoAdapter } from './adapter.js';
|
|
3
|
-
import { StreamChunk, TokenUsage, VideoJobResult, VideoStatusResult, VideoUrlResult } from '../../types.js';
|
|
3
|
+
import { MediaPrompt, MediaPromptFor, StreamChunk, TokenUsage, VideoJobResult, VideoStatusResult, VideoUrlResult } from '../../types.js';
|
|
4
4
|
/** The adapter kind this activity handles */
|
|
5
5
|
export declare const kind: "video";
|
|
6
6
|
/**
|
|
@@ -11,6 +11,19 @@ export type VideoProviderOptions<TAdapter> = TAdapter extends VideoAdapter<any,
|
|
|
11
11
|
* Extract the size type for a VideoAdapter's model via ~types.
|
|
12
12
|
*/
|
|
13
13
|
export type VideoSizeForAdapter<TAdapter> = TAdapter extends VideoAdapter<infer TModel, any, any, infer TSizeMap> ? TModel extends keyof TSizeMap ? TSizeMap[TModel] : string : string;
|
|
14
|
+
/**
|
|
15
|
+
* Extract the prompt type a model accepts from a VideoAdapter via ~types.
|
|
16
|
+
* Mirrors `ImagePromptForModel`: models in the adapter's input-modality map
|
|
17
|
+
* get a `prompt` narrowed to text + their supported part types; adapters
|
|
18
|
+
* without a map fall back to the full MediaPrompt.
|
|
19
|
+
*/
|
|
20
|
+
export type VideoPromptForAdapter<TAdapter> = TAdapter extends VideoAdapter<infer TModel, any, any, any, infer ModsByName> ? string extends keyof ModsByName ? MediaPrompt : TModel extends keyof ModsByName ? MediaPromptFor<ModsByName[TModel][number]> : MediaPrompt : MediaPrompt;
|
|
21
|
+
/**
|
|
22
|
+
* Extract the duration type for a VideoAdapter's model via ~types.
|
|
23
|
+
* Mirrors `VideoSizeForAdapter`. Falls back to `number` for adapters that
|
|
24
|
+
* haven't declared per-model duration constraints.
|
|
25
|
+
*/
|
|
26
|
+
export type VideoDurationForAdapter<TAdapter> = TAdapter extends VideoAdapter<infer TModel, any, any, any, any, infer TDurationMap> ? TModel extends keyof TDurationMap ? TDurationMap[TModel] : number : number;
|
|
14
27
|
/**
|
|
15
28
|
* Base options shared by all video activity operations.
|
|
16
29
|
* The model is extracted from the adapter's model property.
|
|
@@ -33,12 +46,25 @@ interface VideoActivityBaseOptions<TAdapter extends VideoAdapter<string, any, an
|
|
|
33
46
|
export type VideoCreateOptions<TAdapter extends VideoAdapter<string, any, any, any>, TStream extends boolean = false> = VideoActivityBaseOptions<TAdapter> & {
|
|
34
47
|
/** Request type - create a new job (default if not specified) */
|
|
35
48
|
request?: 'create';
|
|
36
|
-
/**
|
|
37
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Description of the desired video. Either a plain string, or — for models
|
|
51
|
+
* that support image-conditioned generation — an ordered array of content
|
|
52
|
+
* parts interleaving text with image inputs. Image parts may carry
|
|
53
|
+
* `metadata.role` (`'start_frame' | 'end_frame' | 'reference' |
|
|
54
|
+
* 'character'`) to disambiguate intent; positional fallback otherwise. The
|
|
55
|
+
* accepted part types are narrowed per model via the adapter's
|
|
56
|
+
* input-modality map.
|
|
57
|
+
*/
|
|
58
|
+
prompt: VideoPromptForAdapter<TAdapter>;
|
|
38
59
|
/** Video size — format depends on the provider (e.g., "16:9", "1280x720") */
|
|
39
60
|
size?: VideoSizeForAdapter<TAdapter>;
|
|
40
|
-
/**
|
|
41
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Video duration in seconds. Adapters that declare a per-model duration
|
|
63
|
+
* map narrow this to the model's valid union (e.g. `4 | 6 | 8` for Veo 3).
|
|
64
|
+
* Pass `adapter.snapDuration(seconds)` to coerce raw seconds to a valid
|
|
65
|
+
* value.
|
|
66
|
+
*/
|
|
67
|
+
duration?: VideoDurationForAdapter<TAdapter>;
|
|
42
68
|
/**
|
|
43
69
|
* Whether to stream the video generation lifecycle.
|
|
44
70
|
* When true, returns an AsyncIterable<StreamChunk> that handles the full
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { toRunErrorPayload } from '../error-payload'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { VideoAdapter } from './adapter'\nimport type {\n StreamChunk,\n TokenUsage,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'video' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a VideoAdapter via ~types.\n */\nexport type VideoProviderOptions<TAdapter> =\n TAdapter extends VideoAdapter<any, any, any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n/**\n * Extract the size type for a VideoAdapter's model via ~types.\n */\nexport type VideoSizeForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<infer TModel, any, any, infer TSizeMap>\n ? TModel extends keyof TSizeMap\n ? TSizeMap[TModel]\n : string\n : string\n\n// ===========================\n// Activity Options Types\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n// ===========================\n\n/**\n * Base options shared by all video activity operations.\n * The model is extracted from the adapter's model property.\n */\ninterface VideoActivityBaseOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n}\n\n/**\n * Options for creating a new video generation job.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The video adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoCreateOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = VideoActivityBaseOptions<TAdapter> & {\n /** Request type - create a new job (default if not specified) */\n request?: 'create'\n /** Text description of the desired video */\n prompt: string\n /** Video size — format depends on the provider (e.g., \"16:9\", \"1280x720\") */\n size?: VideoSizeForAdapter<TAdapter>\n /** Video duration in seconds */\n duration?: number\n /**\n * Whether to stream the video generation lifecycle.\n * When true, returns an AsyncIterable<StreamChunk> that handles the full\n * job lifecycle: create job, poll for status, yield updates, and yield final result.\n * When false or not provided, returns a Promise<VideoJobResult>.\n *\n * @default false\n */\n stream?: TStream\n /** Polling interval in milliseconds (stream mode only). @default 2000 */\n pollingInterval?: number\n /** Maximum time to wait before timing out in milliseconds (stream mode only). @default 600000 */\n maxDuration?: number\n /** Custom run ID (stream mode only) */\n runId?: string\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * // Start a video generation job\n * const { jobId } = await generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park'\n * })\n *\n * console.log('Job started:', jobId)\n * ```\n *\n * @example Stream the full video generation lifecycle\n * ```ts\n * import { generateVideo, toServerSentEventsResponse } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const stream = generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park',\n * stream: true,\n * pollingInterval: 3000,\n * })\n *\n * return toServerSentEventsResponse(stream)\n * ```\n */\nexport function generateVideo<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoActivityResult<'create', TStream> {\n if (options.stream) {\n return runStreamingVideoGeneration(\n options as VideoCreateOptions<TAdapter, true>,\n ) as VideoActivityResult<'create', TStream>\n }\n\n return runCreateVideoJob(options) as VideoActivityResult<'create', TStream>\n}\n\n/**\n * Internal implementation of non-streaming video job creation.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n logger.request(`activity=generateVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const result = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n logger.output(`activity=generateVideo jobId=${result.jobId}`, {\n jobId: result.jobId,\n model: result.model,\n })\n return result\n } catch (error) {\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n throw error\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n const threadId = createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n try {\n // Create the video generation job\n const jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n } as StreamChunk\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n logger.output(\n `activity=generateVideo jobId=${jobResult.jobId} status=completed`,\n {\n jobId: jobResult.jobId,\n url: urlResult.url,\n },\n )\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: {\n jobId: jobResult.jobId,\n status: 'completed',\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: unknown) {\n const payload = toRunErrorPayload(error, 'Video generation failed')\n logger.errors('generateVideo activity failed', {\n message: payload.message,\n code: payload.code,\n source: 'generateVideo',\n })\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId,\n message: payload.message,\n code: payload.code,\n error: payload,\n timestamp: Date.now(),\n } as StreamChunk\n }\n}\n\n/**\n * Get video job status - returns the current status, progress, and URL if available.\n *\n * This function combines status checking and URL retrieval. If the job is completed,\n * it will automatically fetch and include the video URL.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Check job status\n * ```ts\n * import { getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const result = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId: 'job-123'\n * })\n *\n * console.log('Status:', result.status)\n * console.log('Progress:', result.progress)\n * if (result.url) {\n * console.log('Video URL:', result.url)\n * }\n * ```\n */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: {\n adapter: TAdapter & { kind: typeof kind }\n jobId: string\n}): Promise<{\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n error?: string\n usage?: TokenUsage\n}> {\n const { adapter, jobId } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\n\n aiEventClient.emit('video:request:started', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n timestamp: startTime,\n })\n\n // Get status first\n const statusResult = await adapter.getVideoStatus(jobId)\n\n // If completed, also get the URL\n if (statusResult.status === 'completed') {\n try {\n const urlResult = await adapter.getVideoUrl(jobId)\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n if (urlResult.usage) {\n aiEventClient.emit('video:usage', {\n requestId,\n model: adapter.model,\n usage: urlResult.usage,\n timestamp: Date.now(),\n })\n }\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to get video URL'\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: 'failed',\n progress: statusResult.progress,\n error: errorMessage,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n // Provider reported completed but result fetch failed — treat as failed\n return {\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\n }\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // Return status for non-completed jobs\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateVideo() function without executing.\n */\nexport function createVideoOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoCreateOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n VideoAdapter,\n VideoAdapterConfig,\n AnyVideoAdap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ACA,QAAQ,aAAa;AAAA,IACrB,UAAU,aAAa;AAAA,IACvB,OAAO,aAAa;AAAA,IACpB,UAAU,KAAK,IAAA,IAAQ;AAAA,IACvB,WAAW,KAAK,IAAA;AAAA,EAAI,CACrB;AAGD,SAAO;AAAA,IACL,QAAQ,aAAa;AAAA,IACrB,UAAU,aAAa;AAAA,IACvB,OAAO,aAAa;AAAA,EAAA;AAExB;AASO,SAAS,mBAId,SACuC;AACvC,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/activities/generateVideo/index.ts"],"sourcesContent":["/**\n * Video Activity (Experimental)\n *\n * Generates videos from text prompts using a jobs/polling architecture.\n * This is a self-contained module with implementation, types, and JSDoc.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\n\nimport { aiEventClient } from '@tanstack/ai-event-client'\nimport { toRunErrorPayload } from '../error-payload'\nimport { resolveDebugOption } from '../../logger/resolve'\nimport type { InternalLogger } from '../../logger/internal-logger'\nimport type { DebugOption } from '../../logger/types'\nimport type { VideoAdapter } from './adapter'\nimport type {\n MediaPrompt,\n MediaPromptFor,\n StreamChunk,\n TokenUsage,\n VideoJobResult,\n VideoStatusResult,\n VideoUrlResult,\n} from '../../types'\n\n// ===========================\n// Activity Kind\n// ===========================\n\n/** The adapter kind this activity handles */\nexport const kind = 'video' as const\n\n// ===========================\n// Type Extraction Helpers\n// ===========================\n\n/**\n * Extract provider options from a VideoAdapter via ~types.\n */\nexport type VideoProviderOptions<TAdapter> =\n TAdapter extends VideoAdapter<any, any, any, any>\n ? TAdapter['~types']['providerOptions']\n : object\n\n/**\n * Extract the size type for a VideoAdapter's model via ~types.\n */\nexport type VideoSizeForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<infer TModel, any, any, infer TSizeMap>\n ? TModel extends keyof TSizeMap\n ? TSizeMap[TModel]\n : string\n : string\n\n/**\n * Extract the prompt type a model accepts from a VideoAdapter via ~types.\n * Mirrors `ImagePromptForModel`: models in the adapter's input-modality map\n * get a `prompt` narrowed to text + their supported part types; adapters\n * without a map fall back to the full MediaPrompt.\n */\nexport type VideoPromptForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<infer TModel, any, any, any, infer ModsByName>\n ? string extends keyof ModsByName\n ? MediaPrompt\n : TModel extends keyof ModsByName\n ? MediaPromptFor<ModsByName[TModel][number]>\n : MediaPrompt\n : MediaPrompt\n\n/**\n * Extract the duration type for a VideoAdapter's model via ~types.\n * Mirrors `VideoSizeForAdapter`. Falls back to `number` for adapters that\n * haven't declared per-model duration constraints.\n */\nexport type VideoDurationForAdapter<TAdapter> =\n TAdapter extends VideoAdapter<\n infer TModel,\n any,\n any,\n any,\n any,\n infer TDurationMap\n >\n ? TModel extends keyof TDurationMap\n ? TDurationMap[TModel]\n : number\n : number\n\n// ===========================\n// Activity Options Types\n\nfunction createId(prefix: string): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`\n}\n// ===========================\n\n/**\n * Base options shared by all video activity operations.\n * The model is extracted from the adapter's model property.\n */\ninterface VideoActivityBaseOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> {\n /** The video adapter to use (must be created with a model) */\n adapter: TAdapter & { kind: typeof kind }\n}\n\n/**\n * Options for creating a new video generation job.\n * The model is extracted from the adapter's model property.\n *\n * @template TAdapter - The video adapter type\n * @template TStream - Whether to stream the output\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoCreateOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n> = VideoActivityBaseOptions<TAdapter> & {\n /** Request type - create a new job (default if not specified) */\n request?: 'create'\n /**\n * Description of the desired video. Either a plain string, or — for models\n * that support image-conditioned generation — an ordered array of content\n * parts interleaving text with image inputs. Image parts may carry\n * `metadata.role` (`'start_frame' | 'end_frame' | 'reference' |\n * 'character'`) to disambiguate intent; positional fallback otherwise. The\n * accepted part types are narrowed per model via the adapter's\n * input-modality map.\n */\n prompt: VideoPromptForAdapter<TAdapter>\n /** Video size — format depends on the provider (e.g., \"16:9\", \"1280x720\") */\n size?: VideoSizeForAdapter<TAdapter>\n /**\n * Video duration in seconds. Adapters that declare a per-model duration\n * map narrow this to the model's valid union (e.g. `4 | 6 | 8` for Veo 3).\n * Pass `adapter.snapDuration(seconds)` to coerce raw seconds to a valid\n * value.\n */\n duration?: VideoDurationForAdapter<TAdapter>\n /**\n * Whether to stream the video generation lifecycle.\n * When true, returns an AsyncIterable<StreamChunk> that handles the full\n * job lifecycle: create job, poll for status, yield updates, and yield final result.\n * When false or not provided, returns a Promise<VideoJobResult>.\n *\n * @default false\n */\n stream?: TStream\n /** Polling interval in milliseconds (stream mode only). @default 2000 */\n pollingInterval?: number\n /** Maximum time to wait before timing out in milliseconds (stream mode only). @default 600000 */\n maxDuration?: number\n /** Custom run ID (stream mode only) */\n runId?: string\n /**\n * Enable debug logging. Pass `true` to enable all categories, `false` to\n * silence everything including errors, or a `DebugConfig` object for granular\n * control and/or a custom `Logger`.\n */\n debug?: DebugOption\n} & ({} extends VideoProviderOptions<TAdapter>\n ? {\n /** Provider-specific options for video generation */ modelOptions?: VideoProviderOptions<TAdapter>\n }\n : {\n /** Provider-specific options for video generation */ modelOptions: VideoProviderOptions<TAdapter>\n })\n\n/**\n * Options for polling the status of a video generation job.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoStatusOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get job status */\n request: 'status'\n /** The job ID to check status for */\n jobId: string\n}\n\n/**\n * Options for getting the URL of a completed video.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport interface VideoUrlOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n> extends VideoActivityBaseOptions<TAdapter> {\n /** Request type - get video URL */\n request: 'url'\n /** The job ID to get URL for */\n jobId: string\n}\n\n/**\n * Union type for all video activity options.\n * Discriminated by the `request` field.\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? VideoStatusOptions<TAdapter>\n : TRequest extends 'url'\n ? VideoUrlOptions<TAdapter>\n : VideoCreateOptions<TAdapter, TStream>\n\n// ===========================\n// Activity Result Types\n// ===========================\n\n/**\n * Result type for the video activity, based on request type and streaming.\n * - If stream is true (create request): AsyncIterable<StreamChunk>\n * - Otherwise: Promise<VideoJobResult | VideoStatusResult | VideoUrlResult>\n *\n * @experimental Video generation is an experimental feature and may change.\n */\nexport type VideoActivityResult<\n TRequest extends 'create' | 'status' | 'url' = 'create',\n TStream extends boolean = false,\n> = TRequest extends 'status'\n ? Promise<VideoStatusResult>\n : TRequest extends 'url'\n ? Promise<VideoUrlResult>\n : TStream extends true\n ? AsyncIterable<StreamChunk>\n : Promise<VideoJobResult>\n\n// ===========================\n// Activity Implementation\n// ===========================\n\n/**\n * Generate video - creates a video generation job from a text prompt.\n *\n * Uses AI video generation models to create videos based on natural language descriptions.\n * Unlike image generation, video generation is asynchronous and requires polling for completion.\n *\n * When `stream: true` is passed, handles the full job lifecycle automatically:\n * create job → poll for status → stream updates → yield final result.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Create a video generation job\n * ```ts\n * import { generateVideo } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * // Start a video generation job\n * const { jobId } = await generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park'\n * })\n *\n * console.log('Job started:', jobId)\n * ```\n *\n * @example Stream the full video generation lifecycle\n * ```ts\n * import { generateVideo, toServerSentEventsResponse } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const stream = generateVideo({\n * adapter: openaiVideo('sora-2'),\n * prompt: 'A cat chasing a dog in a sunny park',\n * stream: true,\n * pollingInterval: 3000,\n * })\n *\n * return toServerSentEventsResponse(stream)\n * ```\n */\nexport function generateVideo<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoActivityResult<'create', TStream> {\n if (options.stream) {\n return runStreamingVideoGeneration(\n options as VideoCreateOptions<TAdapter, true>,\n ) as VideoActivityResult<'create', TStream>\n }\n\n return runCreateVideoJob(options) as VideoActivityResult<'create', TStream>\n}\n\n/**\n * Internal implementation of non-streaming video job creation.\n */\nasync function runCreateVideoJob<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, boolean>): Promise<VideoJobResult> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n logger.request(`activity=generateVideo provider=${providerName}`, {\n provider: providerName,\n model,\n })\n\n try {\n const result = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n logger.output(`activity=generateVideo jobId=${result.jobId}`, {\n jobId: result.jobId,\n model: result.model,\n })\n return result\n } catch (error) {\n logger.errors('generateVideo activity failed', {\n error,\n source: 'generateVideo',\n })\n throw error\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Internal streaming implementation for video generation.\n * Handles the full job lifecycle: create job → poll for status → stream updates → yield final result.\n */\nasync function* runStreamingVideoGeneration<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: VideoCreateOptions<TAdapter, true>): AsyncIterable<StreamChunk> {\n const { adapter, prompt, size, duration, modelOptions } = options\n const model = adapter.model\n const runId = options.runId ?? createId('run')\n const pollingInterval = options.pollingInterval ?? 2000\n const maxDuration = options.maxDuration ?? 600_000\n const logger: InternalLogger = resolveDebugOption(options.debug)\n const providerName =\n (adapter as { name?: string; provider?: string }).provider ??\n (adapter as { name?: string }).name ??\n 'unknown'\n\n const threadId = createId('thread')\n\n yield {\n type: 'RUN_STARTED',\n runId,\n threadId,\n timestamp: Date.now(),\n } as StreamChunk\n\n logger.request(\n `activity=generateVideo provider=${providerName} stream=true`,\n {\n provider: providerName,\n model,\n },\n )\n\n try {\n // Create the video generation job\n const jobResult = await adapter.createVideoJob({\n model,\n prompt,\n size,\n duration,\n modelOptions,\n logger,\n })\n\n yield {\n type: 'CUSTOM',\n name: 'video:job:created',\n value: { jobId: jobResult.jobId },\n timestamp: Date.now(),\n } as StreamChunk\n\n // Poll for completion\n const startTime = Date.now()\n while (Date.now() - startTime < maxDuration) {\n await sleep(pollingInterval)\n\n const statusResult = await adapter.getVideoStatus(jobResult.jobId)\n\n yield {\n type: 'CUSTOM',\n name: 'video:status',\n value: {\n jobId: jobResult.jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n if (statusResult.status === 'completed') {\n const urlResult = await adapter.getVideoUrl(jobResult.jobId)\n\n logger.output(\n `activity=generateVideo jobId=${jobResult.jobId} status=completed`,\n {\n jobId: jobResult.jobId,\n url: urlResult.url,\n },\n )\n\n yield {\n type: 'CUSTOM',\n name: 'generation:result',\n value: {\n jobId: jobResult.jobId,\n status: 'completed',\n url: urlResult.url,\n expiresAt: urlResult.expiresAt,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n },\n timestamp: Date.now(),\n } as StreamChunk\n\n yield {\n type: 'RUN_FINISHED',\n runId,\n threadId,\n finishReason: 'stop',\n timestamp: Date.now(),\n } as StreamChunk\n return\n }\n\n if (statusResult.status === 'failed') {\n throw new Error(statusResult.error || 'Video generation failed')\n }\n }\n\n throw new Error('Video generation timed out')\n } catch (error: unknown) {\n const payload = toRunErrorPayload(error, 'Video generation failed')\n logger.errors('generateVideo activity failed', {\n message: payload.message,\n code: payload.code,\n source: 'generateVideo',\n })\n yield {\n type: 'RUN_ERROR',\n runId,\n threadId,\n message: payload.message,\n code: payload.code,\n error: payload,\n timestamp: Date.now(),\n } as StreamChunk\n }\n}\n\n/**\n * Get video job status - returns the current status, progress, and URL if available.\n *\n * This function combines status checking and URL retrieval. If the job is completed,\n * it will automatically fetch and include the video URL.\n *\n * @experimental Video generation is an experimental feature and may change.\n *\n * @example Check job status\n * ```ts\n * import { getVideoJobStatus } from '@tanstack/ai'\n * import { openaiVideo } from '@tanstack/ai-openai'\n *\n * const result = await getVideoJobStatus({\n * adapter: openaiVideo('sora-2'),\n * jobId: 'job-123'\n * })\n *\n * console.log('Status:', result.status)\n * console.log('Progress:', result.progress)\n * if (result.url) {\n * console.log('Video URL:', result.url)\n * }\n * ```\n */\nexport async function getVideoJobStatus<\n TAdapter extends VideoAdapter<string, any, any, any>,\n>(options: {\n adapter: TAdapter & { kind: typeof kind }\n jobId: string\n}): Promise<{\n status: 'pending' | 'processing' | 'completed' | 'failed'\n progress?: number\n url?: string\n error?: string\n usage?: TokenUsage\n}> {\n const { adapter, jobId } = options\n const requestId = createId('video-status')\n const startTime = Date.now()\n\n aiEventClient.emit('video:request:started', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n timestamp: startTime,\n })\n\n // Get status first\n const statusResult = await adapter.getVideoStatus(jobId)\n\n // If completed, also get the URL\n if (statusResult.status === 'completed') {\n try {\n const urlResult = await adapter.getVideoUrl(jobId)\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n if (urlResult.usage) {\n aiEventClient.emit('video:usage', {\n requestId,\n model: adapter.model,\n usage: urlResult.usage,\n timestamp: Date.now(),\n })\n }\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n url: urlResult.url,\n ...(urlResult.usage ? { usage: urlResult.usage } : {}),\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Failed to get video URL'\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: 'failed',\n progress: statusResult.progress,\n error: errorMessage,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n // Provider reported completed but result fetch failed — treat as failed\n return {\n status: 'failed' as const,\n progress: statusResult.progress,\n error: errorMessage,\n }\n }\n }\n\n aiEventClient.emit('video:request:completed', {\n requestId,\n provider: adapter.name,\n model: adapter.model,\n requestType: 'status',\n jobId,\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n duration: Date.now() - startTime,\n timestamp: Date.now(),\n })\n\n // Return status for non-completed jobs\n return {\n status: statusResult.status,\n progress: statusResult.progress,\n error: statusResult.error,\n }\n}\n\n// ===========================\n// Options Factory\n// ===========================\n\n/**\n * Create typed options for the generateVideo() function without executing.\n */\nexport function createVideoOptions<\n TAdapter extends VideoAdapter<string, any, any, any>,\n TStream extends boolean = false,\n>(\n options: VideoCreateOptions<TAdapter, TStream>,\n): VideoCreateOptions<TAdapter, TStream> {\n return options\n}\n\n// Re-export adapter types\nexport type {\n VideoAdapter,\n VideoAdapterConfig,\n AnyVideoAdapter,\n} from './adapter'\nexport { BaseVideoAdapter } from './adapter'\n"],"names":[],"mappings":";;;AA8BO,MAAM,OAAO;AA6DpB,SAAS,SAAS,QAAwB;AACxC,SAAO,GAAG,MAAM,IAAI,KAAK,IAAA,CAAK,IAAI,KAAK,OAAA,EAAS,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AAC1E;AA2LO,SAAS,cAId,SACwC;AACxC,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MACL;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO,kBAAkB,OAAO;AAClC;AAKA,eAAe,kBAEb,SAAyE;AACzE,QAAM,EAAE,SAAS,QAAQ,MAAM,UAAU,iBAAiB;AAC1D,QAAM,QAAQ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,UACjB,WAAW,KAAK,IAAA;AAAA,QAAI,CACrB;AAAA,MACH;AACA,aAAO;AAAA,QACL,QAAQ,aAAa;AAAA,QACrB,UAAU,aAAa;AAAA,QACvB,KAAK,UAAU;AAAA,QACf,GAAI,UAAU,QAAQ,EAAE,OAAO,UAAU,MAAA,IAAU,CAAA;AAAA,MAAC;AAAA,IAExD,SAAS,OAAO;AACd,YAAM,eACJ,iBAAiB,QAAQ,MAAM,UAAU;AAC3C,oBAAc,KAAK,2BAA2B;AAAA,QAC5C;AAAA,QACA,UAAU,QAAQ;AAAA,QAClB,OAAO,QAAQ;AAAA,QACf,aAAa;AAAA,QACb;AAAA,QACA,QAAQ;AAAA,QACR,UAAU,aAAa;AAAA,QACvB,OAAO;AAAA,QACP,UAAU,KAAK,IAAA,IAAQ;AAAA,QACvB,WAAW,KAAK,IAAA;AAAA,MAAI,CACrB;AAED,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,UAAU,aAAa;AAAA,QACvB,OAAO;AAAA,MAAA;AAAA,IAEX;AAAA,EACF;AAEA,gBAAc,KAAK,2BAA2B;AAAA,IAC5C;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB,OAAO,QAAQ;AAAA,IACf,aAAa;AAAA,IACb;AAAA,IACA,QAAQ,aAAa;AAAA,IACrB,UAAU,aAAa;AAAA,IACvB,OAAO,aAAa;AAAA,IACpB,UAAU,KAAK,IAAA,IAAQ;AAAA,IACvB,WAAW,KAAK,IAAA;AAAA,EAAI,CACrB;AAGD,SAAO;AAAA,IACL,QAAQ,aAAa;AAAA,IACrB,UAAU,aAAa;AAAA,IACvB,OAAO,aAAa;AAAA,EAAA;AAExB;AASO,SAAS,mBAId,SACuC;AACvC,SAAO;AACT;"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { DurationOptions } from './adapter.js';
|
|
2
|
+
/**
|
|
3
|
+
* Snap a raw seconds value to the closest valid duration for a model's
|
|
4
|
+
* `DurationOptions`.
|
|
5
|
+
*
|
|
6
|
+
* - `none` → `undefined`
|
|
7
|
+
* - `discrete` → closest numeric-parseable entry; if none parse,
|
|
8
|
+
* returns `values[0]` (keyword-only models like 'auto')
|
|
9
|
+
* - `range` → clamped to [min, max] and rounded to `step` (default 1)
|
|
10
|
+
* - `mixed` → closest of (discrete numerics ∪ range values)
|
|
11
|
+
*
|
|
12
|
+
* @experimental Video generation is an experimental feature and may change.
|
|
13
|
+
*/
|
|
14
|
+
export declare function snapToDurationOption<T extends string | number | undefined>(seconds: number, options: DurationOptions<T>): T | undefined;
|