@magichourhq/ai-sdk-provider 0.3.1 → 0.4.1

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Magic Hour provider for the AI SDK
2
2
 
3
- Generate images and videos with [Magic Hour](https://magichour.ai) from the [AI SDK](https://ai-sdk.dev).
3
+ Generate and edit images, and generate videos, with [Magic Hour](https://magichour.ai) from the [AI SDK](https://ai-sdk.dev).
4
4
 
5
5
  ## Install
6
6
 
@@ -32,6 +32,15 @@ const { video } = await generateVideo({
32
32
 
33
33
  For text-to-video, pass a string prompt. An input image can be bytes, base64 or an HTTPS URL.
34
34
 
35
+ To edit images, pass them with the prompt. Up to 10 PNG, JPEG or WebP images:
36
+
37
+ ```ts
38
+ const { image: edited } = await generateImage({
39
+ model: magichour.image("flux-2-klein"),
40
+ prompt: { text: "Make the mug matte blue", images: [image.uint8Array] },
41
+ });
42
+ ```
43
+
35
44
  To configure the provider in code, use `createMagicHour`:
36
45
 
37
46
  ```ts
@@ -50,16 +59,18 @@ const magichour = createMagicHour({ apiKey: process.env.MY_KEY, timeoutMs: 300_0
50
59
 
51
60
  ## Models and options
52
61
 
62
+ Every model in the [Magic Hour API](https://docs.magichour.ai/api-reference/models) works, for example `flux-2-klein`, `nano-banana-2.1` or `gpt-image-2` for images, and `ltx-2.5`, `kling-4.0` or `veo3.1` for video. Known model IDs come from the API spec for autocomplete, and any other ID is passed through, so a new model works before the next release. Each model has its own resolutions, durations, aspect ratios and plan tiers. The API checks them and rejects a request it can't run before charging anything.
63
+
53
64
  | | Image | Video |
54
65
  | --- | --- | --- |
55
- | Models | `default`, `flux-2-klein`, `z-image-turbo`, `qwen-image-2.1` | `default`, `ltx-2.5`, `minimax-h3`, `wan-2.2` |
56
- | Resolution | `640px` (default), `1k`, `2k` | `360p`, `480p` (default), `720p`, `1080p`, `4k` |
57
- | Aspect ratio | `1:1`, `16:9`, `9:16` | `1:1`, `16:9` (default), `9:16` |
66
+ | Resolution | `640px`, `1k`, `2k`, `4k` | `360p`, `480p`, `720p`, `1080p`, `4k` |
67
+ | Aspect ratio | `1:1`, `16:9`, `9:16`; editing also takes `auto`, `4:3`, `3:2`, `4:5` and `2:3` | `1:1`, `16:9` (default), `9:16` |
58
68
 
59
- - Set the resolution with `providerOptions: { magichour: { resolution } }`, or with the AI SDK's `size` for images (640, 1024 or 2048 on the longest edge) and `resolution` for videos (360, 480, 720, 1080 or 2160 on the shortest edge).
60
- - Video `duration` is 1 to 60 seconds, 5 by default. `generateAudio` is passed through.
69
+ - Without a resolution, the API picks the model's default. Set one with `providerOptions: { magichour: { resolution } }`, or with the AI SDK's `size` for images (640, 1024 or 2048 on the longest edge) and `resolution` for videos (360, 480, 720, 1080 or 2160 on the shortest edge).
70
+ - Video `duration` is 5 seconds by default. Some models only take certain durations; Kling 2.6, for example, takes 5 or 10. `generateAudio` is passed through.
61
71
  - Image-to-video keeps the input image's shape, so it takes no aspect ratio.
62
- - Seeds, FPS, image editing and frame or reference inputs aren't supported. They throw before anything is sent.
72
+ - Editing uses Magic Hour's AI Image Editor, with any model the editor offers. Without an aspect ratio, the editor uses `auto`. Each model accepts a different number of input images.
73
+ - Seeds, FPS, masks and video frame or reference inputs aren't supported. They throw before anything is sent.
63
74
  - `default` follows Magic Hour's current recommendation, so its output and cost can change. Choose a model to keep them fixed. See [pricing](https://docs.magichour.ai/pricing).
64
75
 
65
76
  ## Credits and failures
@@ -0,0 +1,8 @@
1
+ import type { ImageModelV4 } from "@ai-sdk/provider";
2
+ import { type CreateBody, type MagicHourClient } from "@magichourhq/browser-client";
3
+ type GenerateImageModel = NonNullable<CreateBody<"ai-image-generator">["model"]>;
4
+ type EditImageModel = NonNullable<CreateBody<"ai-image-editor">["model"]>;
5
+ export type MagicHourImageModelId = GenerateImageModel | EditImageModel | (string & {});
6
+ /** Generates images, or edits them when the prompt includes input images. */
7
+ export declare function imageModel(modelId: string, client: () => MagicHourClient): ImageModelV4;
8
+ export {};
package/dist/image.js ADDED
@@ -0,0 +1,88 @@
1
+ import { MagicHourError } from "@magichourhq/browser-client";
2
+ import { extra, imageResolution, isOneOf, ratio, ratioFromSize } from "./options.js";
3
+ import { filePath, inputImage, submit } from "./requests.js";
4
+ const editAspectRatios = ["auto", "1:1", "16:9", "9:16", "4:3", "3:2", "4:5", "2:3"];
5
+ /** Generates images, or edits them when the prompt includes input images. */
6
+ export function imageModel(modelId, client) {
7
+ return {
8
+ specificationVersion: "v4",
9
+ provider: "magichour.image",
10
+ modelId,
11
+ maxImagesPerCall: 1,
12
+ // The API rejects input images for a model that can't edit, before charging anything.
13
+ supportsFileInputs: true,
14
+ supportsMaskInputs: false,
15
+ async doGenerate(options) {
16
+ const prompt = options.prompt;
17
+ if (!prompt?.trim())
18
+ throw new Error("An image prompt is required.");
19
+ if (options.n !== 1)
20
+ throw new Error("One image per request is supported.");
21
+ if (options.mask)
22
+ throw new Error("Masks are not supported.");
23
+ const files = options.files ?? [];
24
+ if (files.length > 10)
25
+ throw new Error("Image editing accepts up to 10 input images.");
26
+ if (options.seed !== undefined)
27
+ throw new Error("Magic Hour does not expose a seed parameter.");
28
+ const extras = extra(options, ["resolution"]);
29
+ const resolution = imageResolution(options.size, extras.resolution);
30
+ const sizeRatio = ratioFromSize(options.size);
31
+ if (sizeRatio && options.aspectRatio && sizeRatio !== options.aspectRatio)
32
+ throw new Error("size and aspectRatio disagree.");
33
+ const requestedRatio = options.aspectRatio ?? sizeRatio;
34
+ if (files.length && requestedRatio && !isOneOf(editAspectRatios, requestedRatio))
35
+ throw new Error(`Supported aspect ratios for editing: ${editAspectRatios.join(", ")}.`);
36
+ const inputs = files.map(inputImage);
37
+ const transport = client();
38
+ const signal = transport.signal(options.abortSignal);
39
+ let id;
40
+ let timestamp;
41
+ if (inputs.length) {
42
+ const paths = [];
43
+ for (const input of inputs)
44
+ paths.push(await filePath(transport, input, signal));
45
+ timestamp = new Date();
46
+ id = await submit("edit images", modelId, () => transport.create("ai-image-editor", {
47
+ model: modelId,
48
+ image_count: 1,
49
+ ...(resolution ? { resolution } : {}),
50
+ // Without one, the editor uses `auto`.
51
+ ...(requestedRatio
52
+ ? { aspect_ratio: requestedRatio }
53
+ : {}),
54
+ style: { prompt },
55
+ assets: { image_file_paths: paths },
56
+ }, signal, options.headers));
57
+ }
58
+ else {
59
+ const aspectRatio = ratio(requestedRatio);
60
+ timestamp = new Date();
61
+ id = await submit("generate images", modelId, () => transport.create("ai-image-generator", {
62
+ model: modelId,
63
+ image_count: 1,
64
+ ...(resolution ? { resolution } : {}),
65
+ ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}),
66
+ style: { prompt },
67
+ }, signal, options.headers));
68
+ }
69
+ const project = await transport.wait(id, "image", signal, options.headers);
70
+ try {
71
+ const images = await Promise.all(project.downloads.slice(0, 1).map((d) => transport.download(d.url, signal)));
72
+ return {
73
+ images,
74
+ warnings: [],
75
+ isRetryable: false,
76
+ response: { timestamp, modelId, headers: undefined },
77
+ // The AI SDK keeps only this list, and joins it across calls.
78
+ providerMetadata: {
79
+ magichour: { images: [{ projectId: id, creditsCharged: project.credits_charged }] },
80
+ },
81
+ };
82
+ }
83
+ catch {
84
+ throw new MagicHourError("Could not download the generated image.", id);
85
+ }
86
+ },
87
+ };
88
+ }
package/dist/index.d.ts CHANGED
@@ -1,16 +1,16 @@
1
1
  import { type ImageModelV4, type Experimental_VideoModelV4 as VideoModelV4, type ProviderV4 } from "@ai-sdk/provider";
2
2
  import { type ClientSettings } from "@magichourhq/browser-client";
3
+ import { type MagicHourImageModelId } from "./image.js";
4
+ import { type MagicHourVideoModelId } from "./video.js";
3
5
  export { MagicHourError } from "@magichourhq/browser-client";
6
+ export type { MagicHourImageModelId } from "./image.js";
7
+ export type { MagicHourVideoModelId } from "./video.js";
4
8
  export type MagicHourSettings = Omit<ClientSettings, "apiKey"> & {
5
9
  apiKey?: string;
6
10
  };
7
- declare const imageModels: readonly ["default", "flux-2-klein", "z-image-turbo", "qwen-image-2.1"];
8
- declare const videoModels: readonly ["default", "ltx-2.5", "minimax-h3", "wan-2.2"];
9
- export type MagicHourImageModelId = (typeof imageModels)[number];
10
- export type MagicHourVideoModelId = (typeof videoModels)[number];
11
11
  export interface MagicHourProvider extends Omit<ProviderV4, "imageModel"> {
12
12
  image(modelId?: MagicHourImageModelId): ImageModelV4;
13
- imageModel(modelId?: string): ImageModelV4;
13
+ imageModel(modelId?: MagicHourImageModelId): ImageModelV4;
14
14
  video(modelId?: MagicHourVideoModelId): VideoModelV4;
15
15
  videoModel(modelId?: MagicHourVideoModelId): VideoModelV4;
16
16
  }
package/dist/index.js CHANGED
@@ -1,250 +1,23 @@
1
- import { NoSuchModelError, } from "@ai-sdk/provider";
2
- import { MagicHourClient, MagicHourError, httpsURL, } from "@magichourhq/browser-client";
1
+ import { LoadAPIKeyError, NoSuchModelError, } from "@ai-sdk/provider";
2
+ import { MagicHourClient } from "@magichourhq/browser-client";
3
+ import { imageModel } from "./image.js";
4
+ import { videoModel } from "./video.js";
3
5
  export { MagicHourError } from "@magichourhq/browser-client";
4
- const imageModels = ["default", "flux-2-klein", "z-image-turbo", "qwen-image-2.1"];
5
- const videoModels = ["default", "ltx-2.5", "minimax-h3", "wan-2.2"];
6
- const aspectRatios = ["1:1", "16:9", "9:16"];
7
- const imageResolutions = ["640px", "1k", "2k"];
8
- const videoResolutions = ["360p", "480p", "720p", "1080p", "4k"];
9
- function isOneOf(values, value) {
10
- return values.includes(value);
11
- }
12
- function ratio(value) {
13
- if (value === undefined)
14
- return undefined;
15
- if (!isOneOf(aspectRatios, value))
16
- throw new Error("Supported aspect ratios: 1:1, 16:9, 9:16.");
17
- return value;
18
- }
19
- function extra(options, allowed) {
20
- const values = options.providerOptions?.magichour ?? {};
21
- for (const key of Object.keys(values))
22
- if (!allowed.includes(key))
23
- throw new Error(`Unsupported Magic Hour option: ${key}.`);
24
- return values;
25
- }
26
- function ascii(text) {
27
- return [...text].map((c) => c.charCodeAt(0));
28
- }
29
- /** Checks the file signature, so mislabeled or non-image data never reaches a paid job. */
30
- function hasSignature(bytes, extension) {
31
- function startsWith(offset, signature) {
32
- return signature.every((byte, i) => bytes[offset + i] === byte);
33
- }
34
- if (extension === "png")
35
- return startsWith(0, [0x89, ...ascii("PNG\r\n"), 0x1a, 0x0a]);
36
- if (extension === "jpg")
37
- return startsWith(0, [0xff, 0xd8, 0xff]);
38
- return startsWith(0, ascii("RIFF")) && startsWith(8, ascii("WEBP"));
39
- }
40
- /** Decodes strict base64, which `Buffer.from` would otherwise accept with characters dropped. */
41
- function base64Bytes(value) {
42
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))
43
- throw new Error("Image data must be base64.");
44
- return new Uint8Array(Buffer.from(value, "base64"));
45
- }
46
- /** Parses "WIDTHxHEIGHT" with positive whole numbers. */
47
- function dimensions(value) {
48
- const match = /^([1-9]\d*)x([1-9]\d*)$/.exec(value);
49
- if (!match)
50
- throw new Error("Dimensions must look like 1024x1024.");
51
- return [Number(match[1]), Number(match[2])];
52
- }
53
- function imageResolution(size, option) {
54
- if (option !== undefined && !isOneOf(imageResolutions, option))
55
- throw new Error("Image resolution must be 640px, 1k, or 2k.");
56
- if (!size)
57
- return option ?? "640px";
58
- if (option !== undefined)
59
- throw new Error("Use either size or providerOptions.magichour.resolution.");
60
- // Magic Hour exposes longest-edge tiers, rather than arbitrary pixel sizes.
61
- const edge = Math.max(...dimensions(size));
62
- const tier = new Map([
63
- [640, "640px"],
64
- [1024, "1k"],
65
- [2048, "2k"],
66
- ]).get(edge);
67
- if (!tier)
68
- throw new Error("Use a 640, 1024, or 2048 longest edge, or set providerOptions.magichour.resolution.");
69
- return tier;
70
- }
71
- function ratioFromSize(size) {
72
- if (!size)
73
- return undefined;
74
- const [w, h] = dimensions(size);
75
- for (const r of aspectRatios) {
76
- const [rw, rh] = r.split(":").map(Number);
77
- if (Math.abs(w / h - rw / rh) < 0.002)
78
- return r;
79
- }
80
- throw new Error("Dimensions must have a 1:1, 16:9, or 9:16 aspect ratio.");
81
- }
82
6
  export function createMagicHour(settings = {}) {
83
7
  // Resolve credentials lazily so merely importing or registering the provider needs no key.
84
- const client = () => new MagicHourClient({
85
- ...settings,
86
- apiKey: settings.apiKey ?? process.env.MAGIC_HOUR_API_KEY ?? "",
87
- });
8
+ function client() {
9
+ const apiKey = settings.apiKey ?? process.env.MAGIC_HOUR_API_KEY;
10
+ if (!apiKey?.trim())
11
+ throw new LoadAPIKeyError({
12
+ message: "Magic Hour API key is missing. Pass it with the apiKey setting or the MAGIC_HOUR_API_KEY environment variable.",
13
+ });
14
+ return new MagicHourClient({ ...settings, apiKey });
15
+ }
88
16
  function image(modelId = "default") {
89
- if (!isOneOf(imageModels, modelId))
90
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
91
- return {
92
- specificationVersion: "v4",
93
- provider: "magichour.image",
94
- modelId,
95
- maxImagesPerCall: 1,
96
- supportsFileInputs: false,
97
- supportsMaskInputs: false,
98
- async doGenerate(options) {
99
- if (!options.prompt?.trim())
100
- throw new Error("An image prompt is required.");
101
- if (options.n !== 1)
102
- throw new Error("One image per request is supported.");
103
- if (options.files?.length || options.mask)
104
- throw new Error("This provider supports image generation, not image editing.");
105
- if (options.seed !== undefined)
106
- throw new Error("Magic Hour does not expose a seed parameter.");
107
- const extras = extra(options, ["resolution"]);
108
- const resolution = imageResolution(options.size, extras.resolution);
109
- const sizeRatio = ratioFromSize(options.size);
110
- if (sizeRatio && options.aspectRatio && sizeRatio !== options.aspectRatio)
111
- throw new Error("size and aspectRatio disagree.");
112
- const aspectRatio = ratio(options.aspectRatio ?? sizeRatio);
113
- const transport = client();
114
- const signal = transport.signal(options.abortSignal);
115
- const timestamp = new Date();
116
- const id = await transport.create("ai-image-generator", {
117
- model: modelId,
118
- image_count: 1,
119
- resolution,
120
- ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}),
121
- style: { prompt: options.prompt },
122
- }, signal, options.headers);
123
- const project = await transport.wait(id, "image", signal, options.headers);
124
- try {
125
- const images = await Promise.all(project.downloads.slice(0, 1).map((d) => transport.download(d.url, signal)));
126
- return {
127
- images,
128
- warnings: [],
129
- isRetryable: false,
130
- response: { timestamp, modelId, headers: undefined },
131
- // The AI SDK keeps only this list, and joins it across calls.
132
- providerMetadata: {
133
- magichour: { images: [{ projectId: id, creditsCharged: project.credits_charged }] },
134
- },
135
- };
136
- }
137
- catch {
138
- throw new MagicHourError("Could not download the generated image.", id);
139
- }
140
- },
141
- };
17
+ return imageModel(modelId, client);
142
18
  }
143
19
  function video(modelId = "default") {
144
- if (!videoModels.includes(modelId))
145
- throw new NoSuchModelError({ modelId, modelType: "videoModel" });
146
- return {
147
- specificationVersion: "v4",
148
- provider: "magichour.video",
149
- modelId,
150
- maxVideosPerCall: 1,
151
- async doGenerate(options) {
152
- if (options.n !== 1)
153
- throw new Error("One video per request is supported.");
154
- if (!options.prompt?.trim() && !options.image)
155
- throw new Error("A prompt or input image is required.");
156
- if (options.seed !== undefined || options.fps !== undefined)
157
- throw new Error("Magic Hour does not expose seed or FPS parameters.");
158
- if (options.frameImages?.length || options.inputReferences?.length)
159
- throw new Error("Frame and reference inputs are not supported by this adapter.");
160
- const extras = extra(options, ["resolution"]);
161
- if (extras.resolution !== undefined && !isOneOf(videoResolutions, extras.resolution))
162
- throw new Error("Invalid Magic Hour video resolution.");
163
- if (options.resolution && extras.resolution !== undefined)
164
- throw new Error("Use either resolution or providerOptions.magichour.resolution.");
165
- let resolution = extras.resolution ?? "480p";
166
- const dimensionsRatio = ratioFromSize(options.resolution);
167
- if (options.resolution) {
168
- const shortEdge = Math.min(...dimensions(options.resolution));
169
- const mapped = new Map([
170
- [360, "360p"],
171
- [480, "480p"],
172
- [720, "720p"],
173
- [1080, "1080p"],
174
- [2160, "4k"],
175
- ]).get(shortEdge);
176
- if (!mapped)
177
- throw new Error("Unsupported video dimensions; use a resolution tier in providerOptions.magichour.");
178
- resolution = mapped;
179
- }
180
- if (options.image && options.aspectRatio && options.aspectRatio !== "adaptive")
181
- throw new Error("Image-to-video inherits the input image ratio; omit aspectRatio or use adaptive.");
182
- if (!options.image && options.aspectRatio === "adaptive")
183
- throw new Error("adaptive requires an input image.");
184
- const aspectRatio = options.image
185
- ? undefined
186
- : ratio(options.aspectRatio ?? dimensionsRatio);
187
- if (!options.image &&
188
- dimensionsRatio &&
189
- options.aspectRatio &&
190
- dimensionsRatio !== options.aspectRatio)
191
- throw new Error("resolution and aspectRatio disagree.");
192
- const duration = options.duration ?? 5;
193
- if (!Number.isFinite(duration) || duration < 1 || duration > 60)
194
- throw new Error("Duration must be between 1 and 60 seconds; model-specific limits also apply.");
195
- // Validate all options before uploading input or submitting a paid generation.
196
- const transport = client();
197
- const signal = transport.signal(options.abortSignal);
198
- let imagePath;
199
- if (options.image?.type === "url")
200
- imagePath = httpsURL(options.image.url);
201
- else if (options.image?.type === "file") {
202
- const extension = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" }[options.image.mediaType];
203
- if (!extension)
204
- throw new Error("Image-to-video accepts PNG, JPEG, or WebP.");
205
- const bytes = typeof options.image.data === "string"
206
- ? base64Bytes(options.image.data)
207
- : options.image.data;
208
- if (!hasSignature(bytes, extension))
209
- throw new Error(`The input image data isn't a ${extension.toUpperCase()} file.`);
210
- imagePath = await transport.uploadImage(bytes, extension, signal);
211
- }
212
- const timestamp = new Date();
213
- const shared = {
214
- model: modelId,
215
- end_seconds: duration,
216
- resolution,
217
- ...(options.generateAudio !== undefined ? { audio: options.generateAudio } : {}),
218
- };
219
- const id = imagePath
220
- ? await transport.create("image-to-video", {
221
- ...shared,
222
- ...(options.prompt ? { style: { prompt: options.prompt } } : {}),
223
- assets: { image_file_path: imagePath },
224
- }, signal, options.headers)
225
- : await transport.create("text-to-video", {
226
- ...shared,
227
- style: { prompt: options.prompt ?? "" },
228
- aspect_ratio: aspectRatio ?? "16:9",
229
- }, signal, options.headers);
230
- const project = await transport.wait(id, "video", signal, options.headers);
231
- try {
232
- const data = await transport.download(project.downloads[0].url, signal);
233
- return {
234
- videos: [{ type: "binary", data, mediaType: "video/mp4" }],
235
- warnings: [],
236
- response: { timestamp, modelId, headers: undefined },
237
- // A list, because the AI SDK joins only `videos` across calls and overwrites the rest.
238
- providerMetadata: {
239
- magichour: { videos: [{ projectId: id, creditsCharged: project.credits_charged }] },
240
- },
241
- };
242
- }
243
- catch {
244
- throw new MagicHourError("Could not download the generated video.", id);
245
- }
246
- },
247
- };
20
+ return videoModel(modelId, client);
248
21
  }
249
22
  return {
250
23
  specificationVersion: "v4",
@@ -0,0 +1,14 @@
1
+ import type { ImageModelV4CallOptions, Experimental_VideoModelV4CallOptions as VideoModelV4CallOptions } from "@ai-sdk/provider";
2
+ export declare const aspectRatios: readonly ["1:1", "16:9", "9:16"];
3
+ export type AspectRatio = (typeof aspectRatios)[number];
4
+ export declare const imageResolutions: readonly ["640px", "1k", "2k", "4k"];
5
+ export type ImageResolution = (typeof imageResolutions)[number];
6
+ export declare const videoResolutions: readonly ["360p", "480p", "720p", "1080p", "4k"];
7
+ export type VideoResolution = (typeof videoResolutions)[number];
8
+ export declare function isOneOf<T extends string>(values: readonly T[], value: unknown): value is T;
9
+ export declare function ratio(value: string | undefined): AspectRatio | undefined;
10
+ export declare function extra(options: ImageModelV4CallOptions | VideoModelV4CallOptions, allowed: string[]): import("@ai-sdk/provider").JSONObject;
11
+ /** Parses "WIDTHxHEIGHT" with positive whole numbers. */
12
+ export declare function dimensions(value: string): [width: number, height: number];
13
+ export declare function imageResolution(size: string | undefined, option: unknown): ImageResolution | undefined;
14
+ export declare function ratioFromSize(size: string | undefined): AspectRatio | undefined;
@@ -0,0 +1,57 @@
1
+ // Checks and conversions for the AI SDK's call options, shared by the image and video models.
2
+ export const aspectRatios = ["1:1", "16:9", "9:16"];
3
+ export const imageResolutions = ["640px", "1k", "2k", "4k"];
4
+ export const videoResolutions = ["360p", "480p", "720p", "1080p", "4k"];
5
+ export function isOneOf(values, value) {
6
+ return values.includes(value);
7
+ }
8
+ export function ratio(value) {
9
+ if (value === undefined)
10
+ return undefined;
11
+ if (!isOneOf(aspectRatios, value))
12
+ throw new Error("Supported aspect ratios: 1:1, 16:9, 9:16.");
13
+ return value;
14
+ }
15
+ export function extra(options, allowed) {
16
+ const values = options.providerOptions?.magichour ?? {};
17
+ for (const key of Object.keys(values))
18
+ if (!allowed.includes(key))
19
+ throw new Error(`Unsupported Magic Hour option: ${key}.`);
20
+ return values;
21
+ }
22
+ /** Parses "WIDTHxHEIGHT" with positive whole numbers. */
23
+ export function dimensions(value) {
24
+ const match = /^([1-9]\d*)x([1-9]\d*)$/.exec(value);
25
+ if (!match)
26
+ throw new Error("Dimensions must look like 1024x1024.");
27
+ return [Number(match[1]), Number(match[2])];
28
+ }
29
+ export function imageResolution(size, option) {
30
+ if (option !== undefined && !isOneOf(imageResolutions, option))
31
+ throw new Error("Image resolution must be 640px, 1k, 2k, or 4k.");
32
+ if (!size)
33
+ return option;
34
+ if (option !== undefined)
35
+ throw new Error("Use either size or providerOptions.magichour.resolution.");
36
+ // Magic Hour exposes longest-edge tiers, rather than arbitrary pixel sizes.
37
+ const edge = Math.max(...dimensions(size));
38
+ const tier = new Map([
39
+ [640, "640px"],
40
+ [1024, "1k"],
41
+ [2048, "2k"],
42
+ ]).get(edge);
43
+ if (!tier)
44
+ throw new Error("Use a 640, 1024, or 2048 longest edge, or set providerOptions.magichour.resolution.");
45
+ return tier;
46
+ }
47
+ export function ratioFromSize(size) {
48
+ if (!size)
49
+ return undefined;
50
+ const [w, h] = dimensions(size);
51
+ for (const r of aspectRatios) {
52
+ const [rw, rh] = r.split(":").map(Number);
53
+ if (Math.abs(w / h - rw / rh) < 0.002)
54
+ return r;
55
+ }
56
+ throw new Error("Dimensions must have a 1:1, 16:9, or 9:16 aspect ratio.");
57
+ }
@@ -0,0 +1,16 @@
1
+ import type { ImageModelV4File } from "@ai-sdk/provider";
2
+ import { MagicHourClient } from "@magichourhq/browser-client";
3
+ export type InputImage = {
4
+ url: string;
5
+ } | {
6
+ bytes: Uint8Array;
7
+ extension: string;
8
+ };
9
+ /** Checks an input image without uploading it, so a bad file never follows a good upload. */
10
+ export declare function inputImage(file: ImageModelV4File): InputImage;
11
+ export declare function filePath(transport: MagicHourClient, input: InputImage, signal: AbortSignal): Promise<string>;
12
+ /**
13
+ * Names the operation and model in an API rejection. One model setting reaches several endpoints,
14
+ * so the API's own message ("model must be one of …") doesn't say which one refused it.
15
+ */
16
+ export declare function submit(action: string, modelId: string, create: () => Promise<string>): Promise<string>;
@@ -0,0 +1,53 @@
1
+ import { MagicHourError, httpsURL } from "@magichourhq/browser-client";
2
+ // Input images and paid submissions: everything that sends something to Magic Hour.
3
+ function ascii(text) {
4
+ return [...text].map((c) => c.charCodeAt(0));
5
+ }
6
+ /** Checks the file signature, so mislabeled or non-image data never reaches a paid job. */
7
+ function hasSignature(bytes, extension) {
8
+ function startsWith(offset, signature) {
9
+ return signature.every((byte, i) => bytes[offset + i] === byte);
10
+ }
11
+ if (extension === "png")
12
+ return startsWith(0, [0x89, ...ascii("PNG\r\n"), 0x1a, 0x0a]);
13
+ if (extension === "jpg")
14
+ return startsWith(0, [0xff, 0xd8, 0xff]);
15
+ return startsWith(0, ascii("RIFF")) && startsWith(8, ascii("WEBP"));
16
+ }
17
+ /** Decodes strict base64, which `Buffer.from` would otherwise accept with characters dropped. */
18
+ function base64Bytes(value) {
19
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))
20
+ throw new Error("Image data must be base64.");
21
+ return new Uint8Array(Buffer.from(value, "base64"));
22
+ }
23
+ /** Checks an input image without uploading it, so a bad file never follows a good upload. */
24
+ export function inputImage(file) {
25
+ if (file.type === "url")
26
+ return { url: httpsURL(file.url) };
27
+ const extension = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" }[file.mediaType];
28
+ if (!extension)
29
+ throw new Error("Input images must be PNG, JPEG, or WebP.");
30
+ const bytes = typeof file.data === "string" ? base64Bytes(file.data) : file.data;
31
+ if (!hasSignature(bytes, extension))
32
+ throw new Error(`The input image data isn't a ${extension.toUpperCase()} file.`);
33
+ return { bytes, extension };
34
+ }
35
+ export async function filePath(transport, input, signal) {
36
+ if ("url" in input)
37
+ return input.url;
38
+ return transport.uploadImage(input.bytes, input.extension, signal);
39
+ }
40
+ /**
41
+ * Names the operation and model in an API rejection. One model setting reaches several endpoints,
42
+ * so the API's own message ("model must be one of …") doesn't say which one refused it.
43
+ */
44
+ export async function submit(action, modelId, create) {
45
+ try {
46
+ return await create();
47
+ }
48
+ catch (error) {
49
+ if (error instanceof MagicHourError && error.status < 500 && !error.projectId)
50
+ throw new MagicHourError(`Magic Hour can't ${action} with ${modelId}: ${error.message}`, undefined, error.status, undefined, error.code);
51
+ throw error;
52
+ }
53
+ }
@@ -0,0 +1,7 @@
1
+ import type { Experimental_VideoModelV4 as VideoModelV4 } from "@ai-sdk/provider";
2
+ import { type CreateBody, type MagicHourClient } from "@magichourhq/browser-client";
3
+ type VideoModel = NonNullable<CreateBody<"text-to-video">["model"]>;
4
+ export type MagicHourVideoModelId = VideoModel | NonNullable<CreateBody<"image-to-video">["model"]> | (string & {});
5
+ /** Generates videos from text, or from an input image. */
6
+ export declare function videoModel(modelId: MagicHourVideoModelId, client: () => MagicHourClient): VideoModelV4;
7
+ export {};
package/dist/video.js ADDED
@@ -0,0 +1,95 @@
1
+ import { MagicHourError } from "@magichourhq/browser-client";
2
+ import { dimensions, extra, isOneOf, ratio, ratioFromSize, videoResolutions, } from "./options.js";
3
+ import { filePath, inputImage, submit } from "./requests.js";
4
+ /** Generates videos from text, or from an input image. */
5
+ export function videoModel(modelId, client) {
6
+ return {
7
+ specificationVersion: "v4",
8
+ provider: "magichour.video",
9
+ modelId,
10
+ maxVideosPerCall: 1,
11
+ async doGenerate(options) {
12
+ if (options.n !== 1)
13
+ throw new Error("One video per request is supported.");
14
+ if (!options.prompt?.trim() && !options.image)
15
+ throw new Error("A prompt or input image is required.");
16
+ if (options.seed !== undefined || options.fps !== undefined)
17
+ throw new Error("Magic Hour does not expose seed or FPS parameters.");
18
+ if (options.frameImages?.length || options.inputReferences?.length)
19
+ throw new Error("Frame and reference inputs are not supported by this adapter.");
20
+ const extras = extra(options, ["resolution"]);
21
+ if (extras.resolution !== undefined && !isOneOf(videoResolutions, extras.resolution))
22
+ throw new Error("Invalid Magic Hour video resolution.");
23
+ if (options.resolution && extras.resolution !== undefined)
24
+ throw new Error("Use either resolution or providerOptions.magichour.resolution.");
25
+ let resolution = extras.resolution;
26
+ const dimensionsRatio = ratioFromSize(options.resolution);
27
+ if (options.resolution) {
28
+ const shortEdge = Math.min(...dimensions(options.resolution));
29
+ const mapped = new Map([
30
+ [360, "360p"],
31
+ [480, "480p"],
32
+ [720, "720p"],
33
+ [1080, "1080p"],
34
+ [2160, "4k"],
35
+ ]).get(shortEdge);
36
+ if (!mapped)
37
+ throw new Error("Unsupported video dimensions; use a resolution tier in providerOptions.magichour.");
38
+ resolution = mapped;
39
+ }
40
+ if (options.image && options.aspectRatio && options.aspectRatio !== "adaptive")
41
+ throw new Error("Image-to-video inherits the input image ratio; omit aspectRatio or use adaptive.");
42
+ if (!options.image && options.aspectRatio === "adaptive")
43
+ throw new Error("adaptive requires an input image.");
44
+ const aspectRatio = options.image ? undefined : ratio(options.aspectRatio ?? dimensionsRatio);
45
+ if (!options.image &&
46
+ dimensionsRatio &&
47
+ options.aspectRatio &&
48
+ dimensionsRatio !== options.aspectRatio)
49
+ throw new Error("resolution and aspectRatio disagree.");
50
+ const duration = options.duration ?? 5;
51
+ if (!Number.isFinite(duration) || duration < 1 || duration > 60)
52
+ throw new Error("Duration must be between 1 and 60 seconds; model-specific limits also apply.");
53
+ // Validate all options before uploading input or submitting a paid generation.
54
+ const transport = client();
55
+ const signal = transport.signal(options.abortSignal);
56
+ const imagePath = options.image
57
+ ? await filePath(transport, inputImage(options.image), signal)
58
+ : undefined;
59
+ const timestamp = new Date();
60
+ const shared = {
61
+ model: modelId,
62
+ end_seconds: duration,
63
+ ...(resolution ? { resolution } : {}),
64
+ ...(options.generateAudio !== undefined ? { audio: options.generateAudio } : {}),
65
+ };
66
+ const id = imagePath
67
+ ? await submit("animate images", modelId, () => transport.create("image-to-video", {
68
+ ...shared,
69
+ ...(options.prompt ? { style: { prompt: options.prompt } } : {}),
70
+ assets: { image_file_path: imagePath },
71
+ }, signal, options.headers))
72
+ : await submit("generate videos", modelId, () => transport.create("text-to-video", {
73
+ ...shared,
74
+ style: { prompt: options.prompt ?? "" },
75
+ aspect_ratio: aspectRatio ?? "16:9",
76
+ }, signal, options.headers));
77
+ const project = await transport.wait(id, "video", signal, options.headers);
78
+ try {
79
+ const data = await transport.download(project.downloads[0].url, signal);
80
+ return {
81
+ videos: [{ type: "binary", data, mediaType: "video/mp4" }],
82
+ warnings: [],
83
+ response: { timestamp, modelId, headers: undefined },
84
+ // A list, because the AI SDK joins only `videos` across calls and overwrites the rest.
85
+ providerMetadata: {
86
+ magichour: { videos: [{ projectId: id, creditsCharged: project.credits_charged }] },
87
+ },
88
+ };
89
+ }
90
+ catch {
91
+ throw new MagicHourError("Could not download the generated video.", id);
92
+ }
93
+ },
94
+ };
95
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magichourhq/ai-sdk-provider",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "packageManager": "yarn@4.18.0",
5
5
  "description": "Magic Hour image and video provider for the AI SDK",
6
6
  "keywords": [
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@ai-sdk/provider": "^4.0.31",
45
- "@magichourhq/browser-client": "^0.3.2"
45
+ "@magichourhq/browser-client": "^0.3.5"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/node": "^24.0.0",