The best way to control Claude Code, Codex and more from any computer or phone

main
ts 367 lines 13.3 KB
Raw
1 import * as images from "@distilled.cloud/cloudflare/images";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Schedule from "effect/Schedule";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Images.Variant" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * How an image is resized to fit a variant's `width`x`height` box.
17 */
18 export type VariantFit = "scale-down" | "contain" | "cover" | "crop" | "pad";
19
20 /**
21 * What happens to the image's EXIF metadata when the variant is served.
22 */
23 export type VariantMetadata = "keep" | "copyright" | "none";
24
25 export interface VariantProps {
26 /**
27 * Account the variant is created in. Defaults to the ambient Cloudflare
28 * account. Changing it triggers a replacement.
29 */
30 accountId?: string;
31 /**
32 * Variant name — the URL segment used to request the variant (e.g.
33 * `https://imagedelivery.net/<hash>/<image>/<name>`). Alphanumeric only;
34 * Cloudflare rejects hyphens and underscores.
35 *
36 * Defaults to the logical ID verbatim (variant names are user-facing URL
37 * segments, so no uniqueness suffix is appended). Changing the name
38 * triggers a replacement — the API cannot rename a variant.
39 *
40 * @default the logical ID
41 */
42 name?: string;
43 /**
44 * How the image is resized to fit the `width`x`height` box. Mutable.
45 */
46 fit: VariantFit;
47 /**
48 * Maximum width in pixels (1-9999). Mutable.
49 */
50 width: number;
51 /**
52 * Maximum height in pixels (1-9999). Mutable.
53 */
54 height: number;
55 /**
56 * What EXIF metadata is preserved on the served image. Mutable.
57 * @default "none"
58 */
59 metadata?: VariantMetadata;
60 /**
61 * If `true`, this variant can serve an image without a signed URL even
62 * when the image itself requires signed URLs. Mutable.
63 * @default false
64 */
65 neverRequireSignedURLs?: boolean;
66 }
67
68 export interface VariantAttributes {
69 /** The variant's name (its API path identifier and URL segment). */
70 variantName: string;
71 /** Account the variant belongs to. */
72 accountId: string;
73 /** How the image is resized. */
74 fit: VariantFit;
75 /** Maximum width in pixels. */
76 width: number;
77 /** Maximum height in pixels. */
78 height: number;
79 /** EXIF metadata handling. */
80 metadata: VariantMetadata;
81 /** Whether the variant bypasses signed-URL requirements. */
82 neverRequireSignedURLs: boolean;
83 }
84
85 export type Variant = Resource<TypeId, VariantProps, VariantAttributes, never, Providers>;
86
87 /**
88 * A Cloudflare Images variant — a named resizing preset (e.g. `thumbnail`,
89 * `hero`) applied when serving images from Cloudflare Images.
90 *
91 * A variant is identified by its name within an account (up to 100 variants
92 * per account). The name is the URL segment used to request the variant, so
93 * it is immutable — changing it triggers a replacement. All resizing options
94 * (`fit`, `width`, `height`, `metadata`, `neverRequireSignedURLs`) are
95 * mutable in place.
96 *
97 * Note: every Images-enabled account has a built-in `public` variant. Do not
98 * manage `public` with this resource — Cloudflare silently ignores deletes
99 * of the built-in variant, so destroy would not actually remove it.
100 * ### Creating a Variant
101 * **Example:** Thumbnail variant
102 * ```typescript
103 * // Variant names are alphanumeric only (no hyphens/underscores).
104 * const thumbnail = yield* Cloudflare.Images.Variant("thumbnail", {
105 * fit: "cover",
106 * width: 100,
107 * height: 100,
108 * });
109 * ```
110 *
111 * **Example:** Hero variant with explicit name and metadata
112 * ```typescript
113 * const hero = yield* Cloudflare.Images.Variant("HeroImage", {
114 * name: "hero",
115 * fit: "scale-down",
116 * width: 1920,
117 * height: 1080,
118 * metadata: "copyright",
119 * });
120 * ```
121 *
122 * ### Signed URLs
123 * **Example:** Public variant for protected images
124 * ```typescript
125 * // Serve this variant without a signature even when the image itself
126 * // requires signed URLs (e.g. for public thumbnails of private images).
127 * const preview = yield* Cloudflare.Images.Variant("preview", {
128 * fit: "contain",
129 * width: 320,
130 * height: 240,
131 * neverRequireSignedURLs: true,
132 * });
133 * ```
134 *
135 * @see https://developers.cloudflare.com/images/manage-images/create-variants/
136 *
137 * @resource
138 * @product Images
139 * @category Media
140 */
141 export const Variant = Resource<Variant>(TypeId);
142
143 /**
144 * Returns true if the given value is an Variant resource.
145 */
146 export const isVariant = (value: unknown): value is Variant =>
147 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
148
149 export const VariantProvider = () =>
150 Provider.succeed(Variant, {
151 stables: ["variantName", "accountId"],
152
153 list: Effect.fn(function* () {
154 const { accountId } = yield* yield* CloudflareEnvironment;
155
156 // Enumerate variant names from the account-scoped list endpoint, then
157 // hydrate each via the per-variant GET (whose schema is correct) into
158 // the exact `read` Attributes shape.
159 //
160 // NOTE: distilled mis-types this response as a single variant, but the
161 // real body is a keyed `variants` map — so the strict decode currently
162 // fails. The fix is a distilled response-schema patch (see neededPatch
163 // in the agent report); once applied, the successful-decode path below
164 // works unchanged.
165 const names = yield* images.listV1Variants({ accountId }).pipe(
166 Effect.map(variantNamesFrom),
167 // The built-in `public` variant is not managed by this resource —
168 // Cloudflare silently ignores deletes of it (the DELETE returns 200
169 // but the variant persists), so exclude it from enumeration.
170 Effect.map((all) => all.filter((name) => name !== "public")),
171 // Accounts without the Cloudflare Images entitlement reject the route
172 // (code 5403) — there is nothing to enumerate.
173 Effect.catchTag("ImagesAccessNotEnabled", () => Effect.succeed<string[]>([])),
174 );
175
176 const rows = yield* Effect.forEach(
177 names,
178 (name) =>
179 getVariant(accountId, name).pipe(
180 Effect.map((variant) => (variant ? toAttributes(variant, accountId) : undefined)),
181 ),
182 { concurrency: 10 },
183 );
184
185 return rows.filter((row): row is VariantAttributes => row !== undefined);
186 }),
187
188 diff: Effect.fn(function* ({ id, olds, news, output }) {
189 // News may still contain unresolved plan-time expressions — defer to
190 // the engine's default update logic until everything is concrete.
191 if (!isResolved(news)) return undefined;
192 // The variant name is its API path identifier — it cannot be renamed.
193 const oldName = output?.variantName ?? olds?.name ?? id;
194 if ((news.name ?? id) !== oldName) {
195 return { action: "replace" } as const;
196 }
197 // Moving accounts replaces. accountId is an Input — compare only once
198 // both sides are concrete strings.
199 if (
200 typeof olds?.accountId === "string" &&
201 typeof news.accountId === "string" &&
202 olds.accountId !== news.accountId
203 ) {
204 return { action: "replace" } as const;
205 }
206 if (
207 output?.accountId !== undefined &&
208 typeof news.accountId === "string" &&
209 news.accountId !== output.accountId
210 ) {
211 return { action: "replace" } as const;
212 }
213 return undefined;
214 }),
215
216 read: Effect.fn(function* ({ id, output, olds }) {
217 const { accountId } = yield* yield* CloudflareEnvironment;
218 const acct = output?.accountId ?? (olds?.accountId as string | undefined) ?? accountId;
219 const name = output?.variantName ?? olds?.name ?? id;
220
221 const observed = yield* getVariant(acct, name);
222 if (!observed) return undefined;
223 const attrs = toAttributes(observed, acct);
224 // Variants carry no ownership markers. With no prior output we cannot
225 // prove we created a same-named variant — report it `Unowned` so the
226 // engine gates takeover behind the adopt policy.
227 return output?.variantName ? attrs : Unowned(attrs);
228 }),
229
230 reconcile: Effect.fn(function* ({ id, news }) {
231 const { accountId } = yield* yield* CloudflareEnvironment;
232 // Inputs have been resolved to concrete strings by Plan.
233 const acct = (news.accountId as string | undefined) ?? accountId;
234 const name = news.name ?? id;
235
236 // 1. Observe — cloud state is authoritative. The cached output is only
237 // a hint; a missing variant falls through to create.
238 let observed = yield* getVariant(acct, name);
239
240 // 2. Ensure — create when missing. A concurrent create surfaces as
241 // `VariantAlreadyExists` (Cloudflare code 5409): converge by
242 // re-reading the variant that won the race.
243 if (!observed) {
244 observed = yield* images
245 .createV1Variant({
246 accountId: acct,
247 id: name,
248 options: desiredOptions(news),
249 neverRequireSignedURLs: news.neverRequireSignedURLs,
250 })
251 .pipe(
252 Effect.map((created) => created.variant ?? undefined),
253 Effect.catchTag("VariantAlreadyExists", () => getVariant(acct, name)),
254 );
255 }
256 if (!observed) {
257 // Create succeeded but neither the response body nor a re-read
258 // surfaced the variant — eventual-consistency blip; fail typed so
259 // the engine can retry the reconcile.
260 return yield* images.VariantNotFound.make({
261 code: 5401,
262 message: `variant ${name} not observable after create`,
263 });
264 }
265
266 // 3. Sync — diff observed options against desired; PATCH requires the
267 // full options struct, so send everything, but skip the API call
268 // entirely on a no-op.
269 const desired = desiredOptions(news);
270 const desiredSigned = news.neverRequireSignedURLs ?? false;
271 const dirty =
272 observed.options.fit !== desired.fit ||
273 observed.options.width !== desired.width ||
274 observed.options.height !== desired.height ||
275 observed.options.metadata !== desired.metadata ||
276 (observed.neverRequireSignedURLs ?? false) !== desiredSigned;
277
278 if (dirty) {
279 const patched = yield* images.patchV1Variant({
280 accountId: acct,
281 variantId: name,
282 options: desired,
283 neverRequireSignedURLs: desiredSigned,
284 });
285 observed = patched.variant ?? observed;
286 }
287
288 return toAttributes(observed, acct);
289 }),
290
291 delete: Effect.fn(function* ({ output }) {
292 yield* images
293 .deleteV1Variant({
294 accountId: output.accountId,
295 variantId: output.variantName,
296 })
297 .pipe(Effect.catchTag("VariantNotFound", () => Effect.void));
298
299 // Cloudflare's variant DELETE is eventually consistent: the GET
300 // endpoint keeps returning the variant for a short window after a
301 // successful delete. Confirm it is actually gone before reporting
302 // success, so the engine's replacement GC (which deletes the OLD
303 // generation as the new one is created) leaves a genuinely clean slate
304 // rather than an orphan that lingers past the caller's verification.
305 // Bounded — if it never clears we stop polling and proceed.
306 yield* getVariant(output.accountId, output.variantName).pipe(
307 Effect.repeat({
308 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(12)]),
309 until: (observed) => observed === undefined,
310 }),
311 );
312 }),
313 });
314
315 type ObservedVariant = NonNullable<images.GetV1VariantResponse["variant"]>;
316
317 /**
318 * Read a variant by name, mapping "gone" (`VariantNotFound` — Cloudflare
319 * error code 5401, or the envelope-less plain-text 404 the GET endpoint
320 * returns) to `undefined`.
321 */
322 const getVariant = (accountId: string, variantId: string) =>
323 images.getV1Variant({ accountId, variantId }).pipe(
324 Effect.map((response) => response.variant ?? undefined),
325 Effect.catchTag("VariantNotFound", () => Effect.undefined),
326 );
327
328 /**
329 * Extract variant names — the keys of the `variants` map — from a list-variants
330 * payload. The endpoint returns `result.variants` as a keyed object map of
331 * variantId -> variant (not an array), so accept either the unwrapped `result`
332 * (`{ variants: {...} }`) or the full raw body (`{ result: { variants: {...} } }`).
333 */
334 const variantNamesFrom = (value: unknown): string[] => {
335 const root =
336 Predicate.hasProperty(value, "result") &&
337 typeof value.result === "object" &&
338 value.result !== null
339 ? value.result
340 : value;
341 if (
342 Predicate.hasProperty(root, "variants") &&
343 typeof root.variants === "object" &&
344 root.variants !== null
345 ) {
346 return Object.keys(root.variants);
347 }
348 return [];
349 };
350
351 const desiredOptions = (news: VariantProps) => ({
352 fit: news.fit,
353 width: news.width,
354 height: news.height,
355 metadata: news.metadata ?? ("none" as const),
356 });
357
358 const toAttributes = (variant: ObservedVariant, accountId: string): VariantAttributes => ({
359 variantName: variant.id,
360 accountId,
361 // Distilled widens generated string enums to open unions (`string & {}`).
362 fit: variant.options.fit as VariantFit,
363 width: variant.options.width,
364 height: variant.options.height,
365 metadata: variant.options.metadata as VariantMetadata,
366 neverRequireSignedURLs: variant.neverRequireSignedURLs ?? false,
367 });