Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/rotten-lions-scream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astrojs/cloudflare': patch
---

Fixes remote images without a file extension failing with `400 Unsupported format: null` when using the `cloudflare-binding` image service

Astro only adds the `f` (format) parameter to `/_image` URLs when it can infer a format from the source, and otherwise leaves it off so the image service resolves the format from the source itself. Extensionless remote images, such as GitHub avatars like `https://avatars.githubusercontent.com/u/1234`, take that path. The image transform endpoint now falls back to the source's media type when `f` is absent, passing SVG sources through unchanged and encoding everything else as WebP. This also fixes SVG images, which are requested as `f=svg` and previously failed the same way.
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,26 @@ const qualityTable: Record<ImageQualityPreset, number> = {

const defaultQuality = 85;

const SVG_CONTENT_TYPE = 'image/svg+xml';

/**
* Transforms an already-resolved image stream. Split out from `transform` so the build
* can hand over source bytes it read itself: during the build the original image lives
* in Astro's intermediate output rather than behind the ASSETS binding, so the worker
* has no way to fetch it.
*
* `sourceContentType` is the media type the source was served with. It resolves the output
* format for requests that carry no `f` parameter, which core omits whenever it cannot
* infer a source format from the URL — extensionless remote images such as
* `https://avatars.githubusercontent.com/u/1234` are the common case. Core leaves the
* format undefined there on purpose, expecting the image service to determine it from the
* source itself, as the Sharp service does. See withastro/astro.build#2610.
*/
export async function transformStream(
body: ReadableStream,
params: URLSearchParams,
images: ImagesBinding,
sourceContentType?: string | null,
): Promise<Response> {
const supportedFormats: Record<string, ImageOutputOptions['format']> = {
jpeg: 'image/jpeg',
Expand All @@ -30,10 +40,23 @@ export async function transformStream(
avif: 'image/avif',
};

const outputFormat = supportedFormats[params.get('f') ?? ''];
const requestedFormat = params.get('f');
const sourceType = sourceContentType?.split(';')[0].trim().toLowerCase();

// Core asks for `svg` when the source is an SVG, meaning "leave it alone". The IMAGES
// binding cannot emit SVG and Astro does not rasterize SVG sources by default, so serve
// the original bytes.
if (requestedFormat === 'svg' || (!requestedFormat && sourceType === SVG_CONTENT_TYPE)) {
return new Response(body, {
headers: { 'Content-Type': sourceContentType || SVG_CONTENT_TYPE },
});
}

// Mirrors core's `resolveDefaultOutputFormat`, which webp-encodes every non-SVG source.
const outputFormat = requestedFormat ? supportedFormats[requestedFormat] : 'image/webp';

if (!outputFormat) {
return new Response(`Unsupported format: ${params.get('f')}`, { status: 400 });
return new Response(`Unsupported format: ${requestedFormat}`, { status: 400 });
}

const qualityParam = params.get('q');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,10 @@ export async function transform(
return new Response(null, { status: 404 });
}

return transformStream(content.body, url.searchParams, images);
return transformStream(
content.body,
url.searchParams,
images,
content.headers.get('content-type'),
);
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,45 @@
import * as assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { after, before, describe, it } from 'node:test';
import { type Fixture, loadFixture, type PreviewServer } from './test-utils.ts';

const PLACEHOLDER_JPEG = readFileSync(
new URL('./fixtures/binding-image-service/public/placeholder.jpg', import.meta.url),
);
const LOGO_SVG = readFileSync(
new URL('./fixtures/binding-image-service/public/logo.svg', import.meta.url),
);

/** Serves images from extensionless paths, the way GitHub serves user avatars. */
function startRemoteImageServer(): Promise<{ server: Server; port: number }> {
const server = createServer((req, res) => {
if (req.url?.startsWith('/svg')) {
res.writeHead(200, { 'Content-Type': 'image/svg+xml' });
res.end(LOGO_SVG);
return;
}
res.writeHead(200, { 'Content-Type': 'image/jpeg' });
res.end(PLACEHOLDER_JPEG);
});
return new Promise((resolve) => {
server.listen(0, () => {
const address = server.address();
if (typeof address === 'string' || !address) {
throw new TypeError('Unexpected address for testing');
}
resolve({ server, port: address.port });
});
});
}

describe('BindingImageService', () => {
let fixture: Fixture;
let previewServer: PreviewServer;
let redirectServer: Server;
let redirectServerPort: number;
let imageServer: Server;
let imageServerPort: number;

before(async () => {
// Start a local HTTP server that always responds with a 302 redirect.
Expand All @@ -27,6 +59,8 @@ describe('BindingImageService', () => {
});
});

({ server: imageServer, port: imageServerPort } = await startRemoteImageServer());

fixture = await loadFixture({
root: './fixtures/binding-image-service/',
});
Expand All @@ -37,6 +71,7 @@ describe('BindingImageService', () => {
after(async () => {
await previewServer.stop();
await new Promise((resolve) => redirectServer.close(resolve));
await new Promise((resolve) => imageServer.close(resolve));
});

it('returns 403 for missing href parameter', async () => {
Expand Down Expand Up @@ -79,4 +114,34 @@ describe('BindingImageService', () => {
const res = await fixture.fetch(`/_image?href=${encodeURIComponent(href)}&f=webp`);
assert.equal(res.status, 404);
});

// Core omits `f` when it cannot infer a source format from the URL, which is the case
// for every extensionless remote image (GitHub avatars, for one). See withastro/astro.build#2610.
it('defaults to webp for remote images with no format parameter', async () => {
const href = `http://localhost:${imageServerPort}/u/2738`;
const res = await fixture.fetch(`/_image?href=${encodeURIComponent(href)}&w=100`);
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/webp');
});

it('passes through remote SVGs with no format parameter', async () => {
const href = `http://localhost:${imageServerPort}/svg`;
const res = await fixture.fetch(`/_image?href=${encodeURIComponent(href)}&w=100`);
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/svg+xml');
assert.ok((await res.text()).includes('<svg'));
});

it('passes through local SVGs requested as f=svg', async () => {
const res = await fixture.fetch('/_image?href=/logo.svg&f=svg&w=100');
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/svg+xml');
assert.ok((await res.text()).includes('<svg'));
});

it('defaults to webp for local images with no format parameter', async () => {
const res = await fixture.fetch('/_image?href=/placeholder.jpg&w=100');
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/webp');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ describe('Dev image endpoint', () => {
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/avif');
});

// Core omits `f` when it cannot infer a source format from the URL. See withastro/astro.build#2610.
it('defaults to webp when no format parameter is given', async () => {
const res = await fixture.fetch('/_image?href=/placeholder.jpg&w=100');
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/webp');
});
});

describe('Dev image endpoint with prerenderEnvironment: node', () => {
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading