Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / cf-images.ts

1import 'server-only';
2import { getCloudflareContext } from '@opennextjs/cloudflare';
3import { env } from './env';
4
5// Cloudflare Images: server-side upload. Returns the canonical
6// imagedelivery.net URL using the `public` variant by default.
7
8type UploadResult = {
9 id: string;
10 publicUrl: string;
11 printUrl: string;
12};
13
14type UploadOptions = {
15 filename?: string;
16 metadata?: Record<string, string>;
17 requireSignedUrl?: boolean;
18};
19
20type HostedImages = {
21 upload(source: ReadableStream<Uint8Array>, options: {
22 filename: string;
23 metadata?: Record<string, string>;
24 requireSignedURLs?: boolean;
25 }): Promise<{ id: string }>;
26 image(id: string): {
27 bytes(): Promise<ReadableStream<Uint8Array> | null>;
28 delete(): Promise<boolean>;
29 };
30 list(options: { limit: number; cursor?: string }): Promise<{ images: CfImage[]; cursor?: string }>;
31};
32
33function hostedImages(): HostedImages | undefined {
34 if (!process.env.CLOUDFLARE_DEPLOYMENT_ENV) return;
35 const { IMAGES } = getCloudflareContext().env as { IMAGES?: { hosted?: HostedImages } };
36 if (!IMAGES?.hosted) throw new Error('Cloudflare hosted images binding is missing.');
37 return IMAGES.hosted;
38}
39
40export async function uploadImage(
41 source: Blob | Buffer | ArrayBuffer,
42 opts?: UploadOptions,
43): Promise<UploadResult> {
44 const blob = source instanceof Blob ? source : new Blob([source as BlobPart]);
45 const hosted = hostedImages();
46 const { id } = hosted
47 ? await hosted.upload(blob.stream(), {
48 filename: opts?.filename ?? 'upload.png',
49 metadata: opts?.metadata,
50 requireSignedURLs: opts?.requireSignedUrl,
51 })
52 : await uploadWithApi(blob, opts);
53 return { id, publicUrl: imageUrl(id), printUrl: imageUrl(id, 'print') };
54}
55
56async function uploadWithApi(blob: Blob, opts?: UploadOptions): Promise<{ id: string }> {
57 const form = new FormData();
58 form.append('file', blob, opts?.filename ?? 'upload.png');
59 if (opts?.metadata) form.append('metadata', JSON.stringify(opts.metadata));
60 if (opts?.requireSignedUrl) form.append('requireSignedURLs', 'true');
61
62 const url = `https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v1`;
63 const res = await fetch(url, {
64 method: 'POST',
65 headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` },
66 body: form,
67 });
68 const json = await res.json() as {
69 success: boolean;
70 errors?: { message: string }[];
71 result?: { id: string };
72 };
73 if (!json.success || !json.result) {
74 const msg = json.errors?.map(e => e.message).join('; ') ?? 'unknown error';
75 throw new Error(`CF Images upload failed: ${msg}`);
76 }
77 return json.result;
78}
79
80export function imageUrl(imageId: string, variant = 'public'): string {
81 return `https://imagedelivery.net/${env.cf.imagesHash()}/${imageId}/${variant}`;
82}
83
84/** High-res variant for Prodigi assets. 4096×4096 fit:contain. */
85export function printUrl(imageId: string): string {
86 return imageUrl(imageId, 'print');
87}
88
89/** The account's imagedelivery.net base, e.g. https://imagedelivery.net/<hash>.
90 * The hash is public (it appears in every delivered URL), so this is safe to
91 * hand to a client component for building image URLs. */
92export function deliveryBase(): string {
93 return `https://imagedelivery.net/${env.cf.imagesHash()}`;
94}
95
96export async function downloadOriginalImage(deliveredUrl: string): Promise<Buffer> {
97 const prefix = deliveryBase() + '/';
98 if (!deliveredUrl.startsWith(prefix)) throw new Error('This draft does not have an original in the studio image library.');
99 const [variant, ...segments] = deliveredUrl.slice(prefix.length).split('/').reverse();
100 if (!variant || !segments.length || segments.some(segment => !segment)) throw new Error('Invalid studio image URL.');
101 const id = segments.reverse().map(decodeURIComponent).join('/');
102 const hosted = hostedImages();
103 if (hosted) {
104 const bytes = await hosted.image(id).bytes();
105 if (!bytes) throw new Error('The original draft image could not be downloaded.');
106 return Buffer.from(await new Response(bytes).arrayBuffer());
107 }
108 const url = `https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v1/${encodeURIComponent(id)}/blob`;
109 const response = await fetch(url, { headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` }, cache: 'no-store' });
110 if (!response.ok) throw new Error('The original draft image could not be downloaded.');
111 return Buffer.from(await response.arrayBuffer());
112}
113
114export type CfImage = { id: string; uploaded?: string };
115
116/** Delete one image from Cloudflare Images by id. Idempotent: a 404 ("image
117 * not found") is treated as success — the goal state (image gone) is met. */
118export async function deleteImage(id: string): Promise<void> {
119 const hosted = hostedImages();
120 if (hosted) {
121 await hosted.image(id).delete();
122 return;
123 }
124 // CF image ids can contain '/', so we leave separators alone and only
125 // percent-escape pieces that aren't path-safe.
126 const safePath = id.split('/').map(encodeURIComponent).join('/');
127 const url = `https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v1/${safePath}`;
128 const res = await fetch(url, {
129 method: 'DELETE',
130 headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` },
131 });
132 if (res.status === 404) return;
133 type DelResp = { success?: boolean; errors?: { message: string }[] };
134 const json: DelResp = await res.json().catch((): DelResp => ({}));
135 if (!json.success) {
136 const msg = json.errors?.map(e => e.message).join('; ') ?? `HTTP ${res.status}`;
137 throw new Error(`CF Images delete failed: ${msg}`);
138 }
139}
140
141/** List every image in the Cloudflare Images account (v2, continuation-token
142 * paginated). Used by the admin CDN browser. Returns ids + upload time. */
143export async function listImages(): Promise<CfImage[]> {
144 const hosted = hostedImages();
145 const out: CfImage[] = [];
146 let token = '';
147 for (let guard = 0; guard < 200; guard++) {
148 if (hosted) {
149 const page = await hosted.list({ limit: 1000, cursor: token || undefined });
150 out.push(...page.images.map(({ id, uploaded }) => ({ id, uploaded })));
151 token = page.cursor ?? '';
152 if (!token || page.images.length === 0) break;
153 continue;
154 }
155 const url = new URL(`https://api.cloudflare.com/client/v4/accounts/${env.cf.accountId()}/images/v2`);
156 url.searchParams.set('per_page', '1000');
157 if (token) url.searchParams.set('continuation_token', token);
158 const res = await fetch(url, {
159 headers: { Authorization: `Bearer ${env.cf.imagesApiToken()}` },
160 cache: 'no-store',
161 });
162 const json = await res.json() as {
163 success: boolean;
164 errors?: { message: string }[];
165 result?: { images?: CfImage[]; continuation_token?: string };
166 };
167 if (!json.success || !json.result) {
168 const msg = json.errors?.map(e => e.message).join('; ') ?? 'unknown error';
169 throw new Error(`CF Images list failed: ${msg}`);
170 }
171 const batch = json.result.images ?? [];
172 out.push(...batch.map(im => ({ id: im.id, uploaded: im.uploaded })));
173 token = json.result.continuation_token ?? '';
174 if (!token || batch.length === 0) break;
175 }
176 return out;
177}