-
Notifications
You must be signed in to change notification settings - Fork 988
Add configurable Cloudflare image transforms #1390
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
30fdfb5
feat(media): add configurable image transforms
mvvmm 2fa2930
fix(cloudflare): narrow Images binding safely
mvvmm 4c8012a
style: format
emdashbot[bot] 5cdf263
chore: rerun CI
mvvmm 29640dc
fix(media): stream image transform input
mvvmm 6ed3a7e
test(e2e): dismiss onboarding after loading
mvvmm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| "emdash": minor | ||
| "@emdash-cms/cloudflare": minor | ||
| --- | ||
|
|
||
| Add configurable media transforms for files served by EmDash, with a Cloudflare Images adapter that resizes uploaded images on demand and gracefully falls back to the original file when transforms fail. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import { env } from "cloudflare:workers"; | ||
| import type { CreateMediaTransformFn } from "emdash/media"; | ||
|
|
||
| import type { CloudflareImageTransformsConfig } from "./image-transforms.js"; | ||
|
|
||
| const DEFAULT_TIMEOUT_MS = 10000; | ||
| const DEFAULT_WIDTH = 1600; | ||
| const DEFAULT_MAX_WIDTH = 2400; | ||
| const DEFAULT_QUALITY = 85; | ||
|
|
||
| function imageFormatForRequest(request: Request): "image/avif" | "image/webp" { | ||
| const accept = request.headers.get("accept") || ""; | ||
| const avifAccepted = accept.split(",").some((part) => { | ||
| const [mediaType, ...params] = part.split(";").map((value) => value.trim().toLowerCase()); | ||
| if (mediaType !== "image/avif") return false; | ||
| const quality = params.find((param) => param.startsWith("q=")); | ||
| if (!quality) return true; | ||
| const value = Number(quality.slice(2)); | ||
| return !Number.isFinite(value) || value > 0; | ||
| }); | ||
| return avifAccepted ? "image/avif" : "image/webp"; | ||
| } | ||
|
|
||
| function imageWidthForRequest(request: Request, defaultWidth: number, maxWidth: number): number { | ||
| const width = Number(new URL(request.url).searchParams.get("width")); | ||
| if (!Number.isFinite(width) || width <= 0) return defaultWidth; | ||
| return Math.min(Math.round(width), maxWidth); | ||
| } | ||
|
|
||
| async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> { | ||
| let timeoutId: ReturnType<typeof setTimeout> | undefined; | ||
| const timeout = new Promise<never>((_, reject) => { | ||
| timeoutId = setTimeout(() => reject(new Error("Image transform timed out")), timeoutMs); | ||
| }); | ||
| try { | ||
| return await Promise.race([promise, timeout]); | ||
| } finally { | ||
| clearTimeout(timeoutId); | ||
| } | ||
| } | ||
|
|
||
| function getImagesBinding(binding: string): ImagesBinding | undefined { | ||
| // eslint-disable-next-line typescript/no-unsafe-type-assertion -- Workers bindings are exposed through an untyped env object. | ||
| const value = (env as Record<string, unknown>)[binding]; | ||
| if (!isImagesBinding(value)) return undefined; | ||
| return value; | ||
| } | ||
|
|
||
| function isImagesBinding(value: unknown): value is ImagesBinding { | ||
| return ( | ||
| typeof value === "object" && | ||
| value !== null && | ||
| "input" in value && | ||
| typeof value.input === "function" | ||
| ); | ||
| } | ||
|
|
||
| export const createMediaTransform: CreateMediaTransformFn<CloudflareImageTransformsConfig> = ( | ||
| config, | ||
| ) => { | ||
| const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS; | ||
| const defaultWidth = config.defaultWidth ?? DEFAULT_WIDTH; | ||
| const maxWidth = config.maxWidth ?? DEFAULT_MAX_WIDTH; | ||
| const quality = config.quality ?? DEFAULT_QUALITY; | ||
|
|
||
| return async ({ body, request }) => { | ||
| const images = getImagesBinding(config.binding); | ||
| if (!images) return null; | ||
|
|
||
| const transformed = await withTimeout( | ||
| images | ||
| .input(body) | ||
| .transform({ | ||
| fit: "scale-down", | ||
| width: imageWidthForRequest(request, defaultWidth, maxWidth), | ||
| }) | ||
| .output({ | ||
| format: imageFormatForRequest(request), | ||
| quality, | ||
| }), | ||
| timeoutMs, | ||
| ); | ||
|
|
||
| return { | ||
| body: transformed.image(), | ||
| contentType: transformed.contentType(), | ||
| headers: { Vary: "Accept" }, | ||
| }; | ||
| }; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import type { MediaTransformDescriptor } from "emdash"; | ||
|
|
||
| export interface CloudflareImageTransformsConfig { | ||
| /** Name of the Images binding in wrangler.jsonc. */ | ||
| binding: string; | ||
| /** Maximum time to wait for a transformation before serving the original file. */ | ||
| timeoutMs?: number; | ||
| /** Default resize width when the request does not include a valid `?width=`. */ | ||
| defaultWidth?: number; | ||
| /** Maximum allowed resize width. */ | ||
| maxWidth?: number; | ||
| /** Output quality passed to Cloudflare Images. */ | ||
| quality?: number; | ||
| } | ||
|
|
||
| export const CLOUDFLARE_IMAGE_TRANSFORM_TYPES = [ | ||
| "image/jpeg", | ||
| "image/png", | ||
| "image/webp", | ||
| "image/avif", | ||
| ]; | ||
|
|
||
| export function cloudflareImageTransforms( | ||
| config: CloudflareImageTransformsConfig, | ||
| ): MediaTransformDescriptor { | ||
| return { | ||
| entrypoint: "@emdash-cms/cloudflare/media/image-transforms", | ||
| config, | ||
| contentTypes: CLOUDFLARE_IMAGE_TRANSFORM_TYPES, | ||
| }; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.