@fungi.computer/darkroom 0.11.11 → 0.11.13

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.
Files changed (90) hide show
  1. package/README.md +13 -0
  2. package/examples/standalone/README.md +52 -0
  3. package/examples/standalone/worker.ts +87 -0
  4. package/examples/standalone/wrangler.jsonc +26 -0
  5. package/package.json +8 -2
  6. package/src/app-media-contracts.ts +142 -0
  7. package/src/audio-providers/elevenlabs.ts +108 -0
  8. package/src/audio-reference-types.ts +47 -0
  9. package/src/audio-references.ts +107 -0
  10. package/src/browser-failure.ts +73 -0
  11. package/src/browser.ts +7 -0
  12. package/src/cloudflare/provider-reason.ts +89 -0
  13. package/src/cloudflare/provider.ts +405 -0
  14. package/src/cloudflare/r2-destination.ts +130 -0
  15. package/src/cloudflare/reference-images.ts +193 -0
  16. package/src/cloudflare.ts +38 -0
  17. package/src/cost-estimate.ts +129 -0
  18. package/src/daily-media-meter.ts +163 -0
  19. package/src/effect.ts +2 -0
  20. package/src/execution-error.ts +98 -0
  21. package/src/failure.ts +13 -0
  22. package/src/gateway-models.ts +304 -0
  23. package/src/gateway-wire.ts +36 -0
  24. package/src/index.ts +1454 -0
  25. package/src/media-binding.ts +260 -0
  26. package/src/media-content-type.ts +60 -0
  27. package/src/media-generation.ts +171 -0
  28. package/src/media-operation-contract.ts +173 -0
  29. package/src/media-operation-do.ts +257 -0
  30. package/src/media-operation-owner.ts +1786 -0
  31. package/src/media-operation-storage.ts +110 -0
  32. package/src/media-operation.ts +454 -0
  33. package/src/media-path.ts +8 -0
  34. package/src/media-quote.ts +34 -0
  35. package/src/media-run-lifetime.ts +5 -0
  36. package/src/media-written.ts +38 -0
  37. package/src/model-catalog.ts +1574 -0
  38. package/src/neurons.ts +6 -0
  39. package/src/node-webpmux.d.ts +12 -0
  40. package/src/provenance-bytes.ts +22 -0
  41. package/src/provenance-export.ts +126 -0
  42. package/src/provenance-jpeg.ts +83 -0
  43. package/src/provenance-png.ts +26 -0
  44. package/src/provenance-signed.ts +7 -0
  45. package/src/provenance-xmp.ts +57 -0
  46. package/src/provenance.ts +87 -0
  47. package/src/reference-image-size.ts +67 -0
  48. package/src/reference-read.ts +50 -0
  49. package/src/server.ts +711 -0
  50. package/src/video-providers/index.ts +18 -0
  51. package/src/video-providers/minimax.ts +96 -0
  52. package/src/video-providers/reference-encoding.ts +32 -0
  53. package/src/video-providers/types.ts +47 -0
  54. package/src/video-providers/unified.ts +68 -0
  55. package/test/audio-models.test.ts +428 -0
  56. package/test/audio-references.test.ts +428 -0
  57. package/test/custom-catalogue.test.ts +257 -0
  58. package/test/daily-media-meter.test.ts +287 -0
  59. package/test/failure.test.ts +190 -0
  60. package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
  61. package/test/fixtures/media-operation.fixture.ts +134 -0
  62. package/test/fixtures/media-team-prompts.ts +7 -0
  63. package/test/fixtures/native-sqlite.fixture.ts +40 -0
  64. package/test/gateway-models.test.ts +712 -0
  65. package/test/media-operation-do.test.ts +1565 -0
  66. package/test/media-quote.test.ts +81 -0
  67. package/test/media-retention.test.ts +597 -0
  68. package/test/media-service.test.ts +549 -0
  69. package/test/media-team-prompts.test.ts +92 -0
  70. package/test/model-facts.test.ts +126 -0
  71. package/test/prompt-limit.test.ts +53 -0
  72. package/test/provenance-export.test.ts +144 -0
  73. package/test/provenance-images.fixture.mjs +17 -0
  74. package/test/provenance.test.ts +179 -0
  75. package/test/provider-gateway.test.ts +114 -0
  76. package/test/provider-reasons.test.ts +133 -0
  77. package/test/r2-destination.test.ts +166 -0
  78. package/test/reference-image-size.test.ts +73 -0
  79. package/test/reference-images-billing.test.ts +40 -0
  80. package/test/reference-images.test.ts +399 -0
  81. package/test/standalone.cloudflare.test.mjs +298 -0
  82. package/test/standalone.worker.mjs +70 -0
  83. package/test/transform-models.test.ts +400 -0
  84. package/test/video-capabilities.test.ts +160 -0
  85. package/test/video-contract.test.ts +533 -0
  86. package/test/video-failure-lifecycle.test.ts +177 -0
  87. package/test/video-provider.test.ts +136 -0
  88. package/test/video-wire.test.ts +251 -0
  89. package/vitest.cloudflare.config.ts +22 -0
  90. package/vitest.node.config.ts +14 -0
@@ -0,0 +1,70 @@
1
+ import worker, {
2
+ StandaloneMedia as NativeStandaloneMedia,
3
+ } from "../examples/standalone/worker.js";
4
+ import { MediaOperationDO as NativeMediaOperationDO } from "../dist/cloudflare.js";
5
+ export default worker;
6
+
7
+ export const imageBytes = Uint8Array.from(
8
+ globalThis.atob("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"),
9
+ (character) => character.charCodeAt(0),
10
+ );
11
+
12
+ /** Inject only provider bytes and one failed destination write; SQL and R2 are native. */
13
+ export class StandaloneMedia extends NativeStandaloneMedia {
14
+ constructor(state, env) {
15
+ super(state, {
16
+ ...env,
17
+ // The Images binding is not a provider; report fixed metadata for the 1x1 GIFs the proofs store.
18
+ IMAGES: {
19
+ info: async () => ({ format: "image/gif", width: 1, height: 1 }),
20
+ },
21
+ AI: {
22
+ run: async (_model, input) => {
23
+ if (input.multipart !== undefined)
24
+ await env.PROOF.put(
25
+ "provider-input",
26
+ await new globalThis.Response(input.multipart.body).text(),
27
+ );
28
+ const previous = await env.PROOF.get("provider-count");
29
+ const count = previous === null ? 0 : Number(await previous.text());
30
+ await env.PROOF.put("provider-count", String(count + 1));
31
+ const output = await env.PROOF.get("provider-image");
32
+ return output
33
+ ? new Uint8Array(await output.arrayBuffer())
34
+ : imageBytes.slice();
35
+ },
36
+ },
37
+ OUTPUTS: {
38
+ get: env.OUTPUTS.get.bind(env.OUTPUTS),
39
+ put: async (key, bytes, options) => {
40
+ if (await env.PROOF.get("fail-next-save")) {
41
+ await env.PROOF.delete("fail-next-save");
42
+ throw new Error("Injected destination failure");
43
+ }
44
+ return env.OUTPUTS.put(key, bytes, options);
45
+ },
46
+ },
47
+ });
48
+ }
49
+ }
50
+
51
+ /** Lose the acknowledgement after native R2 commits, before the owner records SQL. */
52
+ export class MediaOperationDO extends NativeMediaOperationDO {
53
+ constructor(state, env) {
54
+ super(state, {
55
+ ...env,
56
+ APP_ARTIFACTS: {
57
+ get: env.APP_ARTIFACTS.get.bind(env.APP_ARTIFACTS),
58
+ head: env.APP_ARTIFACTS.head.bind(env.APP_ARTIFACTS),
59
+ put: async (key, bytes, options) => {
60
+ const stored = await env.APP_ARTIFACTS.put(key, bytes, options);
61
+ if (await env.PROOF.get("fail-next-output-ack")) {
62
+ await env.PROOF.delete("fail-next-output-ack");
63
+ throw new Error("Lost output acknowledgement before SQL receipt");
64
+ }
65
+ return stored;
66
+ },
67
+ },
68
+ });
69
+ }
70
+ }
@@ -0,0 +1,400 @@
1
+ import sharp from "sharp";
2
+ import * as z from "zod";
3
+ import { describe, expect, it, vi } from "vitest";
4
+ import {
5
+ getMediaModel,
6
+ listMediaModels,
7
+ resolveMediaReferences,
8
+ validateMediaGenerationSettings,
9
+ type MediaReferenceBytes,
10
+ } from "../src/index.js";
11
+ import {
12
+ estimateMediaModel,
13
+ generate,
14
+ type MediaAiPort,
15
+ } from "../src/cloudflare/provider.js";
16
+ import { quoteMediaGeneration } from "../src/media-quote.js";
17
+ import { createMediaService } from "../src/server.js";
18
+ import { mediaOperationFixture } from "./fixtures/media-operation.fixture.js";
19
+
20
+ const removeBackground = "bria/remove-background";
21
+ const upscale = "pruna/p-image-upscale";
22
+ const solid = (
23
+ width: number,
24
+ height: number,
25
+ format: "png" | "jpeg" = "png",
26
+ ) => {
27
+ const image = sharp({
28
+ create: { width, height, channels: 3, background: "white" },
29
+ });
30
+ return (format === "png" ? image.png() : image.jpeg()).toBuffer();
31
+ };
32
+ const sourceImage = async (
33
+ width: number,
34
+ height: number,
35
+ format: "png" | "jpeg" | "webp" = "png",
36
+ claimed: { width?: number; height?: number } = {},
37
+ ): Promise<MediaReferenceBytes> => ({
38
+ bytes: new Uint8Array(
39
+ format === "webp"
40
+ ? await sharp({
41
+ create: { width, height, channels: 3, background: "white" },
42
+ })
43
+ .webp()
44
+ .toBuffer()
45
+ : await solid(width, height, format),
46
+ ),
47
+ format,
48
+ width: claimed.width ?? width,
49
+ height: claimed.height ?? height,
50
+ filename: "source",
51
+ });
52
+ const reference = [{ computerId: "c", path: "/print.png" }];
53
+ type Extra = { width?: number; height?: number; targetMegapixels?: number };
54
+ const settings = (model: string, extra: Extra = {}) =>
55
+ validateMediaGenerationSettings({
56
+ model,
57
+ prompt: "Remove background",
58
+ references: reference,
59
+ ...extra,
60
+ });
61
+ const reader = (image: MediaReferenceBytes) => ({
62
+ read: () => Promise.resolve(image),
63
+ });
64
+
65
+ const requireModel = (id: string) => {
66
+ const model = listMediaModels().find((entry) => entry.id === id);
67
+ if (model === undefined) throw new Error(`missing ${id}`);
68
+ return model;
69
+ };
70
+
71
+ describe("source-image operations in the catalog", () => {
72
+ it("lists both with their facts, image billing and no prompt-model controls", () => {
73
+ for (const id of [removeBackground, upscale]) {
74
+ const model = getMediaModel(id);
75
+ expect(model?.kind, id).toBe("image");
76
+ expect(model?.billingUnit, id).toBe("image");
77
+ expect(model?.input.maxReferences, id).toBe(1);
78
+ expect(model?.transform?.source, id).toEqual({
79
+ formats: ["png", "jpeg"],
80
+ maxBytes: 8 * 1024 * 1024,
81
+ maxPixels: 25_000_000,
82
+ });
83
+ expect(listMediaModels().map((entry) => entry.id)).toContain(id);
84
+ }
85
+ expect(getMediaModel(removeBackground)?.transform).toMatchObject({
86
+ operation: "remove_background",
87
+ milliunits: 1_800,
88
+ sizes: [],
89
+ });
90
+ expect(getMediaModel(upscale)?.transform).toMatchObject({
91
+ operation: "upscale",
92
+ defaultMegapixels: 4,
93
+ // Cloudflare's published tiers: $0.005 to 4 MP, $0.01 to 8, $0.02 to 16.
94
+ milliunits: null,
95
+ sizes: [
96
+ { megapixels: 4, milliunits: 500 },
97
+ { megapixels: 8, milliunits: 1_000 },
98
+ { megapixels: 16, milliunits: 2_000 },
99
+ ],
100
+ });
101
+ });
102
+
103
+ it("takes exactly one source image and only its own settings", () => {
104
+ expect(() =>
105
+ validateMediaGenerationSettings({ model: upscale, prompt: "Upscale" }),
106
+ ).toThrow("exactly one source image");
107
+ expect(() =>
108
+ settings(removeBackground, { width: 512, height: 512 }),
109
+ ).toThrow("takes one source image");
110
+ expect(() => settings(removeBackground, { targetMegapixels: 4 })).toThrow(
111
+ "does not take an output size",
112
+ );
113
+ expect(() => settings(upscale, { targetMegapixels: 5 })).toThrow(
114
+ "accepts output sizes of 4, 8, 16 megapixels",
115
+ );
116
+ expect(settings(upscale).targetMegapixels).toBe(4);
117
+ expect(() =>
118
+ validateMediaGenerationSettings({
119
+ model: "@cf/black-forest-labs/flux-1-schnell",
120
+ prompt: "x",
121
+ width: 512,
122
+ height: 512,
123
+ targetMegapixels: 4,
124
+ }),
125
+ ).toThrow("does not take an output size");
126
+ });
127
+
128
+ it("quotes the published price of the chosen output size", async () => {
129
+ const small = await sourceImage(400, 300);
130
+ const quote = (model: string, extra?: Extra) =>
131
+ quoteMediaGeneration(
132
+ { model, prompt: "x", references: reference, ...extra },
133
+ reader(small),
134
+ );
135
+ await expect(quote(removeBackground)).resolves.toMatchObject({
136
+ unit: "image",
137
+ units: 1,
138
+ providerCostMilliunits: 1_800,
139
+ });
140
+ await expect(quote(upscale)).resolves.toMatchObject({
141
+ providerCostMilliunits: 500,
142
+ });
143
+ await expect(
144
+ quote(upscale, { targetMegapixels: 8 }),
145
+ ).resolves.toMatchObject({
146
+ providerCostMilliunits: 1_000,
147
+ });
148
+ await expect(
149
+ quote(upscale, { targetMegapixels: 16 }),
150
+ ).resolves.toMatchObject({
151
+ providerCostMilliunits: 2_000,
152
+ });
153
+ });
154
+ });
155
+
156
+ describe("source validation before any paid call", () => {
157
+ it("refuses WebP, an oversized byte count and too many pixels", async () => {
158
+ await expect(
159
+ resolveMediaReferences(
160
+ settings(removeBackground),
161
+ reader(await sourceImage(64, 64, "webp")),
162
+ ),
163
+ ).rejects.toThrow("takes PNG or JPEG images, not WEBP");
164
+ const huge = await sourceImage(64, 64);
165
+ await expect(
166
+ resolveMediaReferences(
167
+ settings(removeBackground),
168
+ reader({ ...huge, bytes: new Uint8Array(8 * 1024 * 1024 + 1) }),
169
+ ),
170
+ ).rejects.toThrow();
171
+ await expect(
172
+ resolveMediaReferences(
173
+ settings(removeBackground),
174
+ reader({ ...huge, width: 5_001, height: 5_000 }),
175
+ ),
176
+ ).rejects.toThrow("over 25 megapixels");
177
+ });
178
+
179
+ it("refuses an upscale whose source is already as large as the output", async () => {
180
+ const big = { ...(await sourceImage(64, 64)), width: 2_000, height: 2_000 };
181
+ await expect(
182
+ resolveMediaReferences(settings(upscale), reader(big)),
183
+ ).rejects.toThrow("already 4.0 megapixels. Choose a larger output");
184
+ await expect(
185
+ resolveMediaReferences(
186
+ settings(upscale, { targetMegapixels: 8 }),
187
+ reader(big),
188
+ ),
189
+ ).resolves.toHaveLength(1);
190
+ });
191
+ });
192
+
193
+ describe("providers", () => {
194
+ const out = async () => new Uint8Array(await solid(8, 8));
195
+ it("sends the source bytes as a data URI and downloads the result", async () => {
196
+ const source = await sourceImage(32, 32);
197
+ const run = vi.fn<MediaAiPort["run"]>(() =>
198
+ Promise.resolve({
199
+ state: "Completed",
200
+ result: { image: "https://provider.example/cut.png" },
201
+ }),
202
+ );
203
+ const ai: MediaAiPort = { run };
204
+ const fetchResult = vi.fn(async () => new Response(await out()));
205
+ const cut = await generate(
206
+ ai,
207
+ settings(removeBackground),
208
+ [source],
209
+ undefined,
210
+ undefined,
211
+ fetchResult,
212
+ );
213
+ expect(cut.format).toBe("png");
214
+ expect(run).toHaveBeenCalledWith(
215
+ removeBackground,
216
+ {
217
+ image: `data:image/png;base64,${Buffer.from(source.bytes).toString("base64")}`,
218
+ preserve_alpha: true,
219
+ },
220
+ undefined,
221
+ );
222
+ await generate(
223
+ ai,
224
+ settings(upscale, { targetMegapixels: 8 }),
225
+ [source],
226
+ undefined,
227
+ undefined,
228
+ fetchResult,
229
+ );
230
+ expect(run).toHaveBeenLastCalledWith(
231
+ upscale,
232
+ expect.objectContaining({ target: 8, output_format: "webp" }),
233
+ undefined,
234
+ );
235
+ const body = z.object({ image: z.string() }).parse(run.mock.lastCall?.[1]);
236
+ expect(body.image.startsWith("data:image/png;base64,")).toBe(true);
237
+ });
238
+
239
+ it("charges the estimate, saves the output and reuses it on retry", async () => {
240
+ const fixture = mediaOperationFixture();
241
+ try {
242
+ const source = await sourceImage(32, 32);
243
+ const run = vi.fn(() =>
244
+ Promise.resolve({
245
+ state: "Completed",
246
+ result: { image: "https://provider.example/up.webp" },
247
+ }),
248
+ );
249
+ const fetchResult = async () =>
250
+ new Response(
251
+ new Uint8Array(
252
+ await sharp(await solid(8, 8))
253
+ .webp()
254
+ .toBuffer(),
255
+ ),
256
+ );
257
+ const admit = vi.fn(() => Promise.resolve({ priceMilliunits: 1_500 }));
258
+ const settle = vi.fn(() => Promise.resolve());
259
+ const writes: string[] = [];
260
+ const service = createMediaService({
261
+ scope: {
262
+ actorId: "artist",
263
+ namespace: "studio",
264
+ owner: "prints",
265
+ destinationId: "c",
266
+ },
267
+ operations: { getByName: () => fixture.owner },
268
+ provider: (request, references, signal, format, audio) =>
269
+ generate(
270
+ { run },
271
+ request,
272
+ references,
273
+ signal,
274
+ undefined,
275
+ fetchResult,
276
+ format,
277
+ audio,
278
+ ),
279
+ metering: { admit, settle },
280
+ refusalMessages: {
281
+ insufficient_credits: "Refill",
282
+ denied: "Denied",
283
+ daily_limit_reached: "Daily limit",
284
+ },
285
+ destination: {
286
+ authorize: () => Promise.resolve(),
287
+ remove: () => Promise.resolve("absent" as const),
288
+ write: (path) => {
289
+ writes.push(path);
290
+ return Promise.resolve();
291
+ },
292
+ readReference: () => Promise.resolve(source),
293
+ },
294
+ });
295
+ const post = () =>
296
+ service.request("/generate", {
297
+ method: "POST",
298
+ headers: {
299
+ "Content-Type": "application/json",
300
+ "X-Request-Id": "upscale-retry",
301
+ },
302
+ body: JSON.stringify({
303
+ path: "/print-up.webp",
304
+ settings: {
305
+ model: upscale,
306
+ prompt: "Upscale to 8 MP",
307
+ targetMegapixels: 8,
308
+ references: reference,
309
+ },
310
+ }),
311
+ });
312
+ const first = await post();
313
+ expect(first.status).toBe(200);
314
+ expect(await first.json()).toMatchObject({
315
+ path: "/print-up.webp",
316
+ // The host's admitted customer price, not the provider cost.
317
+ costMilliunits: 1_500,
318
+ model: upscale,
319
+ });
320
+ const second = await post();
321
+ expect(second.status).toBe(200);
322
+ expect(run).toHaveBeenCalledTimes(1);
323
+ expect(admit).toHaveBeenCalledTimes(1);
324
+ expect(admit).toHaveBeenCalledWith(
325
+ expect.objectContaining({
326
+ units: 1,
327
+ unit: "image",
328
+ providerCostMilliunits: 1_000,
329
+ }),
330
+ );
331
+ expect(settle).toHaveBeenCalledTimes(1);
332
+ expect(writes).toEqual(["/print-up.webp"]);
333
+ } finally {
334
+ fixture.close();
335
+ }
336
+ });
337
+
338
+ it("makes no paid call or admission for an unsupported source", async () => {
339
+ const fixture = mediaOperationFixture();
340
+ try {
341
+ const run = vi.fn();
342
+ const admit = vi.fn();
343
+ const service = createMediaService({
344
+ scope: {
345
+ actorId: "artist",
346
+ namespace: "studio",
347
+ owner: "prints",
348
+ destinationId: "c",
349
+ },
350
+ operations: { getByName: () => fixture.owner },
351
+ provider: () => Promise.reject(new Error("unexpected provider call")),
352
+ metering: { admit, settle: () => Promise.resolve() },
353
+ refusalMessages: {
354
+ insufficient_credits: "Refill",
355
+ denied: "Denied",
356
+ daily_limit_reached: "Daily limit",
357
+ },
358
+ destination: {
359
+ authorize: () => Promise.resolve(),
360
+ remove: () => Promise.resolve("absent" as const),
361
+ write: () => Promise.resolve(),
362
+ readReference: async () => sourceImage(64, 64, "webp"),
363
+ },
364
+ });
365
+ const response = await service.request("/generate", {
366
+ method: "POST",
367
+ headers: {
368
+ "Content-Type": "application/json",
369
+ "X-Request-Id": "refuse-webp",
370
+ },
371
+ body: JSON.stringify({
372
+ path: "/cut.png",
373
+ settings: {
374
+ model: removeBackground,
375
+ prompt: "Remove background",
376
+ references: reference,
377
+ },
378
+ }),
379
+ });
380
+ expect(response.status).toBeGreaterThanOrEqual(400);
381
+ expect(run).not.toHaveBeenCalled();
382
+ expect(admit).not.toHaveBeenCalled();
383
+ } finally {
384
+ fixture.close();
385
+ }
386
+ });
387
+ });
388
+
389
+ describe("catalog price estimates", () => {
390
+ it("estimates each operation at its default output size", () => {
391
+ expect(
392
+ estimateMediaModel(requireModel(removeBackground)).costMilliunits,
393
+ ).toBe(1_800);
394
+ expect(estimateMediaModel(requireModel(upscale)).costMilliunits).toBe(500);
395
+ // The placeholder reference that satisfies validation is not part of the quote.
396
+ expect(
397
+ estimateMediaModel(requireModel(upscale)).settings,
398
+ ).not.toHaveProperty("references");
399
+ });
400
+ });
@@ -0,0 +1,160 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ getMediaModel,
4
+ validateMediaGenerationSettings,
5
+ } from "../src/index.js";
6
+
7
+ /**
8
+ * What each video model documents, from its Cloudflare model page (checked
9
+ * 2026-10-26). A capability the page does not name stays out of the catalog.
10
+ */
11
+ const documented = [
12
+ {
13
+ id: "bytedance/seedance-2.5",
14
+ doc: "https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/",
15
+ roles: ["first-frame", "last-frame", "reference"],
16
+ maxReferenceImages: 30,
17
+ supportsAudio: true,
18
+ defaultGenerateAudio: true,
19
+ },
20
+ {
21
+ id: "bytedance/seedance-2.0",
22
+ doc: "https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/",
23
+ roles: ["first-frame", "last-frame", "reference"],
24
+ maxReferenceImages: 4,
25
+ supportsAudio: true,
26
+ defaultGenerateAudio: true,
27
+ },
28
+ {
29
+ id: "bytedance/seedance-2.0-fast",
30
+ doc: "https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-fast/",
31
+ roles: ["first-frame", "last-frame", "reference"],
32
+ maxReferenceImages: 4,
33
+ supportsAudio: true,
34
+ defaultGenerateAudio: true,
35
+ },
36
+ {
37
+ id: "bytedance/seedance-2.0-mini",
38
+ doc: "https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0-mini/",
39
+ roles: ["first-frame", "last-frame", "reference"],
40
+ maxReferenceImages: 4,
41
+ supportsAudio: true,
42
+ defaultGenerateAudio: true,
43
+ },
44
+ {
45
+ id: "google/veo-3.1",
46
+ doc: "https://developers.cloudflare.com/ai/models/google/veo-3.1/",
47
+ roles: ["first-frame"],
48
+ maxReferenceImages: 0,
49
+ supportsAudio: true,
50
+ defaultGenerateAudio: true,
51
+ },
52
+ {
53
+ id: "google/veo-3.1-fast",
54
+ doc: "https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/",
55
+ roles: ["first-frame"],
56
+ maxReferenceImages: 0,
57
+ supportsAudio: true,
58
+ defaultGenerateAudio: true,
59
+ },
60
+ {
61
+ id: "minimax/h3-max",
62
+ doc: "https://developers.cloudflare.com/ai/models/minimax/h3-max/",
63
+ roles: ["first-frame", "reference"],
64
+ maxReferenceImages: 4,
65
+ supportsAudio: false,
66
+ defaultGenerateAudio: null,
67
+ },
68
+ ] as const;
69
+
70
+ const sized = (id: string) => {
71
+ const video = getMediaModel(id)?.video;
72
+ if (!video) throw new Error(`catalog missing ${id}`);
73
+ const format = video.formats.find(
74
+ (candidate) =>
75
+ candidate.resolution === video.defaultResolution &&
76
+ candidate.aspectRatio === video.defaultAspectRatio,
77
+ );
78
+ if (!format) throw new Error(`${id} default format missing`);
79
+ return {
80
+ model: id,
81
+ prompt: "fern fronds unfurling",
82
+ width: format.width,
83
+ height: format.height,
84
+ };
85
+ };
86
+ const ref = (
87
+ role: "first-frame" | "last-frame" | "reference",
88
+ path: string = role,
89
+ ) => ({
90
+ computerId: "pictures",
91
+ path,
92
+ role,
93
+ });
94
+
95
+ describe("video capabilities follow each model's documentation", () => {
96
+ it.each(documented)("$id ($doc)", (row) => {
97
+ const video = getMediaModel(row.id)?.video;
98
+ expect(video?.referenceRoles).toEqual(row.roles);
99
+ expect(video?.maxReferenceImages).toBe(row.maxReferenceImages);
100
+ expect(video?.supportsAudio).toBe(row.supportsAudio);
101
+ expect(video?.defaultGenerateAudio).toBe(row.defaultGenerateAudio);
102
+ });
103
+
104
+ it("refuses a last frame where the page names none", () => {
105
+ for (const id of ["google/veo-3.1", "minimax/h3-max"])
106
+ expect(() =>
107
+ validateMediaGenerationSettings({
108
+ ...sized(id),
109
+ references: [ref("last-frame", "b")],
110
+ }),
111
+ ).toThrow(/no last frame/);
112
+ });
113
+
114
+ it("accepts a first and last frame on Seedance", () => {
115
+ const settings = validateMediaGenerationSettings({
116
+ ...sized("bytedance/seedance-2.0"),
117
+ references: [ref("first-frame", "a"), ref("last-frame", "b")],
118
+ });
119
+ expect(settings.references?.map((entry) => entry.role)).toEqual([
120
+ "first-frame",
121
+ "last-frame",
122
+ ]);
123
+ });
124
+
125
+ it("names the resolution that rules out reference mode", () => {
126
+ expect(() =>
127
+ validateMediaGenerationSettings({
128
+ ...sized("bytedance/seedance-2.0"),
129
+ resolution: "1080p",
130
+ width: 1920,
131
+ height: 1080,
132
+ references: [ref("reference", "a")],
133
+ }),
134
+ ).toThrow(/takes reference images only at/);
135
+ });
136
+
137
+ it("documents audio only where the page names a field", () => {
138
+ expect(
139
+ validateMediaGenerationSettings({
140
+ ...sized("bytedance/seedance-2.0"),
141
+ generateAudio: false,
142
+ }).generateAudio,
143
+ ).toBe(false);
144
+ expect(
145
+ validateMediaGenerationSettings(sized("google/veo-3.1")).generateAudio,
146
+ ).toBe(true);
147
+ expect(
148
+ validateMediaGenerationSettings(sized("minimax/h3-max")).generateAudio,
149
+ ).toBeUndefined();
150
+ });
151
+
152
+ it("keeps frames and references apart", () => {
153
+ expect(() =>
154
+ validateMediaGenerationSettings({
155
+ ...sized("bytedance/seedance-2.0"),
156
+ references: [ref("first-frame", "a"), ref("reference", "b")],
157
+ }),
158
+ ).toThrow(/cannot be mixed/);
159
+ });
160
+ });