@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,287 @@
1
+ import sharp from "sharp";
2
+ import { createMediaService } from "../src/server.js";
3
+ import * as Effect from "effect/Effect";
4
+ import { describe, expect, it, vi } from "vitest";
5
+ import {
6
+ createDailyMediaMetering,
7
+ DailyMediaMeter,
8
+ type DailyMediaMeterPort,
9
+ } from "../src/daily-media-meter.js";
10
+ import { executeMediaOperation } from "../src/media-operation.js";
11
+ import { MediaBillingRefusal } from "../src/execution-error.js";
12
+ import type { MediaOperationRequest } from "../src/media-operation-owner.js";
13
+ import { mediaOperationFixture as fixture } from "./fixtures/media-operation.fixture.js";
14
+
15
+ const DAY = 86_400_000;
16
+ const request: MediaOperationRequest = {
17
+ model: "@cf/black-forest-labs/flux-2-klein-4b",
18
+ prompt: "a quiet greenhouse",
19
+ width: 1_024,
20
+ height: 768,
21
+ computerId: "computer-a",
22
+ path: "generated/greenhouse.png",
23
+ };
24
+ const png = () =>
25
+ Promise.resolve({ bytes: new Uint8Array([1, 2, 3]), format: "png" });
26
+
27
+ /** The Durable Object's RPC surface over a real SQLite database and a movable clock. */
28
+ function meterFixture(start = 10 * DAY + 5_000) {
29
+ const test = fixture();
30
+ let now = start;
31
+ const meter = new DailyMediaMeter(test.storage, () => now);
32
+ const port: DailyMediaMeterPort = {
33
+ dailyAdmit: (input) => Promise.resolve(meter.admit(input)),
34
+ dailySettle: (input) => {
35
+ meter.settle(input);
36
+ return Promise.resolve();
37
+ },
38
+ };
39
+ return {
40
+ test,
41
+ port,
42
+ meter,
43
+ advance: (ms: number) => {
44
+ now += ms;
45
+ },
46
+ at: (timestamp: number) => {
47
+ now = timestamp;
48
+ },
49
+ };
50
+ }
51
+
52
+ function execute(
53
+ owner: ReturnType<typeof fixture>["owner"],
54
+ requestId: string,
55
+ metering: ReturnType<typeof createDailyMediaMetering>,
56
+ run: () => Promise<{ bytes: Uint8Array; format: string }>,
57
+ ) {
58
+ return Effect.runPromise(
59
+ executeMediaOperation({
60
+ operation: owner,
61
+ actorUserId: "actor-a",
62
+ coordinates: { namespace: "oyster", owner: "prints" },
63
+ requestId,
64
+ request,
65
+ metering,
66
+ destination: {
67
+ authorize: () => Promise.resolve(),
68
+ remove: () => Promise.resolve("absent" as const),
69
+ write: () => Promise.resolve(),
70
+ },
71
+ generation: {
72
+ prepare: () =>
73
+ Promise.resolve({
74
+ costMilliunits: 600,
75
+ references: [],
76
+ audioReferences: [],
77
+ run,
78
+ }),
79
+ },
80
+ }),
81
+ );
82
+ }
83
+
84
+ describe("daily media limit", () => {
85
+ it("admits up to the limit, refuses beyond it, and keeps the total exact", async () => {
86
+ const { port, test } = meterFixture();
87
+ const metering = createDailyMediaMetering(port, 1_000);
88
+ const admit = (operationId: string, providerCostMilliunits: number) =>
89
+ metering.admit({
90
+ operationId,
91
+ model: "m",
92
+ unit: "image",
93
+ units: 1,
94
+ providerCostMilliunits,
95
+ });
96
+ await expect(admit("a", 600)).resolves.toEqual({ priceMilliunits: 600 });
97
+ await expect(admit("b", 401)).rejects.toMatchObject({
98
+ code: "daily_limit_reached",
99
+ });
100
+ // The refusal held nothing: exactly the remainder is still available.
101
+ await expect(admit("b", 400)).resolves.toEqual({ priceMilliunits: 400 });
102
+ // A retried admit of the same operation never counts twice.
103
+ await expect(admit("a", 600)).resolves.toEqual({ priceMilliunits: 600 });
104
+ await expect(admit("c", 1)).rejects.toBeInstanceOf(MediaBillingRefusal);
105
+ test.close();
106
+ });
107
+
108
+ it("lets only one of two concurrent admits near the limit pass", async () => {
109
+ const { port, test } = meterFixture();
110
+ const metering = createDailyMediaMetering(port, 1_000);
111
+ const admit = (operationId: string) =>
112
+ metering.admit({
113
+ operationId,
114
+ model: "m",
115
+ unit: "image",
116
+ units: 1,
117
+ providerCostMilliunits: 600,
118
+ });
119
+ const results = await Promise.allSettled([admit("a"), admit("b")]);
120
+ expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
121
+ expect(results.filter((r) => r.status === "rejected")).toHaveLength(1);
122
+ test.close();
123
+ });
124
+
125
+ it("releases a hold on settle(0) and keeps it once delivered", async () => {
126
+ const { port, test } = meterFixture();
127
+ const metering = createDailyMediaMetering(port, 1_000);
128
+ const admit = (operationId: string, cost: number) =>
129
+ metering.admit({
130
+ operationId,
131
+ model: "m",
132
+ unit: "image",
133
+ units: 1,
134
+ providerCostMilliunits: cost,
135
+ });
136
+ await admit("a", 700);
137
+ await metering.settle({ operationId: "a", units: 0 });
138
+ await expect(admit("b", 1_000)).resolves.toBeDefined();
139
+ await metering.settle({ operationId: "b", units: 1 });
140
+ await expect(admit("c", 1)).rejects.toMatchObject({
141
+ code: "daily_limit_reached",
142
+ });
143
+ test.close();
144
+ });
145
+
146
+ it("starts a new total at 00:00 UTC", async () => {
147
+ const { port, test, at } = meterFixture();
148
+ const metering = createDailyMediaMetering(port, 1_000);
149
+ const admit = (operationId: string) =>
150
+ metering.admit({
151
+ operationId,
152
+ model: "m",
153
+ unit: "image",
154
+ units: 1,
155
+ providerCostMilliunits: 1_000,
156
+ });
157
+ at(11 * DAY - 1);
158
+ await admit("a");
159
+ await expect(admit("b")).rejects.toMatchObject({
160
+ code: "daily_limit_reached",
161
+ });
162
+ at(11 * DAY);
163
+ await expect(admit("b")).resolves.toBeDefined();
164
+ test.close();
165
+ });
166
+
167
+ it("refuses before any provider dispatch, then releases a failed run's hold", async () => {
168
+ const { port, test } = meterFixture();
169
+ const metering = createDailyMediaMetering(port, 1_000);
170
+ const run = vi.fn(png);
171
+ await execute(test.owner, "request-a", metering, run);
172
+ expect(run).toHaveBeenCalledOnce();
173
+ // 600 delivered; a second 600 would pass 1,000, so nothing is dispatched.
174
+ const second = fixture(
175
+ ":memory:",
176
+ new Map(),
177
+ undefined,
178
+ "media-operation-b",
179
+ );
180
+ const refused = vi.fn(png);
181
+ await expect(
182
+ execute(second.owner, "request-b", metering, refused),
183
+ ).rejects.toThrow("Media billing failed");
184
+ expect(refused).not.toHaveBeenCalled();
185
+ // A provider failure delivers nothing, so its hold is released.
186
+ const third = fixture(
187
+ ":memory:",
188
+ new Map(),
189
+ undefined,
190
+ "media-operation-c",
191
+ );
192
+ const meter = createDailyMediaMetering(port, 1_200);
193
+ const failing = vi.fn(() => Promise.reject(new Error("provider down")));
194
+ await expect(
195
+ execute(third.owner, "request-c", meter, failing),
196
+ ).rejects.toThrow();
197
+ const fourth = fixture(
198
+ ":memory:",
199
+ new Map(),
200
+ undefined,
201
+ "media-operation-d",
202
+ );
203
+ await expect(
204
+ execute(fourth.owner, "request-d", meter, vi.fn(png)),
205
+ ).resolves.toMatchObject({ kind: "succeeded" });
206
+ for (const each of [test, second, third, fourth]) each.close();
207
+ });
208
+ });
209
+
210
+ it.each([
211
+ ["admit", "Couldn't check today's spending limit. Try again."],
212
+ ["settle", "Couldn't record this generation's spending. Retry this request."],
213
+ ] as const)(
214
+ "names a daily meter %s RPC failure without exposing its private cause",
215
+ async (operation, message) => {
216
+ const test = fixture();
217
+ try {
218
+ const bytes = await sharp({
219
+ create: { width: 1024, height: 768, channels: 3, background: "white" },
220
+ })
221
+ .png()
222
+ .toBuffer();
223
+ const rpcError = new Error("synthetic-private-RPC-detail");
224
+ const provider = vi.fn(() => Promise.resolve({ bytes, format: "png" }));
225
+ const service = createMediaService({
226
+ scope: {
227
+ actorId: "artist",
228
+ namespace: "oyster",
229
+ owner: "prints",
230
+ destinationId: "computer-a",
231
+ },
232
+ operations: { getByName: () => test.owner },
233
+ provider,
234
+ metering: createDailyMediaMetering(
235
+ {
236
+ dailyAdmit: () =>
237
+ operation === "admit"
238
+ ? Promise.reject(rpcError)
239
+ : Promise.resolve(true),
240
+ dailySettle: () =>
241
+ operation === "settle"
242
+ ? Promise.reject(rpcError)
243
+ : Promise.resolve(),
244
+ },
245
+ 1000,
246
+ ),
247
+ refusalMessages: {
248
+ denied: "Daily limit reached.",
249
+ insufficient_credits: "Daily limit reached.",
250
+ daily_limit_reached: "Daily limit reached.",
251
+ },
252
+ destination: {
253
+ authorize: () => Promise.resolve(),
254
+ remove: () => Promise.resolve("absent" as const),
255
+ write: () => Promise.resolve(),
256
+ },
257
+ });
258
+ const response = await service.request("/generate", {
259
+ method: "POST",
260
+ headers: {
261
+ "Content-Type": "application/json",
262
+ "X-Request-Id": `daily-rpc-${operation}`,
263
+ },
264
+ body: JSON.stringify({
265
+ path: request.path,
266
+ settings: {
267
+ model: request.model,
268
+ prompt: request.prompt,
269
+ width: request.width,
270
+ height: request.height,
271
+ },
272
+ }),
273
+ });
274
+ expect(response.status).toBe(503);
275
+ const body = await response.json();
276
+ expect(body).toMatchObject({
277
+ code: "HOST_FAILURE",
278
+ stage: "billing",
279
+ error: message,
280
+ });
281
+ expect(JSON.stringify(body)).not.toContain(rpcError.message);
282
+ expect(provider).toHaveBeenCalledTimes(operation === "admit" ? 0 : 1);
283
+ } finally {
284
+ test.close();
285
+ }
286
+ },
287
+ );
@@ -0,0 +1,190 @@
1
+ import { inspect } from "node:util";
2
+ import * as Redacted from "effect/Redacted";
3
+ import { afterEach, expect, it, vi } from "vitest";
4
+ import { z } from "zod";
5
+ import { generate, type MediaAiPort } from "../src/cloudflare/provider.js";
6
+ import { validateMediaGenerationSettings } from "../src/index.js";
7
+ import { reportCatchFailure } from "../src/failure.js";
8
+
9
+ afterEach(() => vi.restoreAllMocks());
10
+
11
+ const marker = "synthetic-private-cause-marker";
12
+ const nested = new Error(`Nested I/O failure ${marker}`);
13
+ const failure = new Error(`Operation failed ${marker}`, { cause: nested });
14
+
15
+ it.each([failure, marker])(
16
+ "Media service reporter retains the redacted caught value (case %#)",
17
+ (cause) => {
18
+ const report = vi
19
+ .spyOn(console, "error")
20
+ .mockImplementation(() => undefined);
21
+ reportCatchFailure("fixture.read", cause);
22
+ expect(report).toHaveBeenCalledOnce();
23
+ const retained = report.mock.calls
24
+ .flatMap((args: unknown[]) => args)
25
+ .filter(Redacted.isRedacted)
26
+ .map(Redacted.value);
27
+ expect(retained).toHaveLength(1);
28
+ expect(retained[0]).toBe(cause);
29
+ if (retained[0] instanceof Error) {
30
+ expect(retained[0].cause).toBe(nested);
31
+ expect(retained[0].stack).toBe(failure.stack);
32
+ }
33
+ expect(JSON.stringify(report.mock.calls)).toContain("fixture.read");
34
+ expect(JSON.stringify(report.mock.calls)).not.toContain(marker);
35
+ expect(inspect(report.mock.calls, { depth: null })).not.toContain(marker);
36
+ expect(
37
+ report.mock.calls
38
+ .flatMap((args: unknown[]) => args)
39
+ .map(String)
40
+ .join(" "),
41
+ ).not.toContain(marker);
42
+ },
43
+ );
44
+
45
+ it.each(["@cf/black-forest-labs/flux-1-schnell", "openai/gpt-image-2"])(
46
+ "provider reporter retains its original failure for %s",
47
+ async (model) => {
48
+ const report = vi
49
+ .spyOn(console, "error")
50
+ .mockImplementation(() => undefined);
51
+ const run = vi.fn<MediaAiPort["run"]>().mockRejectedValue(failure);
52
+ const settings = validateMediaGenerationSettings({
53
+ model,
54
+ prompt: "fixture",
55
+ width: 1024,
56
+ height: 1024,
57
+ });
58
+ await expect(generate({ run }, settings, [])).rejects.toMatchObject({
59
+ name: "MediaExecutionError",
60
+ stage: "provider",
61
+ cause: failure,
62
+ });
63
+ const retained = report.mock.calls
64
+ .flatMap((args: unknown[]) => args)
65
+ .filter(Redacted.isRedacted)
66
+ .map(Redacted.value);
67
+ expect(retained).toEqual([failure]);
68
+ expect(retained[0]).toBe(failure);
69
+ expect(JSON.stringify(report.mock.calls)).toContain(
70
+ "Media provider request failed",
71
+ );
72
+ expect(inspect(report.mock.calls, { depth: null })).not.toContain(marker);
73
+ expect(JSON.stringify(report.mock.calls)).not.toContain(marker);
74
+ },
75
+ );
76
+
77
+ it("keeps an ordinary 8007 failure opaque instead of treating its number as a safety verdict", async () => {
78
+ const report = vi.spyOn(console, "error").mockImplementation(() => undefined);
79
+ const cause = new Error(`8007: AiError: upstream unavailable ${marker}`);
80
+ const run = vi.fn<MediaAiPort["run"]>().mockRejectedValue(cause);
81
+ const settings = validateMediaGenerationSettings({
82
+ model: "@cf/black-forest-labs/flux-1-schnell",
83
+ prompt: "fixture",
84
+ width: 1024,
85
+ height: 768,
86
+ });
87
+ await expect(generate({ run }, settings, [])).rejects.toMatchObject({
88
+ name: "MediaExecutionError",
89
+ stage: "provider",
90
+ cause,
91
+ });
92
+ expect(JSON.stringify(report.mock.calls)).toContain('"providerCode":8007');
93
+ expect(inspect(report.mock.calls, { depth: null })).not.toContain(marker);
94
+ });
95
+
96
+ it("recognizes the captured Flux output rejection without treating 3030 as transient", async () => {
97
+ const report = vi.spyOn(console, "error").mockImplementation(() => undefined);
98
+ // Exact upstream message observed in the retained Prints request's REST
99
+ // replay, 2026-10-29. Workers AI prefixes binding errors with the code.
100
+ const cause = new Error(
101
+ "3030: AiError: AiError: Your output has been flagged. Please choose another prompt / input image combination (5dbf4c51-d344-437d-b202-7bdd4310a043)",
102
+ );
103
+ const run = vi.fn<MediaAiPort["run"]>().mockRejectedValue(cause);
104
+ const settings = validateMediaGenerationSettings({
105
+ model: "@cf/black-forest-labs/flux-2-klein-4b",
106
+ prompt: "This little guy dunking a baskettball",
107
+ width: 1280,
108
+ height: 720,
109
+ });
110
+ await expect(generate({ run }, settings, [])).rejects.toMatchObject({
111
+ name: "MediaSafetyFilterRefusal",
112
+ stage: "provider",
113
+ cause,
114
+ provider: { code: 3030 },
115
+ });
116
+ expect(run).toHaveBeenCalledOnce();
117
+ expect(report).toHaveBeenCalledWith(
118
+ "Media provider request failed",
119
+ expect.objectContaining({
120
+ model: settings.model,
121
+ providerCode: 3030,
122
+ category: "Error",
123
+ providerMessage: cause.message,
124
+ }),
125
+ expect.anything(),
126
+ );
127
+ });
128
+
129
+ it("retries documented capacity exhaustion once with a fresh multipart stream, then stops", async () => {
130
+ // https://developers.cloudflare.com/workers-ai/platform/errors/
131
+ // 3040: "Capacity temporarily exceeded, please try again."
132
+ const diagnostic = vi
133
+ .spyOn(console, "error")
134
+ .mockImplementation(() => undefined);
135
+ const bodies: FormData[] = [];
136
+ const multipart = z.object({
137
+ multipart: z.object({
138
+ body: z.instanceof(ReadableStream),
139
+ contentType: z.string(),
140
+ }),
141
+ });
142
+ const run = vi.fn<MediaAiPort["run"]>(async (_model, input) => {
143
+ const checked = multipart.parse(input).multipart;
144
+ bodies.push(
145
+ await new Response(checked.body, {
146
+ headers: { "Content-Type": checked.contentType },
147
+ }).formData(),
148
+ );
149
+ throw new Error("3040: Capacity temporarily exceeded, please try again.");
150
+ });
151
+ const settings = validateMediaGenerationSettings({
152
+ model: "@cf/black-forest-labs/flux-2-klein-4b",
153
+ prompt: "a mushroom on a basketball court",
154
+ width: 1024,
155
+ height: 768,
156
+ });
157
+ await expect(generate({ run }, settings, [])).rejects.toMatchObject({
158
+ stage: "provider",
159
+ provider: { code: 3040 },
160
+ });
161
+ expect(run).toHaveBeenCalledTimes(2);
162
+ expect(diagnostic).toHaveBeenCalledOnce();
163
+ expect(bodies).toHaveLength(2);
164
+ for (const body of bodies) {
165
+ expect(body.get("prompt")).toBe("a mushroom on a basketball court");
166
+ expect(body.get("width")).toBe("1024");
167
+ expect(body.get("height")).toBe("768");
168
+ }
169
+ });
170
+
171
+ it.each([3030, 3043, 3007, 3008])(
172
+ "does not infer automatic retry permission from provider code %i",
173
+ async (code) => {
174
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
175
+ const run = vi
176
+ .fn<MediaAiPort["run"]>()
177
+ .mockRejectedValue(new Error(`${String(code)}: upstream details`));
178
+ const settings = validateMediaGenerationSettings({
179
+ model: "@cf/black-forest-labs/flux-2-klein-4b",
180
+ prompt: "a mushroom on a basketball court",
181
+ width: 1024,
182
+ height: 768,
183
+ });
184
+ await expect(generate({ run }, settings, [])).rejects.toMatchObject({
185
+ name: "MediaExecutionError",
186
+ provider: { code },
187
+ });
188
+ expect(run).toHaveBeenCalledOnce();
189
+ },
190
+ );
@@ -0,0 +1,10 @@
1
+ /** Minimal Node test host for importing Darkroom's Cloudflare-only module. */
2
+ export class DurableObject<Env> {
3
+ protected readonly ctx: DurableObjectState;
4
+ protected readonly env: Env;
5
+
6
+ public constructor(ctx: DurableObjectState, env: Env) {
7
+ this.ctx = ctx;
8
+ this.env = env;
9
+ }
10
+ }
@@ -0,0 +1,134 @@
1
+ import * as Schema from "effect/Schema";
2
+ import { vi } from "vitest";
3
+ import { createNativeSqliteFixture } from "./native-sqlite.fixture.js";
4
+ import type { MediaErasureMarker } from "../../src/media-operation-storage.js";
5
+ import {
6
+ MediaOperationOwner,
7
+ type MediaOperationHooks,
8
+ } from "../../src/media-operation-owner.js";
9
+ import {
10
+ createWorkersAiMediaProvider,
11
+ type MediaAiPort,
12
+ } from "../../src/cloudflare/provider.js";
13
+
14
+ export function mediaOperationFixture(
15
+ databasePath = ":memory:",
16
+ outputs = new Map<string, Uint8Array>(),
17
+ ai?: MediaAiPort,
18
+ objectName = "media-operation-a",
19
+ hooks: MediaOperationHooks = {},
20
+ ) {
21
+ const native = createNativeSqliteFixture(databasePath);
22
+ const kv = new Map<string, unknown>();
23
+ let alarm: number | null = null;
24
+ const metadata = new Map<string, Record<string, string>>();
25
+ const bucket = {
26
+ put: (
27
+ key: string,
28
+ value: Uint8Array,
29
+ options?: { customMetadata?: Record<string, string> },
30
+ ) => {
31
+ if (outputs.has(key)) return Promise.resolve(null);
32
+ const bytes = value.slice();
33
+ outputs.set(key, bytes);
34
+ if (options?.customMetadata) metadata.set(key, options.customMetadata);
35
+ return Promise.resolve({
36
+ key,
37
+ version: "version-1",
38
+ size: bytes.byteLength,
39
+ });
40
+ },
41
+ head: (key: string) => {
42
+ const bytes = outputs.get(key);
43
+ return Promise.resolve(
44
+ bytes === undefined
45
+ ? null
46
+ : {
47
+ key,
48
+ version: "version-1",
49
+ size: bytes.byteLength,
50
+ httpMetadata: { contentType: "image/png" },
51
+ },
52
+ );
53
+ },
54
+ get: (key: string) => {
55
+ const bytes = outputs.get(key);
56
+ return Promise.resolve(
57
+ bytes === undefined
58
+ ? null
59
+ : {
60
+ key,
61
+ version: "version-1",
62
+ size: bytes.byteLength,
63
+ customMetadata: metadata.get(key) ?? {},
64
+ arrayBuffer: () => Promise.resolve(bytes.slice().buffer),
65
+ },
66
+ );
67
+ },
68
+ delete: (key: string) => {
69
+ outputs.delete(key);
70
+ metadata.delete(key);
71
+ return Promise.resolve();
72
+ },
73
+ };
74
+ const state = {
75
+ id: { name: objectName },
76
+ storage: {
77
+ sql: native.storage.sql,
78
+ transactionSync: native.storage.transactionSync,
79
+ isErased: () => Promise.resolve(kv.get("botanical:erased") === true),
80
+ markErased: (marker: MediaErasureMarker) => {
81
+ kv.set("botanical:erased-details", marker);
82
+ kv.set("botanical:erased", true);
83
+ return Promise.resolve();
84
+ },
85
+ readErasureMarker: () =>
86
+ Promise.resolve(
87
+ Schema.decodeUnknownSync(
88
+ Schema.UndefinedOr(
89
+ Schema.Struct({
90
+ destinationPath: Schema.NullOr(Schema.String),
91
+ writtenSha256: Schema.NullOr(Schema.String),
92
+ abandonedGeneration: Schema.Boolean,
93
+ }),
94
+ ),
95
+ )(kv.get("botanical:erased-details")) ?? null,
96
+ ),
97
+ listKeys: () => Promise.resolve([...kv.keys()]),
98
+ deleteAlarm: () => {
99
+ alarm = null;
100
+ return Promise.resolve();
101
+ },
102
+ deleteKeys: (keys: readonly string[]) => {
103
+ for (const key of keys) kv.delete(key);
104
+ return Promise.resolve();
105
+ },
106
+ getAlarm: () => Promise.resolve(alarm),
107
+ setAlarm: (value: number) => {
108
+ alarm = value;
109
+ return Promise.resolve();
110
+ },
111
+ },
112
+ blockConcurrencyWhile: <T>(body: () => T | Promise<T>) =>
113
+ Promise.resolve(body()),
114
+ };
115
+
116
+ const artifacts = bucket;
117
+ const owner = new MediaOperationOwner(
118
+ state,
119
+ { APP_ARTIFACTS: artifacts },
120
+ ai === undefined
121
+ ? undefined
122
+ : () =>
123
+ createWorkersAiMediaProvider(ai, { gateway: { id: "fungi-hub" } }),
124
+ hooks,
125
+ );
126
+ return {
127
+ owner,
128
+ context: state,
129
+ storage: native.storage,
130
+ bucket,
131
+ advance: (milliseconds: number) => vi.advanceTimersByTime(milliseconds),
132
+ close: native.close,
133
+ };
134
+ }
@@ -0,0 +1,7 @@
1
+ /** The media team's real prompts, copied byte for byte from the CTO review (Nov 13), Â artifact included. */
2
+ export const dreamGardenPrompt =
3
+ "Late-90s shonen anime cel animation, bold black linework, flat color blocks, subtle VHS film grain. Dreamlike, lucid, slightly surreal: oversized plants, impossible scale, floating glowing spores, soft pastel light with no clear source. Palette of deep emerald, hot pink, teal, violet and pale gold. Hand-painted anime background detail. No photorealism, no 3D render, no smooth CGI, no text, no music. \n\n@image1 = Jesse: 18-year-old young man, slim build, messy spiky dark-brown hair, warm brown eyes, tan skin. Plain white t-shirt with a faded pink graphic on the chest, loose blue cargo jeans, white sneakers with blue stripes.\n\n@image2 = DREAM GARDEN. Scene reference. \n\n\n\nAUDIO: The soft, warm, shimmering chime continues, held long. Jesse's slow, quiet breath catching in wonder. Faint sparkling spores. No dialogue, no music.\nExtreme close-up of [JESSE]'s face, the reverse angle from the leaves, the camera at ground level looking straight back at him. His face fills the vertical frame from his eyebrows to his chin, a few messy dark-brown strands of hair at the top edge. He lies low on the moss, propped on his elbows, his gaze fixed just past the lens, slightly upward, in wonder and awe. His mouth hangs open, his eyes wide and shining. A tiny, warm pink and golden glow from just in front of him lights his face softly from below, with small warm highlights reflected in his brown irises. Soft teal light from the leaves edges his cheek. A few glowing golden spores drift slowly across the foreground, out of focus.\nBackground: dark, blurred teal and violet foliage.\nCamera movement: static, with an almost imperceptible slow push-in.\nDuration: 3 seconds. [STYLE: DREAM GARDEN]";
4
+ export const rallyWreckPrompt =
5
+ "Late-90s shonen anime cel animation, bold black linework, flat saturated color blocks, minimal soft blending, subtle VHS film grain. Bright, clean, directional light. No photorealism, no 3D render, no smooth CGI, no yellow haze, no text, no logos, no music.\u00c2\n\n@image1 = Jesse: 18-year-old young man, slim build, messy spiky dark-brown hair, warm brown eyes, tan skin. Plain white t-shirt with a faded pink graphic on the chest, loose blue cargo jeans, white sneakers with blue stripes.\n\n@image2 = Jesse's car: a small, white, boxy 1980s three-door hatchback rally car, upright square body, wide box fender flares, round headlights, mud-splattered.\n\n@image3 = Scene and frame reference \n\nAUDIO: A low hiss of smoke and steam from the engine, slow ticking and creaking of cooling metal. Faint, muffled rally engines in the far distance. Low wind. No music, no dialogue.\nStatic camera, no movement at all. Low-angle shot from ground level, the camera resting in the dirt.\nForeground, filling the left half of the vertical frame: the wrecked white rally car lying upside down on its roof, close to the camera, its front end facing us. A boxy 1980s hatchback with wide box fender flares, a round amber headlight and a mud-splattered white body, its exposed underside, suspension and engine parts facing up. All four wheels are still attached, motionless. A single thick column of grey smoke rises slowly and steadily from the engine bay, drifting upward and gently across the sky.\nBackground, right side of the frame: [JESSE] lies flat on his back in the open churned dirt a few yards away, arms spread out, completely still, eyes closed, dusty, his white t-shirt and blue cargo jeans dirty. Clear line of sight to him; nothing blocks him.\nThe scene is settled and quiet after the crash: the dust has already fallen, nothing is in the air except the rising smoke. No flying debris, no loose or detached wheels, no tires, no rocks or dirt clods in the air, no other cars in the frame. The only motion is the slow smoke and a light breeze.\nFlat overcast daylight, pale grey sky. Ominous and still.";
6
+ export const dinerPrompt =
7
+ "@image1 =Scene and character reference\n@image2 =Character reference\n@image3 =Character reference\n@image4 =Scene reference. 90's diner.\n\nShot should look like @image1. @image3 continues to talk, \"And then there's the whole time travel shit. Like, wouldn't organic matter be the hardest shit to send back? And they couldn't send him with any clothes?!\"";
@@ -0,0 +1,40 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import type { MediaOperationStorage } from "../../src/media-operation-storage.js";
3
+
4
+ /**
5
+ * A real node:sqlite database behind the Workers-shaped synchronous SQL
6
+ * capability Darkroom's owners use. It lives in Darkroom so the tests run from
7
+ * the published package as well as from the repository.
8
+ */
9
+ export function createNativeSqliteFixture(databasePath = ":memory:") {
10
+ const database = new DatabaseSync(databasePath);
11
+ database.exec("PRAGMA foreign_keys = ON");
12
+ const storage: Pick<MediaOperationStorage, "sql" | "transactionSync"> = {
13
+ sql: {
14
+ exec: (statement, ...bindings) => {
15
+ const prepared = database.prepare(statement);
16
+ const rows = /^\s*(?:SELECT|PRAGMA|WITH)\b/iu.test(statement)
17
+ ? prepared.all(...bindings).map((row) => ({ ...row }))
18
+ : (prepared.run(...bindings), []);
19
+ return { toArray: () => rows };
20
+ },
21
+ },
22
+ transactionSync: (body) => {
23
+ database.exec("BEGIN");
24
+ try {
25
+ const result = body();
26
+ database.exec("COMMIT");
27
+ return result;
28
+ } catch (error) {
29
+ database.exec("ROLLBACK");
30
+ throw error;
31
+ }
32
+ },
33
+ };
34
+ return {
35
+ storage,
36
+ close: () => {
37
+ database.close();
38
+ },
39
+ };
40
+ }