@magichourhq/ai-sdk-provider 0.4.0 → 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
@@ -59,7 +59,7 @@ const magichour = createMagicHour({ apiKey: process.env.MY_KEY, timeoutMs: 300_0
59
59
 
60
60
  ## Models and options
61
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. Model IDs are typed from the API spec, so new models arrive with new releases. 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.
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
63
 
64
64
  | | Image | Video |
65
65
  | --- | --- | --- |
@@ -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,17 +1,16 @@
1
1
  import { type ImageModelV4, type Experimental_VideoModelV4 as VideoModelV4, type ProviderV4 } from "@ai-sdk/provider";
2
- import { type ClientSettings, type CreateBody } from "@magichourhq/browser-client";
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
- type GenerateImageModel = NonNullable<CreateBody<"ai-image-generator">["model"]>;
8
- type EditImageModel = NonNullable<CreateBody<"ai-image-editor">["model"]>;
9
- type VideoModel = NonNullable<CreateBody<"text-to-video">["model"]>;
10
- export type MagicHourImageModelId = GenerateImageModel | EditImageModel;
11
- export type MagicHourVideoModelId = VideoModel | NonNullable<CreateBody<"image-to-video">["model"]>;
12
11
  export interface MagicHourProvider extends Omit<ProviderV4, "imageModel"> {
13
12
  image(modelId?: MagicHourImageModelId): ImageModelV4;
14
- imageModel(modelId?: string): ImageModelV4;
13
+ imageModel(modelId?: MagicHourImageModelId): ImageModelV4;
15
14
  video(modelId?: MagicHourVideoModelId): VideoModelV4;
16
15
  videoModel(modelId?: MagicHourVideoModelId): VideoModelV4;
17
16
  }
package/dist/index.js CHANGED
@@ -1,295 +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 editAspectRatios = ["auto", "1:1", "16:9", "9:16", "4:3", "3:2", "4:5", "2:3"];
5
- const aspectRatios = ["1:1", "16:9", "9:16"];
6
- const imageResolutions = ["640px", "1k", "2k", "4k"];
7
- const videoResolutions = ["360p", "480p", "720p", "1080p", "4k"];
8
- function isOneOf(values, value) {
9
- return values.includes(value);
10
- }
11
- function ratio(value) {
12
- if (value === undefined)
13
- return undefined;
14
- if (!isOneOf(aspectRatios, value))
15
- throw new Error("Supported aspect ratios: 1:1, 16:9, 9:16.");
16
- return value;
17
- }
18
- function extra(options, allowed) {
19
- const values = options.providerOptions?.magichour ?? {};
20
- for (const key of Object.keys(values))
21
- if (!allowed.includes(key))
22
- throw new Error(`Unsupported Magic Hour option: ${key}.`);
23
- return values;
24
- }
25
- function ascii(text) {
26
- return [...text].map((c) => c.charCodeAt(0));
27
- }
28
- /** Checks the file signature, so mislabeled or non-image data never reaches a paid job. */
29
- function hasSignature(bytes, extension) {
30
- function startsWith(offset, signature) {
31
- return signature.every((byte, i) => bytes[offset + i] === byte);
32
- }
33
- if (extension === "png")
34
- return startsWith(0, [0x89, ...ascii("PNG\r\n"), 0x1a, 0x0a]);
35
- if (extension === "jpg")
36
- return startsWith(0, [0xff, 0xd8, 0xff]);
37
- return startsWith(0, ascii("RIFF")) && startsWith(8, ascii("WEBP"));
38
- }
39
- /** Decodes strict base64, which `Buffer.from` would otherwise accept with characters dropped. */
40
- function base64Bytes(value) {
41
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))
42
- throw new Error("Image data must be base64.");
43
- return new Uint8Array(Buffer.from(value, "base64"));
44
- }
45
- /** Parses "WIDTHxHEIGHT" with positive whole numbers. */
46
- function dimensions(value) {
47
- const match = /^([1-9]\d*)x([1-9]\d*)$/.exec(value);
48
- if (!match)
49
- throw new Error("Dimensions must look like 1024x1024.");
50
- return [Number(match[1]), Number(match[2])];
51
- }
52
- /** Checks an input image without uploading it, so a bad file never follows a good upload. */
53
- function inputImage(file) {
54
- if (file.type === "url")
55
- return { url: httpsURL(file.url) };
56
- const extension = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" }[file.mediaType];
57
- if (!extension)
58
- throw new Error("Input images must be PNG, JPEG, or WebP.");
59
- const bytes = typeof file.data === "string" ? base64Bytes(file.data) : file.data;
60
- if (!hasSignature(bytes, extension))
61
- throw new Error(`The input image data isn't a ${extension.toUpperCase()} file.`);
62
- return { bytes, extension };
63
- }
64
- async function filePath(transport, input, signal) {
65
- if ("url" in input)
66
- return input.url;
67
- return transport.uploadImage(input.bytes, input.extension, signal);
68
- }
69
- function imageResolution(size, option) {
70
- if (option !== undefined && !isOneOf(imageResolutions, option))
71
- throw new Error("Image resolution must be 640px, 1k, 2k, or 4k.");
72
- if (!size)
73
- return option;
74
- if (option !== undefined)
75
- throw new Error("Use either size or providerOptions.magichour.resolution.");
76
- // Magic Hour exposes longest-edge tiers, rather than arbitrary pixel sizes.
77
- const edge = Math.max(...dimensions(size));
78
- const tier = new Map([
79
- [640, "640px"],
80
- [1024, "1k"],
81
- [2048, "2k"],
82
- ]).get(edge);
83
- if (!tier)
84
- throw new Error("Use a 640, 1024, or 2048 longest edge, or set providerOptions.magichour.resolution.");
85
- return tier;
86
- }
87
- function ratioFromSize(size) {
88
- if (!size)
89
- return undefined;
90
- const [w, h] = dimensions(size);
91
- for (const r of aspectRatios) {
92
- const [rw, rh] = r.split(":").map(Number);
93
- if (Math.abs(w / h - rw / rh) < 0.002)
94
- return r;
95
- }
96
- throw new Error("Dimensions must have a 1:1, 16:9, or 9:16 aspect ratio.");
97
- }
98
- /**
99
- * Names the operation and model in an API rejection. One model setting reaches several endpoints,
100
- * so the API's own message ("model must be one of …") doesn't say which one refused it.
101
- */
102
- async function submit(action, modelId, create) {
103
- try {
104
- return await create();
105
- }
106
- catch (error) {
107
- if (error instanceof MagicHourError && error.status < 500 && !error.projectId)
108
- throw new MagicHourError(`Magic Hour can't ${action} with ${modelId}: ${error.message}`, undefined, error.status, undefined, error.code);
109
- throw error;
110
- }
111
- }
112
6
  export function createMagicHour(settings = {}) {
113
7
  // Resolve credentials lazily so merely importing or registering the provider needs no key.
114
- const client = () => new MagicHourClient({
115
- ...settings,
116
- apiKey: settings.apiKey ?? process.env.MAGIC_HOUR_API_KEY ?? "",
117
- });
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
+ }
118
16
  function image(modelId = "default") {
119
- return {
120
- specificationVersion: "v4",
121
- provider: "magichour.image",
122
- modelId,
123
- maxImagesPerCall: 1,
124
- // The API rejects input images for a model that can't edit, before charging anything.
125
- supportsFileInputs: true,
126
- supportsMaskInputs: false,
127
- async doGenerate(options) {
128
- const prompt = options.prompt;
129
- if (!prompt?.trim())
130
- throw new Error("An image prompt is required.");
131
- if (options.n !== 1)
132
- throw new Error("One image per request is supported.");
133
- if (options.mask)
134
- throw new Error("Masks are not supported.");
135
- const files = options.files ?? [];
136
- if (files.length > 10)
137
- throw new Error("Image editing accepts up to 10 input images.");
138
- if (options.seed !== undefined)
139
- throw new Error("Magic Hour does not expose a seed parameter.");
140
- const extras = extra(options, ["resolution"]);
141
- const resolution = imageResolution(options.size, extras.resolution);
142
- const sizeRatio = ratioFromSize(options.size);
143
- if (sizeRatio && options.aspectRatio && sizeRatio !== options.aspectRatio)
144
- throw new Error("size and aspectRatio disagree.");
145
- const requestedRatio = options.aspectRatio ?? sizeRatio;
146
- if (files.length && requestedRatio && !isOneOf(editAspectRatios, requestedRatio))
147
- throw new Error(`Supported aspect ratios for editing: ${editAspectRatios.join(", ")}.`);
148
- const inputs = files.map(inputImage);
149
- const transport = client();
150
- const signal = transport.signal(options.abortSignal);
151
- let id;
152
- let timestamp;
153
- if (inputs.length) {
154
- const paths = [];
155
- for (const input of inputs)
156
- paths.push(await filePath(transport, input, signal));
157
- timestamp = new Date();
158
- id = await submit("edit images", modelId, () => transport.create("ai-image-editor", {
159
- model: modelId,
160
- image_count: 1,
161
- ...(resolution ? { resolution } : {}),
162
- // Without one, the editor uses `auto`.
163
- ...(requestedRatio
164
- ? { aspect_ratio: requestedRatio }
165
- : {}),
166
- style: { prompt },
167
- assets: { image_file_paths: paths },
168
- }, signal, options.headers));
169
- }
170
- else {
171
- const aspectRatio = ratio(requestedRatio);
172
- timestamp = new Date();
173
- id = await submit("generate images", modelId, () => transport.create("ai-image-generator", {
174
- model: modelId,
175
- image_count: 1,
176
- ...(resolution ? { resolution } : {}),
177
- ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}),
178
- style: { prompt },
179
- }, signal, options.headers));
180
- }
181
- const project = await transport.wait(id, "image", signal, options.headers);
182
- try {
183
- const images = await Promise.all(project.downloads.slice(0, 1).map((d) => transport.download(d.url, signal)));
184
- return {
185
- images,
186
- warnings: [],
187
- isRetryable: false,
188
- response: { timestamp, modelId, headers: undefined },
189
- // The AI SDK keeps only this list, and joins it across calls.
190
- providerMetadata: {
191
- magichour: { images: [{ projectId: id, creditsCharged: project.credits_charged }] },
192
- },
193
- };
194
- }
195
- catch {
196
- throw new MagicHourError("Could not download the generated image.", id);
197
- }
198
- },
199
- };
17
+ return imageModel(modelId, client);
200
18
  }
201
19
  function video(modelId = "default") {
202
- return {
203
- specificationVersion: "v4",
204
- provider: "magichour.video",
205
- modelId,
206
- maxVideosPerCall: 1,
207
- async doGenerate(options) {
208
- if (options.n !== 1)
209
- throw new Error("One video per request is supported.");
210
- if (!options.prompt?.trim() && !options.image)
211
- throw new Error("A prompt or input image is required.");
212
- if (options.seed !== undefined || options.fps !== undefined)
213
- throw new Error("Magic Hour does not expose seed or FPS parameters.");
214
- if (options.frameImages?.length || options.inputReferences?.length)
215
- throw new Error("Frame and reference inputs are not supported by this adapter.");
216
- const extras = extra(options, ["resolution"]);
217
- if (extras.resolution !== undefined && !isOneOf(videoResolutions, extras.resolution))
218
- throw new Error("Invalid Magic Hour video resolution.");
219
- if (options.resolution && extras.resolution !== undefined)
220
- throw new Error("Use either resolution or providerOptions.magichour.resolution.");
221
- let resolution = extras.resolution;
222
- const dimensionsRatio = ratioFromSize(options.resolution);
223
- if (options.resolution) {
224
- const shortEdge = Math.min(...dimensions(options.resolution));
225
- const mapped = new Map([
226
- [360, "360p"],
227
- [480, "480p"],
228
- [720, "720p"],
229
- [1080, "1080p"],
230
- [2160, "4k"],
231
- ]).get(shortEdge);
232
- if (!mapped)
233
- throw new Error("Unsupported video dimensions; use a resolution tier in providerOptions.magichour.");
234
- resolution = mapped;
235
- }
236
- if (options.image && options.aspectRatio && options.aspectRatio !== "adaptive")
237
- throw new Error("Image-to-video inherits the input image ratio; omit aspectRatio or use adaptive.");
238
- if (!options.image && options.aspectRatio === "adaptive")
239
- throw new Error("adaptive requires an input image.");
240
- const aspectRatio = options.image
241
- ? undefined
242
- : ratio(options.aspectRatio ?? dimensionsRatio);
243
- if (!options.image &&
244
- dimensionsRatio &&
245
- options.aspectRatio &&
246
- dimensionsRatio !== options.aspectRatio)
247
- throw new Error("resolution and aspectRatio disagree.");
248
- const duration = options.duration ?? 5;
249
- if (!Number.isFinite(duration) || duration < 1 || duration > 60)
250
- throw new Error("Duration must be between 1 and 60 seconds; model-specific limits also apply.");
251
- // Validate all options before uploading input or submitting a paid generation.
252
- const transport = client();
253
- const signal = transport.signal(options.abortSignal);
254
- const imagePath = options.image
255
- ? await filePath(transport, inputImage(options.image), signal)
256
- : undefined;
257
- const timestamp = new Date();
258
- const shared = {
259
- model: modelId,
260
- end_seconds: duration,
261
- ...(resolution ? { resolution } : {}),
262
- ...(options.generateAudio !== undefined ? { audio: options.generateAudio } : {}),
263
- };
264
- const id = imagePath
265
- ? await submit("animate images", modelId, () => transport.create("image-to-video", {
266
- ...shared,
267
- ...(options.prompt ? { style: { prompt: options.prompt } } : {}),
268
- assets: { image_file_path: imagePath },
269
- }, signal, options.headers))
270
- : await submit("generate videos", modelId, () => transport.create("text-to-video", {
271
- ...shared,
272
- style: { prompt: options.prompt ?? "" },
273
- aspect_ratio: aspectRatio ?? "16:9",
274
- }, signal, options.headers));
275
- const project = await transport.wait(id, "video", signal, options.headers);
276
- try {
277
- const data = await transport.download(project.downloads[0].url, signal);
278
- return {
279
- videos: [{ type: "binary", data, mediaType: "video/mp4" }],
280
- warnings: [],
281
- response: { timestamp, modelId, headers: undefined },
282
- // A list, because the AI SDK joins only `videos` across calls and overwrites the rest.
283
- providerMetadata: {
284
- magichour: { videos: [{ projectId: id, creditsCharged: project.credits_charged }] },
285
- },
286
- };
287
- }
288
- catch {
289
- throw new MagicHourError("Could not download the generated video.", id);
290
- }
291
- },
292
- };
20
+ return videoModel(modelId, client);
293
21
  }
294
22
  return {
295
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.4.0",
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": [