From fdd4677e324df964059929659193adde26af6e87 Mon Sep 17 00:00:00 2001 From: AhmedElBanna80 Date: Sat, 3 Oct 2026 21:03:46 +0300 Subject: [PATCH 01/16] fix(image): honor trailingSlash, fix custom-loader srcSet, support images.loaderFile next/image had three related gaps against Next.js's documented behavior: - imageOptimizationUrl() always emitted `/_next/image?...`, ignoring `trailingSlash: true`. Next.js emits `/_next/image/?...` in that case. Both the App Router and legacy Image shims share this helper, so both were affected. - A custom `loader` prop was called once with the intrinsic width and a forced quality of 75, producing a single `src` with no `srcSet`. Next.js gives a custom loader the same per-breakpoint treatment as the built-in loader: both the 1x and 2x (or sizes-derived) candidate widths, and the `quality` prop passed through as given (including `undefined`, letting the loader apply its own default) rather than forced to 75. - `images.loaderFile` was parsed but never wired up anywhere, so it had no effect. It's now resolved via a `resolve.alias` entry (aliasing the bare specifier `vinext:image-loader-file` to the configured file, or to a no-op default when unset) that the Image shim imports unconditionally and falls back to when no per-image `loader` prop is given. Fixes two of next/image's existing unit tests that had encoded the old (incorrect) custom-loader behavior, and adds coverage for all three fixes. --- packages/vinext/src/check.ts | 2 +- packages/vinext/src/config/next-config.ts | 4 + packages/vinext/src/index.ts | 11 ++ .../src/shims/image-loader-file-default.ts | 17 ++ packages/vinext/src/shims/image.tsx | 159 +++++++++++++----- .../src/virtual-vinext-image-loader-file.d.ts | 12 ++ scripts/check-shim-types.mjs | 7 + tests/image-component.test.ts | 68 +++++++- tests/image-loader-file.test.ts | 59 +++++++ vite.config.ts | 6 + 10 files changed, 299 insertions(+), 46 deletions(-) create mode 100644 packages/vinext/src/shims/image-loader-file-default.ts create mode 100644 packages/vinext/src/virtual-vinext-image-loader-file.d.ts create mode 100644 tests/image-loader-file.test.ts diff --git a/packages/vinext/src/check.ts b/packages/vinext/src/check.ts index 95aa6e0667..89226b87fe 100644 --- a/packages/vinext/src/check.ts +++ b/packages/vinext/src/check.ts @@ -217,7 +217,7 @@ const CONFIG_SUPPORT: Record = { images: { status: "partial", detail: - "remotePatterns, deviceSizes/imageSizes, qualities and SVG/CSP options honoured; resizing needs an optimizer via vinext({ images: { optimizer } }), images are served as-is otherwise; loader/loaderFile are ignored", + "remotePatterns, deviceSizes/imageSizes, qualities, SVG/CSP options, the `loader` prop and `images.loaderFile` honoured; resizing needs an optimizer via vinext({ images: { optimizer } }), images are served as-is otherwise", }, allowedDevOrigins: { status: "supported", detail: "dev server cross-origin allowlist" }, output: { diff --git a/packages/vinext/src/config/next-config.ts b/packages/vinext/src/config/next-config.ts index 5bbd155028..af4dce6d05 100644 --- a/packages/vinext/src/config/next-config.ts +++ b/packages/vinext/src/config/next-config.ts @@ -314,6 +314,10 @@ export type NextConfig = { headers?: () => Promise | NextHeader[]; /** Image optimization config */ images?: { + /** "default" (built-in /_next/image endpoint) or "custom" (use `loaderFile`). Defaults to "default". */ + loader?: "default" | "custom"; + /** Path to a module exporting a custom image loader as its default export. Requires `loader: "custom"`. */ + loaderFile?: string; remotePatterns?: Array< | URL | { diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index 01d4c98b3d..024e885113 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -1306,6 +1306,7 @@ const _appBrowserServerActionClientPath = resolveShimModulePath( const _appRscCombinedHandlerPath = resolveShimModulePath(_serverDir, "app-rsc-combined-handler"); const _appRscHandlerPath = resolveShimModulePath(_serverDir, "app-rsc-handler"); const _pagesClientAssetsPath = resolveShimModulePath(_serverDir, "pages-client-assets"); +const _imageLoaderFileDefaultPath = resolveShimModulePath(_shimsDir, "image-loader-file-default"); // Source checkouts resolve to TypeScript and must stay in Vite's graph so tests // do not execute a stale dist build. Published packages resolve to emitted JS, // which Node can load natively outside the RSC transform graph. @@ -3518,6 +3519,16 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { ...nextConfig.aliases, ...nextShimMap, "vinext/server/pages-client-assets": _pagesClientAssetsPath, + // `images.loaderFile` from next.config.js — an absolute + // path when `images: { loader: "custom", loaderFile }` is + // set, else the no-op default (shims/image.tsx imports + // this unconditionally and treats `undefined` as "no + // configured loader file"). + "vinext:image-loader-file": + nextConfig.images?.loader === "custom" && + typeof nextConfig.images.loaderFile === "string" + ? path.resolve(root, nextConfig.images.loaderFile) + : _imageLoaderFileDefaultPath, }, tsconfigPathAliases, { ...nextConfig.aliases, ...nextShimMap }, diff --git a/packages/vinext/src/shims/image-loader-file-default.ts b/packages/vinext/src/shims/image-loader-file-default.ts new file mode 100644 index 0000000000..e80a31fcf3 --- /dev/null +++ b/packages/vinext/src/shims/image-loader-file-default.ts @@ -0,0 +1,17 @@ +/** + * Default resolution target for the `vinext:image-loader-file` alias. + * + * The vinext plugin aliases that bare specifier to the user's configured + * `images.loaderFile` (resolved to an absolute path) when next.config.js + * sets `images: { loader: "custom", loaderFile: "..." }` — see the + * `resolve.alias` entries built in index.ts's `config()` hook. When no + * `loaderFile` is configured, the alias points here instead, so + * `shims/image.tsx`'s `import __imageLoaderFileDefault from + * "vinext:image-loader-file"` always resolves to something: a real custom + * loader, or `undefined` (a no-op — the shim falls back to the built-in + * /_next/image loader). + */ +import type { ImageLoader } from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; + +const loader: ImageLoader | undefined = undefined; +export default loader; diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 1e450f4ace..d493e38fb9 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -26,6 +26,11 @@ import type { import { getDeploymentId } from "../utils/deployment-id.js"; import { hasRemoteMatch, isPrivateIp, type RemotePattern } from "./image-config.js"; import { useMergedRef } from "./use-merged-ref.js"; +// Resolves to the user's `images.loaderFile` (via a resolve.alias entry +// the vinext plugin adds in index.ts) when next.config.js sets +// `images: { loader: "custom", loaderFile: "..." }`; otherwise `undefined` +// (shims/image-loader-file-default.ts) — a no-op, same as not importing it. +import __imageLoaderFileDefault from "vinext:image-loader-file"; export type { ImageLoader, StaticImageData, StaticRequire }; export type ImageLoaderProps = Parameters[0]; @@ -82,6 +87,13 @@ const __dangerouslyAllowSVG = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG = */ const __dangerouslyAllowLocalIP = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_LOCAL_IP === "true"; const __globallyUnoptimized = process.env.__VINEXT_IMAGE_UNOPTIMIZED === "true"; +/** + * Whether trailingSlash is enabled in next.config.js. Mirrors the define + * consumed by the Link/Router shims (shims/link.tsx, shims/router.ts, + * shims/navigation.ts) so the image optimization endpoint's own path obeys + * the same config, matching Next.js's `images.path` normalization. + */ +const __trailingSlash: boolean = process.env.__VINEXT_TRAILING_SLASH === "true"; /** * Validate that a remote URL is allowed by the configured remote patterns. @@ -295,7 +307,10 @@ export function imageOptimizationUrl(src: string, width: number, quality: number const source = extractLocalDeploymentId(src); const deploymentQuery = source.src.startsWith("/") && source.deploymentId ? `&dpl=${source.deploymentId}` : ""; - return `/_next/image?url=${encodeURIComponent(source.src)}&w=${width}&q=${quality}${deploymentQuery}`; + // Matches Next.js: when `trailingSlash` is set, the image optimizer's own + // path gets a trailing slash too, same as every other route. + const basePath = __trailingSlash ? "/_next/image/" : "/_next/image"; + return `${basePath}?url=${encodeURIComponent(source.src)}&w=${width}&q=${quality}${deploymentQuery}`; } function preloadImageResource(input: { @@ -333,10 +348,11 @@ function getImageWidths(width: number): number[] { ]; } -function generateImageAttributes( +function generateAttributesWithResolver( + resolveUrl: (src: string, width: number, quality?: number) => string, src: string, width: number, - quality: number = 75, + quality: number | undefined, sizes?: string, ): { src: string; srcSet: string } { if (sizes) { @@ -350,28 +366,56 @@ function generateImageAttributes( : 0; const candidates = ALL_IMAGE_WIDTHS.filter((candidateWidth) => candidateWidth >= minimumWidth); return { - src: imageOptimizationUrl(src, candidates[candidates.length - 1], quality), + src: resolveUrl(src, candidates[candidates.length - 1], quality), srcSet: candidates - .map( - (candidateWidth) => - `${imageOptimizationUrl(src, candidateWidth, quality)} ${candidateWidth}w`, - ) + .map((candidateWidth) => `${resolveUrl(src, candidateWidth, quality)} ${candidateWidth}w`) .join(", "), }; } const widths = getImageWidths(width); return { - src: imageOptimizationUrl(src, widths[widths.length - 1], quality), + src: resolveUrl(src, widths[widths.length - 1], quality), srcSet: widths - .map( - (candidateWidth, index) => - `${imageOptimizationUrl(src, candidateWidth, quality)} ${index + 1}x`, - ) + .map((candidateWidth, index) => `${resolveUrl(src, candidateWidth, quality)} ${index + 1}x`) .join(", "), }; } +function generateImageAttributes( + src: string, + width: number, + quality: number = 75, + sizes?: string, +): { src: string; srcSet: string } { + return generateAttributesWithResolver(imageOptimizationUrl, src, width, quality, sizes); +} + +/** + * Same per-width srcSet treatment as generateImageAttributes, but routed + * through a user-supplied loader (the `loader` prop or `images.loaderFile`) + * instead of the built-in /_next/image endpoint. Unlike the built-in loader, + * `quality` is passed through as given — including `undefined` — so a + * custom loader's own default (if any) applies, matching Next.js: the + * forced quality=75 default is specific to the built-in loader. + */ +function generateLoaderAttributes( + loader: ImageLoader, + src: string, + width: number, + quality: number | undefined, + sizes?: string, +): { src: string; srcSet: string } { + return generateAttributesWithResolver( + (loaderSrc, loaderWidth, loaderQuality) => + loader({ src: loaderSrc, width: loaderWidth, quality: loaderQuality }), + src, + width, + quality, + sizes, + ); +} + const Image = forwardRef(function Image( { src: srcProp, @@ -574,13 +618,26 @@ const Image = forwardRef(function Image( ); } - // If a custom loader is provided, use basic img with loader URL - if (loader) { - const resolvedQuality = typeof quality === "string" ? Number(quality) : (quality ?? 75); - const resolvedSrc = loader({ src, width: imgWidth ?? 0, quality: resolvedQuality }); + // A custom loader — either the `loader` prop, or `images.loaderFile` from + // next.config.js when no per-image prop was given — takes full + // responsibility for the URL, bypassing remotePatterns validation and the + // /_next/image endpoint. `quality` is passed through as given (possibly + // undefined); only the built-in loader defaults it to 75. + const effectiveLoader = loader ?? (__imageLoaderFileDefault as ImageLoader | undefined); + if (effectiveLoader) { + const resolvedQuality = typeof quality === "string" ? Number(quality) : quality; + const loaderAttributes = + imgWidth && !fill + ? generateLoaderAttributes(effectiveLoader, src, imgWidth, resolvedQuality, sizes) + : undefined; + const resolvedSrc = loaderAttributes + ? loaderAttributes.src + : effectiveLoader({ src, width: imgWidth ?? 0, quality: resolvedQuality }); + const resolvedSrcSet = loaderAttributes?.srcSet; preloadImageResource({ shouldPreload, src: resolvedSrc, + srcSet: resolvedSrcSet, sizes, fetchPriority: priorityFetchPriority, }); @@ -593,6 +650,7 @@ const Image = forwardRef(function Image( height={fill ? undefined : imgHeight} loading={imageLoading} decoding="async" + srcSet={resolvedSrcSet} sizes={sizes} className={className} onLoad={handleLoad} @@ -856,32 +914,47 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { } } - // Resolve src through custom loader if provided - const imgQuality = typeof _quality === "string" ? Number(_quality) : (_quality ?? 75); - const resolvedSrc = blockedInProd - ? "" - : loader - ? loader({ src, width: imgWidth ?? 0, quality: imgQuality }) - : src; - - // For local images (no loader, not remote), route through optimization endpoint. - // When `unoptimized` is true, bypass the endpoint entirely (Next.js compat). - // SVG sources auto-skip unless dangerouslyAllowSVG is enabled. - const isSvg = isSvgUrl(resolvedSrc); - const skipOpt = - (isSvg && !__dangerouslyAllowSVG) || blockedInProd || !!loader || isRemoteUrl(resolvedSrc); - const optimizedAttributes = - imgWidth && !fill && !skipOpt - ? generateImageAttributes(resolvedSrc, imgWidth, imgQuality, sizes) - : null; - const optimizedSrc = skipOpt - ? resolvedSrc - : optimizedAttributes - ? optimizedAttributes.src - : imageOptimizationUrl(resolvedSrc, RESPONSIVE_WIDTHS[0], imgQuality); - - // Build srcSet for local images — each width points to /_next/image - const srcSet = optimizedAttributes?.srcSet; + // Resolve src through a custom loader if provided (the `loader` prop, or + // `images.loaderFile` from next.config.js when no per-image prop was + // given). `quality` is passed through as given, including `undefined` — + // only the built-in /_next/image loader below defaults it to 75. + const effectiveLoader = loader ?? (__imageLoaderFileDefault as ImageLoader | undefined); + const imgQuality = typeof _quality === "string" ? Number(_quality) : _quality; + + let optimizedSrc: string; + let srcSet: string | undefined; + if (blockedInProd) { + optimizedSrc = ""; + srcSet = undefined; + } else if (effectiveLoader) { + const loaderAttributes = + imgWidth && !fill + ? generateLoaderAttributes(effectiveLoader, src, imgWidth, imgQuality, sizes) + : undefined; + optimizedSrc = loaderAttributes + ? loaderAttributes.src + : effectiveLoader({ src, width: imgWidth ?? 0, quality: imgQuality }); + srcSet = loaderAttributes?.srcSet; + } else { + // For local images (no loader, not remote), route through the + // optimization endpoint. When `unoptimized` is true, bypass the + // endpoint entirely (Next.js compat). SVG sources auto-skip unless + // dangerouslyAllowSVG is enabled. + const resolvedQuality = imgQuality ?? 75; + const isSvg = isSvgUrl(src); + const skipOpt = (isSvg && !__dangerouslyAllowSVG) || isRemoteUrl(src); + const optimizedAttributes = + imgWidth && !fill && !skipOpt + ? generateImageAttributes(src, imgWidth, resolvedQuality, sizes) + : null; + optimizedSrc = skipOpt + ? src + : optimizedAttributes + ? optimizedAttributes.src + : imageOptimizationUrl(src, RESPONSIVE_WIDTHS[0], resolvedQuality); + // Build srcSet for local images — each width points to /_next/image + srcSet = optimizedAttributes?.srcSet; + } // Blur placeholder styles — sanitize to prevent CSS injection const sanitizedBlurURL = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; diff --git a/packages/vinext/src/virtual-vinext-image-loader-file.d.ts b/packages/vinext/src/virtual-vinext-image-loader-file.d.ts new file mode 100644 index 0000000000..9bff284f54 --- /dev/null +++ b/packages/vinext/src/virtual-vinext-image-loader-file.d.ts @@ -0,0 +1,12 @@ +/** + * Aliased (resolve.alias, not a virtual module — there's no generated + * content to produce, just a file swap) to the user's `images.loaderFile` + * when next.config.js sets `images: { loader: "custom", loaderFile }`, + * else to shims/image-loader-file-default.ts (`undefined`). See index.ts's + * `config()` hook and shims/image.tsx. + */ +declare module "vinext:image-loader-file" { + import type { ImageLoader } from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; + const loader: ImageLoader | undefined; + export default loader; +} diff --git a/scripts/check-shim-types.mjs b/scripts/check-shim-types.mjs index 1e55c4f99e..5f9f49f879 100644 --- a/scripts/check-shim-types.mjs +++ b/scripts/check-shim-types.mjs @@ -53,6 +53,13 @@ function renderContracts(tempDir) { `/// `, `/// `, `/// `, + // Ambient type for the `vinext:image-loader-file` resolve.alias id that + // shims/image.tsx imports unconditionally (see that file and index.ts's + // `config()` hook). Kept in its own file rather than global.d.ts, same + // as the other per-feature virtual-module ambient types (e.g. + // virtual-vinext-rsc-entry.d.ts) — unlike those, this one is imported + // from inside shims/, so this contract check needs to know about it too. + `/// `, "", ]; diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index 7783bb4ebe..5187edf917 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -63,6 +63,59 @@ describe("default loader emits /_next/image URLs (issue #1513)", () => { }); }); +// ─── trailingSlash: the image optimizer's own path obeys the config ──── +// +// Ported from Next.js e2e fixtures: +// test/e2e/next-image-new/trailing-slash/trailing-slash.test.ts +// test/e2e/next-image-legacy/trailing-slash/trailing-slash.test.ts +// Both expect /_next/image/?url=... (trailing slash before the query +// string) once next.config.js sets `trailingSlash: true`. imageOptimizationUrl +// is shared by the legacy Image shim (shims/legacy-image.tsx wraps this +// component), so fixing it here fixes both fixtures. + +describe("imageOptimizationUrl honors trailingSlash", () => { + afterEach(() => { + delete process.env.__VINEXT_TRAILING_SLASH; + vi.resetModules(); + }); + + it("adds a trailing slash before the query string when trailingSlash is set", async () => { + process.env.__VINEXT_TRAILING_SLASH = "true"; + vi.resetModules(); + const { imageOptimizationUrl: imageOptimizationUrlWithTrailingSlash } = + await import("../packages/vinext/src/shims/image.js"); + expect(imageOptimizationUrlWithTrailingSlash("/test.jpg", 828, 75)).toBe( + "/_next/image/?url=%2Ftest.jpg&w=828&q=75", + ); + }); + + it("does not add a trailing slash when trailingSlash is unset", async () => { + delete process.env.__VINEXT_TRAILING_SLASH; + vi.resetModules(); + const { imageOptimizationUrl: imageOptimizationUrlDefault } = + await import("../packages/vinext/src/shims/image.js"); + expect(imageOptimizationUrlDefault("/test.jpg", 828, 75)).toBe( + "/_next/image?url=%2Ftest.jpg&w=828&q=75", + ); + }); + + it("the Image component's SSR src carries the trailing slash", async () => { + process.env.__VINEXT_TRAILING_SLASH = "true"; + vi.resetModules(); + const { default: TrailingSlashImage } = await import("../packages/vinext/src/shims/image.js"); + const html = ReactDOMServer.renderToString( + React.createElement(TrailingSlashImage, { + id: "test1", + alt: "test", + src: "/_next/static/media/test.hash.jpg", + width: 400, + height: 300, + }), + ); + expect(html).toMatch(/src="\/_next\/image\/\?url=/); + }); +}); + // ─── SSR rendering ────────────────────────────────────────────────────── describe("Image SSR rendering", () => { @@ -212,7 +265,13 @@ describe("Image SSR rendering", () => { loader, }), ); - expect(html).toContain('src="https://cdn.example.com/photo.jpg?w=200&q=75"'); + // A custom loader gets the same per-width srcSet treatment as the + // built-in loader: src is the 2x (larger) breakpoint, srcSet carries + // both the 1x and 2x breakpoints rounded up from [200, 400]. + expect(html).toContain('src="https://cdn.example.com/photo.jpg?w=640&q=75"'); + expect(html).toContain( + 'srcSet="https://cdn.example.com/photo.jpg?w=256&q=75 1x, https://cdn.example.com/photo.jpg?w=640&q=75 2x"', + ); }); it("renders StaticImageData (import result)", () => { @@ -431,7 +490,12 @@ describe("getImageProps", () => { loader, }); - expect(props.src).toBe("https://cdn.example.com/photo.jpg?w=300"); + // Same per-width srcSet treatment as the built-in loader: [300, 600] + // round up to the nearest configured breakpoints, 384 and 640. + expect(props.src).toBe("https://cdn.example.com/photo.jpg?w=640"); + expect(props.srcSet).toBe( + "https://cdn.example.com/photo.jpg?w=384 1x, https://cdn.example.com/photo.jpg?w=640 2x", + ); }); it("returns blur placeholder styles", () => { diff --git a/tests/image-loader-file.test.ts b/tests/image-loader-file.test.ts new file mode 100644 index 0000000000..1a6fc541e6 --- /dev/null +++ b/tests/image-loader-file.test.ts @@ -0,0 +1,59 @@ +/** + * `images.loaderFile` config wiring. + * + * Next.js's `images: { loader: "custom", loaderFile: "./my-loader.js" }` + * points at a module whose default export is a custom ImageLoader, used by + * every `next/image` instance that doesn't set its own `loader` prop. + * + * vinext wires this as a `resolve.alias` entry (not a generated virtual + * module — there is nothing to generate, just a file swap): the bare + * specifier `vinext:image-loader-file` resolves to the user's configured + * file when set, or to shims/image-loader-file-default.ts (`undefined`, + * a no-op) otherwise. shims/image.tsx imports that specifier unconditionally + * and falls back to it when no per-image `loader` prop is given — see + * tests/image-component.test.ts for the shim-side srcSet/quality behavior + * once a loader (prop or loaderFile) is in play. + * + * Ported from Next.js: test/e2e/next-image-new/loader-config/loader-config.test.ts + * https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/loader-config/loader-config.test.ts + */ +import path from "node:path"; +import { describe, it, expect } from "vite-plus/test"; +import vinext from "../packages/vinext/src/index.js"; + +const APP_FIXTURE_DIR = path.resolve(import.meta.dirname, "./fixtures/app-basic"); + +async function resolveAliasMap(images?: Record) { + const plugins = vinext({ nextConfig: () => ({ images }) }) as any[]; + const configPlugin = plugins.find((plugin) => plugin.name === "vinext:config"); + const config = await configPlugin.config( + { root: APP_FIXTURE_DIR, plugins: [] }, + { command: "build", mode: "production" }, + ); + const alias = config.resolve.alias as Array<{ find: string; replacement: string }>; + return Object.fromEntries(alias.map((entry) => [entry.find, entry.replacement])); +} + +describe("images.loaderFile resolve.alias wiring", () => { + it("aliases to the no-op default when images is unset", async () => { + const aliasMap = await resolveAliasMap(undefined); + expect(aliasMap["vinext:image-loader-file"]).toMatch(/image-loader-file-default\.(ts|js)$/); + }); + + it("aliases to the no-op default when loader is 'default' (or unset) even with loaderFile present", async () => { + const aliasMap = await resolveAliasMap({ loaderFile: "./my-loader.js" }); + expect(aliasMap["vinext:image-loader-file"]).toMatch(/image-loader-file-default\.(ts|js)$/); + }); + + it("aliases to the configured file, resolved against the project root, when loader is 'custom'", async () => { + const aliasMap = await resolveAliasMap({ loader: "custom", loaderFile: "./my-loader.js" }); + expect(aliasMap["vinext:image-loader-file"]).toBe( + path.resolve(APP_FIXTURE_DIR, "./my-loader.js"), + ); + }); + + it("aliases to the no-op default when loader is 'custom' but loaderFile is missing", async () => { + const aliasMap = await resolveAliasMap({ loader: "custom" }); + expect(aliasMap["vinext:image-loader-file"]).toMatch(/image-loader-file-default\.(ts|js)$/); + }); +}); diff --git a/vite.config.ts b/vite.config.ts index 4abd2ac280..b337b8e658 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -17,6 +17,12 @@ const WORKSPACE_SRC_ALIAS = { "@vinext/cloudflare/internal": CLOUDFLARE_SRC, "@vinext/cloudflare/cache": path.resolve(import.meta.dirname, "packages/cloudflare/src/cache"), "@vinext/cloudflare/images": path.resolve(import.meta.dirname, "packages/cloudflare/src/images"), + // No next.config.js in these unit tests, so always resolve to the no-op + // default — same as a project that never sets `images.loaderFile`. + "vinext:image-loader-file": path.resolve( + import.meta.dirname, + "packages/vinext/src/shims/image-loader-file-default.ts", + ), }; export default defineConfig({ From aa3ae0d94466cc85ce26724eaaeea950a370fbcc Mon Sep 17 00:00:00 2001 From: AhmedElBanna80 Date: Sun, 4 Oct 2026 11:26:00 +0300 Subject: [PATCH 02/16] test(image): update shims.test.ts custom-loader assertions for per-breakpoint srcSet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tests/shims.test.ts has its own, separate custom-loader coverage for next/image that duplicates (but doesn't share with) tests/image-component.test.ts — it still pinned the old single-width/quality-75 behavior this PR replaced. Bring it in line with the per-breakpoint treatment: src is the 2x candidate, srcSet carries both 1x and 2x, and quality passes through as given (undefined here, since neither test sets a quality prop). --- tests/shims.test.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/tests/shims.test.ts b/tests/shims.test.ts index fb9d63cad0..fb83d6efed 100644 --- a/tests/shims.test.ts +++ b/tests/shims.test.ts @@ -26296,8 +26296,14 @@ describe("next/image enhancements", () => { height: 600, loader: ({ src, width, quality }) => `https://cdn.example.com${src}?w=${width}&q=${quality}`, }); - // Custom loader bypasses the /_next/image endpoint - expect(result.props.src).toBe("https://cdn.example.com/photo.jpg?w=800&q=75"); + // Custom loader bypasses the /_next/image endpoint and gets the same + // per-width srcSet treatment as the built-in loader: src is the 2x + // (larger) breakpoint, with quality passed through as given + // (undefined here, since no quality prop was set). + expect(result.props.src).toBe("https://cdn.example.com/photo.jpg?w=1920&q=undefined"); + expect(result.props.srcSet).toBe( + "https://cdn.example.com/photo.jpg?w=828&q=undefined 1x, https://cdn.example.com/photo.jpg?w=1920&q=undefined 2x", + ); expect(result.props.src).not.toContain("/_next/image"); }); @@ -26452,7 +26458,13 @@ describe("next/image component rendering", () => { `https://cdn.example.com${src}?w=${width}&q=${quality}`, }), ); - expect(html).toContain('src="https://cdn.example.com/photo.jpg?w=800&q=75"'); + // Per-width srcSet treatment: src is the 2x breakpoint, srcSet carries + // both the 1x and 2x breakpoints; quality passed through as given + // (undefined here, since no quality prop was set). + expect(html).toContain('src="https://cdn.example.com/photo.jpg?w=1920&q=undefined"'); + expect(html).toContain( + 'srcSet="https://cdn.example.com/photo.jpg?w=828&q=undefined 1x, https://cdn.example.com/photo.jpg?w=1920&q=undefined 2x"', + ); }); it("renders with custom sizes attribute", async () => { From 7f7f69cbf8b48a1d3ef901e6a3c9344b9d1de5b9 Mon Sep 17 00:00:00 2001 From: James Date: Tue, 6 Oct 2026 04:21:01 +0100 Subject: [PATCH 03/16] fix(image): wire images.loaderFile without a root test alias and match Next.js rules - Import the loaderFile slot as vinext/shims/image-loader-file so unit tests resolve it through the existing vinext/shims alias; drop the root vite.config.ts alias, the ambient .d.ts and the check-shim-types hook. - Keep that specifier bare in dist so the plugin alias still applies. - Apply loaderFile when images.loader is unset, default or custom, and throw Next.js's errors for other loaders or a missing file. - Skip remotePatterns validation in getImageProps when a custom loader owns the URL, as the component path and Next.js do. - Add dev-server fixture tests for trailingSlash, loader-prop srcSet and images.loaderFile. --- packages/vinext/src/check.ts | 2 +- packages/vinext/src/config/next-config.ts | 6 +- packages/vinext/src/index.ts | 38 ++++-- .../src/shims/image-loader-file-default.ts | 17 --- .../vinext/src/shims/image-loader-file.ts | 13 ++ packages/vinext/src/shims/image.tsx | 34 ++--- .../src/virtual-vinext-image-loader-file.d.ts | 12 -- packages/vinext/vite.config.ts | 4 + scripts/check-shim-types.mjs | 7 - tests/image-loader-file.test.ts | 78 ++++++----- tests/image-optimization-parity.test.ts | 126 +++++++++++++++++- vite.config.ts | 6 - 12 files changed, 236 insertions(+), 107 deletions(-) delete mode 100644 packages/vinext/src/shims/image-loader-file-default.ts create mode 100644 packages/vinext/src/shims/image-loader-file.ts delete mode 100644 packages/vinext/src/virtual-vinext-image-loader-file.d.ts diff --git a/packages/vinext/src/check.ts b/packages/vinext/src/check.ts index 89226b87fe..e4d12126a7 100644 --- a/packages/vinext/src/check.ts +++ b/packages/vinext/src/check.ts @@ -217,7 +217,7 @@ const CONFIG_SUPPORT: Record = { images: { status: "partial", detail: - "remotePatterns, deviceSizes/imageSizes, qualities, SVG/CSP options, the `loader` prop and `images.loaderFile` honoured; resizing needs an optimizer via vinext({ images: { optimizer } }), images are served as-is otherwise", + "remotePatterns, deviceSizes/imageSizes, qualities, SVG/CSP options and loaderFile honoured; resizing needs an optimizer via vinext({ images: { optimizer } }), images are served as-is otherwise; the imgix/cloudinary/akamai loader presets are ignored", }, allowedDevOrigins: { status: "supported", detail: "dev server cross-origin allowlist" }, output: { diff --git a/packages/vinext/src/config/next-config.ts b/packages/vinext/src/config/next-config.ts index af4dce6d05..8d8cc68d15 100644 --- a/packages/vinext/src/config/next-config.ts +++ b/packages/vinext/src/config/next-config.ts @@ -314,9 +314,9 @@ export type NextConfig = { headers?: () => Promise | NextHeader[]; /** Image optimization config */ images?: { - /** "default" (built-in /_next/image endpoint) or "custom" (use `loaderFile`). Defaults to "default". */ - loader?: "default" | "custom"; - /** Path to a module exporting a custom image loader as its default export. Requires `loader: "custom"`. */ + /** Image loader. Defaults to "default"; only "default" and "custom" can be combined with `loaderFile`. */ + loader?: "default" | "imgix" | "cloudinary" | "akamai" | "custom"; + /** Path (relative to the project root) to a module whose default export is the image loader. */ loaderFile?: string; remotePatterns?: Array< | URL diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index 024e885113..4aa22b9004 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -1306,7 +1306,28 @@ const _appBrowserServerActionClientPath = resolveShimModulePath( const _appRscCombinedHandlerPath = resolveShimModulePath(_serverDir, "app-rsc-combined-handler"); const _appRscHandlerPath = resolveShimModulePath(_serverDir, "app-rsc-handler"); const _pagesClientAssetsPath = resolveShimModulePath(_serverDir, "pages-client-assets"); -const _imageLoaderFileDefaultPath = resolveShimModulePath(_shimsDir, "image-loader-file-default"); +const _imageLoaderFilePath = resolveShimModulePath(_shimsDir, "image-loader-file"); + +/** + * Resolve the module behind `vinext/shims/image-loader-file`. Ported from + * Next.js's `images.loaderFile` normalization in server/config.ts: the file + * is used when `images.loader` is unset, "default" or "custom", and must exist. + */ +function resolveImageLoaderFile(images: NextConfig["images"], root: string): string { + const loaderFile = images?.loaderFile; + if (!loaderFile) return _imageLoaderFilePath; + const loader = images.loader ?? "default"; + if (loader !== "default" && loader !== "custom") { + throw new Error( + `Specified images.loader property (${loader}) cannot be used with images.loaderFile property. Please set images.loader to "custom".`, + ); + } + const absolutePath = path.resolve(root, loaderFile); + if (!fs.existsSync(absolutePath)) { + throw new Error(`Specified images.loaderFile does not exist at "${absolutePath}".`); + } + return absolutePath; +} // Source checkouts resolve to TypeScript and must stay in Vite's graph so tests // do not execute a stale dist build. Published packages resolve to emitted JS, // which Node can load natively outside the RSC transform graph. @@ -3519,16 +3540,11 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { ...nextConfig.aliases, ...nextShimMap, "vinext/server/pages-client-assets": _pagesClientAssetsPath, - // `images.loaderFile` from next.config.js — an absolute - // path when `images: { loader: "custom", loaderFile }` is - // set, else the no-op default (shims/image.tsx imports - // this unconditionally and treats `undefined` as "no - // configured loader file"). - "vinext:image-loader-file": - nextConfig.images?.loader === "custom" && - typeof nextConfig.images.loaderFile === "string" - ? path.resolve(root, nextConfig.images.loaderFile) - : _imageLoaderFileDefaultPath, + // shims/image.tsx imports this slot for `images.loaderFile`. + // Like Next.js (which aliases next/dist/shared/lib/image-loader + // to the file), point it at the user's file, resolved against + // the project root; otherwise keep vinext's `undefined` default. + "vinext/shims/image-loader-file": resolveImageLoaderFile(nextConfig.images, root), }, tsconfigPathAliases, { ...nextConfig.aliases, ...nextShimMap }, diff --git a/packages/vinext/src/shims/image-loader-file-default.ts b/packages/vinext/src/shims/image-loader-file-default.ts deleted file mode 100644 index e80a31fcf3..0000000000 --- a/packages/vinext/src/shims/image-loader-file-default.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Default resolution target for the `vinext:image-loader-file` alias. - * - * The vinext plugin aliases that bare specifier to the user's configured - * `images.loaderFile` (resolved to an absolute path) when next.config.js - * sets `images: { loader: "custom", loaderFile: "..." }` — see the - * `resolve.alias` entries built in index.ts's `config()` hook. When no - * `loaderFile` is configured, the alias points here instead, so - * `shims/image.tsx`'s `import __imageLoaderFileDefault from - * "vinext:image-loader-file"` always resolves to something: a real custom - * loader, or `undefined` (a no-op — the shim falls back to the built-in - * /_next/image loader). - */ -import type { ImageLoader } from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; - -const loader: ImageLoader | undefined = undefined; -export default loader; diff --git a/packages/vinext/src/shims/image-loader-file.ts b/packages/vinext/src/shims/image-loader-file.ts new file mode 100644 index 0000000000..e0f819a1ff --- /dev/null +++ b/packages/vinext/src/shims/image-loader-file.ts @@ -0,0 +1,13 @@ +/** + * The `images.loaderFile` slot imported by shims/image.tsx. + * + * This module exports `undefined` (no configured loader file, so the built-in + * /_next/image loader applies). When next.config.js sets `images.loaderFile`, + * the vinext plugin aliases `vinext/shims/image-loader-file` to that file + * instead (see the `resolve.alias` entries in index.ts's `config()` hook), + * mirroring how Next.js aliases `next/dist/shared/lib/image-loader` to it. + */ +import type { ImageLoader } from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; + +const loader: ImageLoader | undefined = undefined; +export default loader; diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index d493e38fb9..080e584405 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -26,11 +26,9 @@ import type { import { getDeploymentId } from "../utils/deployment-id.js"; import { hasRemoteMatch, isPrivateIp, type RemotePattern } from "./image-config.js"; import { useMergedRef } from "./use-merged-ref.js"; -// Resolves to the user's `images.loaderFile` (via a resolve.alias entry -// the vinext plugin adds in index.ts) when next.config.js sets -// `images: { loader: "custom", loaderFile: "..." }`; otherwise `undefined` -// (shims/image-loader-file-default.ts) — a no-op, same as not importing it. -import __imageLoaderFileDefault from "vinext:image-loader-file"; +// The user's `images.loaderFile` default export when next.config.js sets one +// (the vinext plugin aliases this specifier to it), otherwise `undefined`. +import configuredImageLoader from "vinext/shims/image-loader-file"; export type { ImageLoader, StaticImageData, StaticRequire }; export type ImageLoaderProps = Parameters[0]; @@ -309,8 +307,8 @@ export function imageOptimizationUrl(src: string, width: number, quality: number source.src.startsWith("/") && source.deploymentId ? `&dpl=${source.deploymentId}` : ""; // Matches Next.js: when `trailingSlash` is set, the image optimizer's own // path gets a trailing slash too, same as every other route. - const basePath = __trailingSlash ? "/_next/image/" : "/_next/image"; - return `${basePath}?url=${encodeURIComponent(source.src)}&w=${width}&q=${quality}${deploymentQuery}`; + const imagePath = __trailingSlash ? "/_next/image/" : "/_next/image"; + return `${imagePath}?url=${encodeURIComponent(source.src)}&w=${width}&q=${quality}${deploymentQuery}`; } function preloadImageResource(input: { @@ -623,7 +621,7 @@ const Image = forwardRef(function Image( // responsibility for the URL, bypassing remotePatterns validation and the // /_next/image endpoint. `quality` is passed through as given (possibly // undefined); only the built-in loader defaults it to 75. - const effectiveLoader = loader ?? (__imageLoaderFileDefault as ImageLoader | undefined); + const effectiveLoader = loader ?? configuredImageLoader; if (effectiveLoader) { const resolvedQuality = typeof quality === "string" ? Number(quality) : quality; const loaderAttributes = @@ -900,9 +898,18 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { return { props: Object.assign(imageProps, { "data-nimg": fill ? "fill" : "1" }) }; } - // Validate remote URLs against configured patterns + // Resolve src through a custom loader if provided (the `loader` prop, or + // `images.loaderFile` from next.config.js when no per-image prop was + // given). `quality` is passed through as given, including `undefined` — + // only the built-in /_next/image loader below defaults it to 75. + const effectiveLoader = loader ?? configuredImageLoader; + const imgQuality = typeof _quality === "string" ? Number(_quality) : _quality; + + // Validate remote URLs against configured patterns. As in the component + // path (and Next.js's default loader), a custom loader owns the URL, so + // remotePatterns don't apply to it. let blockedInProd = false; - if (isRemoteUrl(src)) { + if (!effectiveLoader && isRemoteUrl(src)) { const validation = validateRemoteUrl(src); if (!validation.allowed) { if (__isDev) { @@ -914,13 +921,6 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { } } - // Resolve src through a custom loader if provided (the `loader` prop, or - // `images.loaderFile` from next.config.js when no per-image prop was - // given). `quality` is passed through as given, including `undefined` — - // only the built-in /_next/image loader below defaults it to 75. - const effectiveLoader = loader ?? (__imageLoaderFileDefault as ImageLoader | undefined); - const imgQuality = typeof _quality === "string" ? Number(_quality) : _quality; - let optimizedSrc: string; let srcSet: string | undefined; if (blockedInProd) { diff --git a/packages/vinext/src/virtual-vinext-image-loader-file.d.ts b/packages/vinext/src/virtual-vinext-image-loader-file.d.ts deleted file mode 100644 index 9bff284f54..0000000000 --- a/packages/vinext/src/virtual-vinext-image-loader-file.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Aliased (resolve.alias, not a virtual module — there's no generated - * content to produce, just a file swap) to the user's `images.loaderFile` - * when next.config.js sets `images: { loader: "custom", loaderFile }`, - * else to shims/image-loader-file-default.ts (`undefined`). See index.ts's - * `config()` hook and shims/image.tsx. - */ -declare module "vinext:image-loader-file" { - import type { ImageLoader } from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; - const loader: ImageLoader | undefined; - export default loader; -} diff --git a/packages/vinext/vite.config.ts b/packages/vinext/vite.config.ts index fd58465e15..73ed21a8f9 100644 --- a/packages/vinext/vite.config.ts +++ b/packages/vinext/vite.config.ts @@ -66,6 +66,10 @@ const externalizeBareThirdPartySpecifiers = ( isResolved: boolean, ) => { if (isResolved) return false; + // shims/image.tsx imports the `images.loaderFile` slot by this bare + // specifier so the vinext plugin can alias it to the user's loader file. + // Keep it bare in `dist` instead of rewriting it to a relative import. + if (id === "vinext/shims/image-loader-file") return true; // Relative/absolute paths, virtual modules, and protocol-prefixed ids // resolve normally. if (id.startsWith(".") || id.startsWith("/") || id.startsWith("\0") || id.includes(":")) { diff --git a/scripts/check-shim-types.mjs b/scripts/check-shim-types.mjs index 5f9f49f879..1e55c4f99e 100644 --- a/scripts/check-shim-types.mjs +++ b/scripts/check-shim-types.mjs @@ -53,13 +53,6 @@ function renderContracts(tempDir) { `/// `, `/// `, `/// `, - // Ambient type for the `vinext:image-loader-file` resolve.alias id that - // shims/image.tsx imports unconditionally (see that file and index.ts's - // `config()` hook). Kept in its own file rather than global.d.ts, same - // as the other per-feature virtual-module ambient types (e.g. - // virtual-vinext-rsc-entry.d.ts) — unlike those, this one is imported - // from inside shims/, so this contract check needs to know about it too. - `/// `, "", ]; diff --git a/tests/image-loader-file.test.ts b/tests/image-loader-file.test.ts index 1a6fc541e6..3c069a1fc7 100644 --- a/tests/image-loader-file.test.ts +++ b/tests/image-loader-file.test.ts @@ -1,59 +1,73 @@ /** * `images.loaderFile` config wiring. * - * Next.js's `images: { loader: "custom", loaderFile: "./my-loader.js" }` - * points at a module whose default export is a custom ImageLoader, used by - * every `next/image` instance that doesn't set its own `loader` prop. - * - * vinext wires this as a `resolve.alias` entry (not a generated virtual - * module — there is nothing to generate, just a file swap): the bare - * specifier `vinext:image-loader-file` resolves to the user's configured - * file when set, or to shims/image-loader-file-default.ts (`undefined`, - * a no-op) otherwise. shims/image.tsx imports that specifier unconditionally - * and falls back to it when no per-image `loader` prop is given — see - * tests/image-component.test.ts for the shim-side srcSet/quality behavior - * once a loader (prop or loaderFile) is in play. - * - * Ported from Next.js: test/e2e/next-image-new/loader-config/loader-config.test.ts - * https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/loader-config/loader-config.test.ts + * shims/image.tsx imports `vinext/shims/image-loader-file`; the vinext plugin + * aliases that specifier to the configured loader file, mirroring how Next.js + * aliases `next/dist/shared/lib/image-loader` to it. The rules come from the + * `images.loaderFile` normalization in Next.js's server/config.ts. See + * tests/image-optimization-parity.test.ts for the end-to-end fixture coverage. */ +import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; -import { describe, it, expect } from "vite-plus/test"; +import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test"; import vinext from "../packages/vinext/src/index.js"; +import { APP_FIXTURE_DIR, aliasEntriesToRecord } from "./helpers.js"; -const APP_FIXTURE_DIR = path.resolve(import.meta.dirname, "./fixtures/app-basic"); +const SPECIFIER = "vinext/shims/image-loader-file"; +const DEFAULT_MODULE_RE = /[/\\]shims[/\\]image-loader-file\.(ts|js)$/; async function resolveAliasMap(images?: Record) { + // oxlint-disable-next-line typescript/no-explicit-any const plugins = vinext({ nextConfig: () => ({ images }) }) as any[]; const configPlugin = plugins.find((plugin) => plugin.name === "vinext:config"); const config = await configPlugin.config( { root: APP_FIXTURE_DIR, plugins: [] }, { command: "build", mode: "production" }, ); - const alias = config.resolve.alias as Array<{ find: string; replacement: string }>; - return Object.fromEntries(alias.map((entry) => [entry.find, entry.replacement])); + return aliasEntriesToRecord(config.resolve.alias); } describe("images.loaderFile resolve.alias wiring", () => { - it("aliases to the no-op default when images is unset", async () => { - const aliasMap = await resolveAliasMap(undefined); - expect(aliasMap["vinext:image-loader-file"]).toMatch(/image-loader-file-default\.(ts|js)$/); + let tmpDir: string; + let loaderFile: string; + + beforeAll(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "vinext-image-loader-file-")); + loaderFile = path.join(tmpDir, "my-loader.js"); + fs.writeFileSync(loaderFile, "export default ({ src }) => src;\n"); + }); + + afterAll(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); }); - it("aliases to the no-op default when loader is 'default' (or unset) even with loaderFile present", async () => { - const aliasMap = await resolveAliasMap({ loaderFile: "./my-loader.js" }); - expect(aliasMap["vinext:image-loader-file"]).toMatch(/image-loader-file-default\.(ts|js)$/); + it("keeps vinext's undefined default when loaderFile is unset", async () => { + expect((await resolveAliasMap(undefined))[SPECIFIER]).toMatch(DEFAULT_MODULE_RE); + expect((await resolveAliasMap({ loader: "custom" }))[SPECIFIER]).toMatch(DEFAULT_MODULE_RE); }); - it("aliases to the configured file, resolved against the project root, when loader is 'custom'", async () => { - const aliasMap = await resolveAliasMap({ loader: "custom", loaderFile: "./my-loader.js" }); - expect(aliasMap["vinext:image-loader-file"]).toBe( - path.resolve(APP_FIXTURE_DIR, "./my-loader.js"), + it.each([undefined, "default", "custom"])( + "resolves loaderFile against the project root when loader is %s", + async (loader) => { + const aliasMap = await resolveAliasMap({ + loader, + loaderFile: path.relative(APP_FIXTURE_DIR, loaderFile), + }); + expect(aliasMap[SPECIFIER]).toBe(loaderFile); + }, + ); + + it("rejects loaderFile combined with a built-in loader preset", async () => { + await expect(resolveAliasMap({ loader: "imgix", loaderFile })).rejects.toThrow( + 'Specified images.loader property (imgix) cannot be used with images.loaderFile property. Please set images.loader to "custom".', ); }); - it("aliases to the no-op default when loader is 'custom' but loaderFile is missing", async () => { - const aliasMap = await resolveAliasMap({ loader: "custom" }); - expect(aliasMap["vinext:image-loader-file"]).toMatch(/image-loader-file-default\.(ts|js)$/); + it("rejects a loaderFile that does not exist", async () => { + const missing = path.join(tmpDir, "missing-loader.js"); + await expect(resolveAliasMap({ loaderFile: missing })).rejects.toThrow( + `Specified images.loaderFile does not exist at "${missing}".`, + ); }); }); diff --git a/tests/image-optimization-parity.test.ts b/tests/image-optimization-parity.test.ts index 072894a7e7..44da9d1a17 100644 --- a/tests/image-optimization-parity.test.ts +++ b/tests/image-optimization-parity.test.ts @@ -10,7 +10,10 @@ const PNG_1X1 = Buffer.from( "base64", ); -async function createImageFixture(router: "app" | "pages"): Promise { +async function createImageFixture( + router: "app" | "pages", + options: { nextConfig?: string; files?: Record } = {}, +): Promise { const baseFixtureDir = router === "app" ? APP_FIXTURE_DIR : PAGES_FIXTURE_DIR; const rootDir = await fs.mkdtemp(path.join(os.tmpdir(), `vinext-${router}-image-parity-`)); await fs.cp(baseFixtureDir, rootDir, { recursive: true }); @@ -63,9 +66,29 @@ export default function Page() { ); } + if (options.nextConfig !== undefined) { + // next.config.ts takes priority over other extensions, so overwrite it. + await fs.writeFile(path.join(rootDir, "next.config.ts"), options.nextConfig); + } + for (const [file, contents] of Object.entries(options.files ?? {})) { + await fs.mkdir(path.dirname(path.join(rootDir, file)), { recursive: true }); + await fs.writeFile(path.join(rootDir, file), contents); + } + return rootDir; } +function getImageSrcSetFromHtml(html: string, alt: string): string { + for (const match of html.matchAll(/]*>/g)) { + const tag = match[0]; + if (!tag.includes(`alt="${alt}"`)) continue; + const srcSetMatch = tag.match(/\ssrcSet="([^"]+)"/); + if (srcSetMatch) return srcSetMatch[1].replaceAll("&", "&"); + } + + throw new Error(`Could not find srcSet on tag for alt="${alt}"`); +} + function getImageSrcFromHtml(html: string, alt: string): string { for (const match of html.matchAll(/]*>/g)) { const tag = match[0]; @@ -174,5 +197,106 @@ describe("image deployment query parity", () => { }); }); +// Ported from Next.js: test/e2e/next-image-new/trailing-slash/trailing-slash.test.ts +// https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/trailing-slash/trailing-slash.test.ts +describe("App Router next/image with trailingSlash: true", () => { + let server: ViteDevServer; + let baseUrl: string; + let fixtureDir: string; + + beforeAll(async () => { + fixtureDir = await createImageFixture("app", { + nextConfig: "export default { trailingSlash: true };\n", + files: { + "app/image-parity/loader-prop/page.tsx": `"use client"; +import Image from "next/image"; + +export default function Page() { + return ( + loader-prop \`https://cdn.example.com\${src}?w=\${width}&q=\${quality ?? "auto"}\`} + /> + ); +} +`, + }, + }); + ({ server, baseUrl } = await startFixtureServer(fixtureDir, { appRouter: true })); + }, 30000); + + afterAll(async () => { + await server?.close(); + await fs.rm(fixtureDir, { recursive: true, force: true }); + }); + + it("emits /_next/image/ URLs that reach the image endpoint directly", async () => { + const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/"); + const src = getImageSrcFromHtml(html, "space"); + + expect(src).toBe("/_next/image/?url=%2Fhello%20world.png&w=128&q=75"); + expect(getImageSrcSetFromHtml(html, "space")).toBe( + "/_next/image/?url=%2Fhello%20world.png&w=64&q=75 1x, /_next/image/?url=%2Fhello%20world.png&w=128&q=75 2x", + ); + + // The dev image endpoint 302s to the source file; no trailing-slash 308 first. + const res = await fetch(new URL(src, baseUrl), { redirect: "manual" }); + expect(res.status).toBe(302); + expect(res.headers.get("location")).toBe("/hello%20world.png"); + }); + + // Next.js runs a custom loader through the same generateImgAttrs as the + // default loader (shared/lib/get-img-props.ts), passing quality unchanged. + it("gives a custom loader prop every srcSet width and an unset quality", async () => { + const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/loader-prop/"); + + expect(getImageSrcFromHtml(html, "loader-prop")).toBe( + "https://cdn.example.com/hello world.png?w=128&q=auto", + ); + expect(getImageSrcSetFromHtml(html, "loader-prop")).toBe( + "https://cdn.example.com/hello world.png?w=64&q=auto 1x, https://cdn.example.com/hello world.png?w=128&q=auto 2x", + ); + }); +}); + +// Ported from Next.js: test/e2e/next-image-new/loader-config/loader-config.test.ts +// https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/loader-config/loader-config.test.ts +describe("App Router next/image with images.loaderFile", () => { + let server: ViteDevServer; + let baseUrl: string; + let fixtureDir: string; + + beforeAll(async () => { + fixtureDir = await createImageFixture("app", { + // Next.js applies loaderFile when images.loader is unset, "default" or "custom". + nextConfig: 'export default { images: { loaderFile: "./dummy-loader.mjs" } };\n', + files: { + "dummy-loader.mjs": `export default function dummyLoader({ src, width, quality }) { + return \`\${src}#w:\${width},q:\${quality || 50}\`; +} +`, + }, + }); + ({ server, baseUrl } = await startFixtureServer(fixtureDir, { appRouter: true })); + }, 30000); + + afterAll(async () => { + await server?.close(); + await fs.rm(fixtureDir, { recursive: true, force: true }); + }); + + it("routes images without a loader prop through the configured loader file", async () => { + const html = await fetchHtmlWithRetry(baseUrl, "/image-parity"); + + expect(getImageSrcFromHtml(html, "space")).toBe("/hello world.png#w:128,q:50"); + expect(getImageSrcSetFromHtml(html, "space")).toBe( + "/hello world.png#w:64,q:50 1x, /hello world.png#w:128,q:50 2x", + ); + }); +}); + runLocalImageUrlParitySuite("app"); runLocalImageUrlParitySuite("pages"); diff --git a/vite.config.ts b/vite.config.ts index b337b8e658..4abd2ac280 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -17,12 +17,6 @@ const WORKSPACE_SRC_ALIAS = { "@vinext/cloudflare/internal": CLOUDFLARE_SRC, "@vinext/cloudflare/cache": path.resolve(import.meta.dirname, "packages/cloudflare/src/cache"), "@vinext/cloudflare/images": path.resolve(import.meta.dirname, "packages/cloudflare/src/images"), - // No next.config.js in these unit tests, so always resolve to the no-op - // default — same as a project that never sets `images.loaderFile`. - "vinext:image-loader-file": path.resolve( - import.meta.dirname, - "packages/vinext/src/shims/image-loader-file-default.ts", - ), }; export default defineConfig({ From 8323621b880761d5522c3fd283fcd84040207d4a Mon Sep 17 00:00:00 2001 From: James Date: Tue, 6 Oct 2026 04:49:21 +0100 Subject: [PATCH 04/16] fix(image): match Next.js for configured loaders on fill, overrideSrc and custom mode - Give width-less (fill) images every device width and sizes=100vw when a custom loader or loaderFile is in effect, as Next.js getWidths() does. - Apply overrideSrc over the loader-generated src in both Image and getImageProps. - Throw Next.js's missing-loader error when images.loader is "custom" and an image has neither a loader prop nor a loaderFile, and its missing default export error for an empty loaderFile. --- packages/vinext/src/index.ts | 8 ++ packages/vinext/src/shims/image.tsx | 99 +++++++++++++++++-------- tests/image-component.test.ts | 87 ++++++++++++++++++++++ tests/image-loader-file.test.ts | 18 ++++- tests/image-optimization-parity.test.ts | 29 ++++++++ 5 files changed, 209 insertions(+), 32 deletions(-) diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index 1572806601..98de33d857 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -2905,6 +2905,14 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { defines["process.env.__VINEXT_IMAGE_UNOPTIMIZED"] = JSON.stringify( String(nextConfig.images?.unoptimized === true), ); + // images.loader / images.loaderFile modes the next/image shim validates + // against at render time (see resolveImageLoader in shims/image.tsx). + defines["process.env.__VINEXT_IMAGE_CUSTOM_LOADER"] = JSON.stringify( + String(nextConfig.images?.loader === "custom"), + ); + defines["process.env.__VINEXT_IMAGE_LOADER_FILE"] = JSON.stringify( + String(Boolean(nextConfig.images?.loaderFile)), + ); // Build ID — resolved from next.config generateBuildId() or random UUID. // Exposed so server entries and the next/server shim can inject it. // Also used to namespace ISR cache keys so old cached entries from a diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 080e584405..9186dbe770 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -85,6 +85,10 @@ const __dangerouslyAllowSVG = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG = */ const __dangerouslyAllowLocalIP = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_LOCAL_IP === "true"; const __globallyUnoptimized = process.env.__VINEXT_IMAGE_UNOPTIMIZED === "true"; +/** `images.loader: "custom"` — images without a loader prop or loaderFile throw. */ +const __customImageLoader = process.env.__VINEXT_IMAGE_CUSTOM_LOADER === "true"; +/** `images.loaderFile` is set, so `configuredImageLoader` must be its default export. */ +const __hasImageLoaderFile = process.env.__VINEXT_IMAGE_LOADER_FILE === "true"; /** * Whether trailingSlash is enabled in next.config.js. Mirrors the define * consumed by the Link/Router shims (shims/link.tsx, shims/router.ts, @@ -349,10 +353,10 @@ function getImageWidths(width: number): number[] { function generateAttributesWithResolver( resolveUrl: (src: string, width: number, quality?: number) => string, src: string, - width: number, + width: number | undefined, quality: number | undefined, sizes?: string, -): { src: string; srcSet: string } { +): { src: string; srcSet: string; sizes?: string } { if (sizes) { const viewportWidthPattern = /(^|\s)(1?\d?\d)vw/g; const viewportPercentages = Array.from(sizes.matchAll(viewportWidthPattern), (match) => @@ -368,6 +372,19 @@ function generateAttributesWithResolver( srcSet: candidates .map((candidateWidth) => `${resolveUrl(src, candidateWidth, quality)} ${candidateWidth}w`) .join(", "), + sizes, + }; + } + + // No intrinsic width (e.g. `fill`): Next.js's getWidths() offers every + // device size and defaults `sizes` to 100vw. + if (width === undefined) { + return { + src: resolveUrl(src, RESPONSIVE_WIDTHS[RESPONSIVE_WIDTHS.length - 1], quality), + srcSet: RESPONSIVE_WIDTHS.map( + (candidateWidth) => `${resolveUrl(src, candidateWidth, quality)} ${candidateWidth}w`, + ).join(", "), + sizes: "100vw", }; } @@ -400,10 +417,10 @@ function generateImageAttributes( function generateLoaderAttributes( loader: ImageLoader, src: string, - width: number, + width: number | undefined, quality: number | undefined, sizes?: string, -): { src: string; srcSet: string } { +): { src: string; srcSet: string; sizes?: string } { return generateAttributesWithResolver( (loaderSrc, loaderWidth, loaderQuality) => loader({ src: loaderSrc, width: loaderWidth, quality: loaderQuality }), @@ -414,6 +431,27 @@ function generateLoaderAttributes( ); } +/** + * Pick the loader for an image: the `loader` prop, else `images.loaderFile`, + * else `undefined` for the built-in /_next/image loader. Ported from the + * loader checks at the top of Next.js's getImgProps (shared/lib/get-img-props.ts). + */ +function resolveImageLoader(src: string, loader: ImageLoader | undefined): ImageLoader | undefined { + if (__hasImageLoaderFile && typeof configuredImageLoader === "undefined") { + throw new Error( + "images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config", + ); + } + const effectiveLoader = loader ?? configuredImageLoader; + if (!effectiveLoader && __customImageLoader) { + throw new Error( + `Image with src "${src}" is missing "loader" prop.` + + "\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader", + ); + } + return effectiveLoader; +} + const Image = forwardRef(function Image( { src: srcProp, @@ -487,6 +525,7 @@ const Image = forwardRef(function Image( height: imgHeight, blurDataURL: imgBlurDataURL, } = resolveImageSource({ src: srcProp, width, height, blurDataURL }); + const effectiveLoader = resolveImageLoader(src, loader); const shouldPreload = preload === true || priority === true; const priorityFetchPriority = priority ? "high" : undefined; const imageLoading = priority ? "eager" : shouldPreload ? loading : (loading ?? "lazy"); @@ -621,22 +660,21 @@ const Image = forwardRef(function Image( // responsibility for the URL, bypassing remotePatterns validation and the // /_next/image endpoint. `quality` is passed through as given (possibly // undefined); only the built-in loader defaults it to 75. - const effectiveLoader = loader ?? configuredImageLoader; if (effectiveLoader) { const resolvedQuality = typeof quality === "string" ? Number(quality) : quality; - const loaderAttributes = - imgWidth && !fill - ? generateLoaderAttributes(effectiveLoader, src, imgWidth, resolvedQuality, sizes) - : undefined; - const resolvedSrc = loaderAttributes - ? loaderAttributes.src - : effectiveLoader({ src, width: imgWidth ?? 0, quality: resolvedQuality }); - const resolvedSrcSet = loaderAttributes?.srcSet; + const loaderAttributes = generateLoaderAttributes( + effectiveLoader, + src, + fill ? undefined : imgWidth, + resolvedQuality, + sizes, + ); + const resolvedSrc = overrideSrc || loaderAttributes.src; preloadImageResource({ shouldPreload, src: resolvedSrc, - srcSet: resolvedSrcSet, - sizes, + srcSet: loaderAttributes.srcSet, + sizes: loaderAttributes.sizes, fetchPriority: priorityFetchPriority, }); return ( @@ -648,8 +686,8 @@ const Image = forwardRef(function Image( height={fill ? undefined : imgHeight} loading={imageLoading} decoding="async" - srcSet={resolvedSrcSet} - sizes={sizes} + srcSet={loaderAttributes.srcSet} + sizes={loaderAttributes.sizes} className={className} onLoad={handleLoad} onError={handleError} @@ -865,6 +903,7 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { height: imgHeight, blurDataURL: imgBlurDataURL, } = resolveImageSource({ src: srcProp, width, height, blurDataURL: blurDataURLProp }); + const effectiveLoader = resolveImageLoader(src, loader); const shouldPreload = _preload === true || priority === true; if (_unoptimized === true || __globallyUnoptimized) { @@ -898,11 +937,10 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { return { props: Object.assign(imageProps, { "data-nimg": fill ? "fill" : "1" }) }; } - // Resolve src through a custom loader if provided (the `loader` prop, or - // `images.loaderFile` from next.config.js when no per-image prop was - // given). `quality` is passed through as given, including `undefined` — - // only the built-in /_next/image loader below defaults it to 75. - const effectiveLoader = loader ?? configuredImageLoader; + // A custom loader (the `loader` prop, or `images.loaderFile` from + // next.config.js when no per-image prop was given) gets `quality` as given, + // including `undefined` — only the built-in /_next/image loader below + // defaults it to 75. const imgQuality = typeof _quality === "string" ? Number(_quality) : _quality; // Validate remote URLs against configured patterns. As in the component @@ -927,14 +965,15 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { optimizedSrc = ""; srcSet = undefined; } else if (effectiveLoader) { - const loaderAttributes = - imgWidth && !fill - ? generateLoaderAttributes(effectiveLoader, src, imgWidth, imgQuality, sizes) - : undefined; - optimizedSrc = loaderAttributes - ? loaderAttributes.src - : effectiveLoader({ src, width: imgWidth ?? 0, quality: imgQuality }); - srcSet = loaderAttributes?.srcSet; + const loaderAttributes = generateLoaderAttributes( + effectiveLoader, + src, + fill ? undefined : imgWidth, + imgQuality, + sizes, + ); + optimizedSrc = overrideSrc || loaderAttributes.src; + srcSet = loaderAttributes.srcSet; } else { // For local images (no loader, not remote), route through the // optimization endpoint. When `unoptimized` is true, bypass the diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index 5187edf917..76eac1739c 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -116,6 +116,46 @@ describe("imageOptimizationUrl honors trailingSlash", () => { }); }); +// ─── images.loader / images.loaderFile validation ────────────────────── +// +// Ported from the loader checks at the top of Next.js's getImgProps +// (packages/next/src/shared/lib/get-img-props.ts). + +describe("images.loader config validation", () => { + afterEach(() => { + delete process.env.__VINEXT_IMAGE_CUSTOM_LOADER; + delete process.env.__VINEXT_IMAGE_LOADER_FILE; + vi.resetModules(); + }); + + it('throws for an image without a loader prop when images.loader is "custom"', async () => { + process.env.__VINEXT_IMAGE_CUSTOM_LOADER = "true"; + vi.resetModules(); + const shim = await import("../packages/vinext/src/shims/image.js"); + const imageProps = { alt: "a", src: "/photo.jpg", width: 100, height: 100 }; + const message = 'Image with src "/photo.jpg" is missing "loader" prop.'; + + expect(() => + ReactDOMServer.renderToString(React.createElement(shim.default, imageProps)), + ).toThrow(message); + expect(() => shim.getImageProps({ ...imageProps, unoptimized: true })).toThrow(message); + expect( + shim.getImageProps({ ...imageProps, loader: ({ src, width }) => `${src}?w=${width}` }).props + .src, + ).toBe("/photo.jpg?w=256"); + }); + + it("throws when images.loaderFile has no default export", async () => { + process.env.__VINEXT_IMAGE_LOADER_FILE = "true"; + vi.resetModules(); + const shim = await import("../packages/vinext/src/shims/image.js"); + + expect(() => + shim.getImageProps({ alt: "a", src: "/photo.jpg", width: 100, height: 100 }), + ).toThrow("images.loaderFile detected but the file is missing default export."); + }); +}); + // ─── SSR rendering ────────────────────────────────────────────────────── describe("Image SSR rendering", () => { @@ -274,6 +314,53 @@ describe("Image SSR rendering", () => { ); }); + // Next.js getWidths(config, undefined, sizes): a width-less (fill) image + // offers every device size and defaults sizes to 100vw. + it("gives a fill image's custom loader every device width and sizes=100vw", () => { + const loader = ({ src, width }: { src: string; width: number }) => + `https://cdn.example.com${src}?w=${width}`; + const deviceSizes = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]; + const expectedSrcSet = deviceSizes + .map((w) => `https://cdn.example.com/photo.jpg?w=${w} ${w}w`) + .join(", "); + + const html = ReactDOMServer.renderToString( + React.createElement(Image, { alt: "fill", src: "/photo.jpg", fill: true, loader }), + ); + expect(html).toContain('src="https://cdn.example.com/photo.jpg?w=3840"'); + expect(html).toContain(`srcSet="${expectedSrcSet}"`); + expect(html).toContain('sizes="100vw"'); + + const { props } = getImageProps({ alt: "fill", src: "/photo.jpg", fill: true, loader }); + expect(props.src).toBe("https://cdn.example.com/photo.jpg?w=3840"); + expect(props.srcSet).toBe(expectedSrcSet); + expect(props.sizes).toBe("100vw"); + }); + + // Next.js: `src: overrideSrc || imgAttributes.src`, keeping the loader srcSet. + it("applies overrideSrc on top of custom loader attributes", () => { + const loader = ({ src, width }: { src: string; width: number }) => + `https://cdn.example.com${src}?w=${width}`; + const imageProps = { + alt: "override", + src: "/photo.jpg", + width: 200, + height: 150, + loader, + overrideSrc: "/override.jpg", + }; + const srcSet = + "https://cdn.example.com/photo.jpg?w=256 1x, https://cdn.example.com/photo.jpg?w=640 2x"; + + const html = ReactDOMServer.renderToString(React.createElement(Image, imageProps)); + expect(html).toContain('src="/override.jpg"'); + expect(html).toContain(`srcSet="${srcSet}"`); + + const { props } = getImageProps(imageProps); + expect(props.src).toBe("/override.jpg"); + expect(props.srcSet).toBe(srcSet); + }); + it("renders StaticImageData (import result)", () => { const staticImage: StaticImageData = { src: "/_next/static/media/test.abc123.png", diff --git a/tests/image-loader-file.test.ts b/tests/image-loader-file.test.ts index 3c069a1fc7..15c18c78c6 100644 --- a/tests/image-loader-file.test.ts +++ b/tests/image-loader-file.test.ts @@ -17,14 +17,18 @@ import { APP_FIXTURE_DIR, aliasEntriesToRecord } from "./helpers.js"; const SPECIFIER = "vinext/shims/image-loader-file"; const DEFAULT_MODULE_RE = /[/\\]shims[/\\]image-loader-file\.(ts|js)$/; -async function resolveAliasMap(images?: Record) { +async function runConfigHook(images?: Record) { // oxlint-disable-next-line typescript/no-explicit-any const plugins = vinext({ nextConfig: () => ({ images }) }) as any[]; const configPlugin = plugins.find((plugin) => plugin.name === "vinext:config"); - const config = await configPlugin.config( + return configPlugin.config( { root: APP_FIXTURE_DIR, plugins: [] }, { command: "build", mode: "production" }, ); +} + +async function resolveAliasMap(images?: Record) { + const config = await runConfigHook(images); return aliasEntriesToRecord(config.resolve.alias); } @@ -47,6 +51,16 @@ describe("images.loaderFile resolve.alias wiring", () => { expect((await resolveAliasMap({ loader: "custom" }))[SPECIFIER]).toMatch(DEFAULT_MODULE_RE); }); + it("inlines the loader modes the next/image shim validates against", async () => { + const unset = (await runConfigHook(undefined)).define; + expect(unset["process.env.__VINEXT_IMAGE_CUSTOM_LOADER"]).toBe('"false"'); + expect(unset["process.env.__VINEXT_IMAGE_LOADER_FILE"]).toBe('"false"'); + + const custom = (await runConfigHook({ loader: "custom", loaderFile })).define; + expect(custom["process.env.__VINEXT_IMAGE_CUSTOM_LOADER"]).toBe('"true"'); + expect(custom["process.env.__VINEXT_IMAGE_LOADER_FILE"]).toBe('"true"'); + }); + it.each([undefined, "default", "custom"])( "resolves loaderFile against the project root when loader is %s", async (loader) => { diff --git a/tests/image-optimization-parity.test.ts b/tests/image-optimization-parity.test.ts index 44da9d1a17..fafc17f6f8 100644 --- a/tests/image-optimization-parity.test.ts +++ b/tests/image-optimization-parity.test.ts @@ -277,6 +277,19 @@ describe("App Router next/image with images.loaderFile", () => { "dummy-loader.mjs": `export default function dummyLoader({ src, width, quality }) { return \`\${src}#w:\${width},q:\${quality || 50}\`; } +`, + "app/image-parity/loader-file-variants/page.tsx": `import Image from "next/image"; + +export default function Page() { + return ( +
+
+ fill +
+ override +
+ ); +} `, }, }); @@ -296,6 +309,22 @@ describe("App Router next/image with images.loaderFile", () => { "/hello world.png#w:64,q:50 1x, /hello world.png#w:128,q:50 2x", ); }); + + it("gives fill images every device width and honors overrideSrc", async () => { + const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/loader-file-variants"); + const deviceSizes = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]; + + expect(getImageSrcFromHtml(html, "fill")).toBe("/hello world.png#w:3840,q:50"); + expect(getImageSrcSetFromHtml(html, "fill")).toBe( + deviceSizes.map((w) => `/hello world.png#w:${w},q:50 ${w}w`).join(", "), + ); + expect(html).toMatch(/]*alt="fill"[^>]*sizes="100vw"/); + + expect(getImageSrcFromHtml(html, "override")).toBe("/override.png"); + expect(getImageSrcSetFromHtml(html, "override")).toBe( + "/hello world.png#w:64,q:50 1x, /hello world.png#w:128,q:50 2x", + ); + }); }); runLocalImageUrlParitySuite("app"); From db8b569a8e985906d1f627f5bcc1d3b4fd115f12 Mon Sep 17 00:00:00 2001 From: James Date: Tue, 6 Oct 2026 05:08:51 +0100 Subject: [PATCH 05/16] fix(image): skip custom loaders for inline sources and keep src after srcSet - Treat data: and blob: sources as unoptimized when a custom loader or loaderFile is in effect, as Next.js does, so the loader never sees them. - Order src after srcSet/sizes in the custom-loader and in the getImageProps() result, matching Next.js's Safari-motivated prop order. --- packages/vinext/src/shims/image.tsx | 18 +++++++++++++---- tests/image-component.test.ts | 30 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 9186dbe770..8463de6c39 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -452,6 +452,10 @@ function resolveImageLoader(src: string, loader: ImageLoader | undefined): Image return effectiveLoader; } +function isInlineSrc(src: string): boolean { + return src.startsWith("data:") || src.startsWith("blob:"); +} + const Image = forwardRef(function Image( { src: srcProp, @@ -615,7 +619,9 @@ const Image = forwardRef(function Image( } : undefined; - if (_unoptimized === true || __globallyUnoptimized) { + // Next.js treats data:/blob: sources as unoptimized, so even a custom loader + // never sees them. + if (_unoptimized === true || __globallyUnoptimized || (effectiveLoader && isInlineSrc(src))) { // Unoptimized images are fetched directly by the browser, so intentionally // skip remote URL validation: there is no server-side optimizer fetch and // therefore no SSRF surface. This matches Next.js behavior. @@ -680,7 +686,6 @@ const Image = forwardRef(function Image( return ( {alt}(function Image( decoding="async" srcSet={loaderAttributes.srcSet} sizes={loaderAttributes.sizes} + // After srcSet/sizes, as in Next.js: Safari would otherwise start + // fetching `src` before it sees the responsive candidates. + src={resolvedSrc} className={className} onLoad={handleLoad} onError={handleError} @@ -906,7 +914,7 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { const effectiveLoader = resolveImageLoader(src, loader); const shouldPreload = _preload === true || priority === true; - if (_unoptimized === true || __globallyUnoptimized) { + if (_unoptimized === true || __globallyUnoptimized || (effectiveLoader && isInlineSrc(src))) { // As in the component path, unoptimized images never reach the server-side // optimizer, so remote URL validation is intentionally unnecessary. const renderedSrc = overrideSrc || src; @@ -1008,7 +1016,6 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { : undefined; const imageProps: ImgProps = { - src: optimizedSrc, alt, width: fill ? undefined : imgWidth, height: fill ? undefined : imgHeight, @@ -1017,6 +1024,9 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { decoding: "async" as const, srcSet, sizes: sizes ?? (fill ? "100vw" : undefined), + // After srcSet/sizes, matching Next.js's prop order (Safari fetches `src` + // early if React applies it first). + src: optimizedSrc, className, style: fill ? getFillStyle(style, blurStyle) : { ...blurStyle, ...style }, ...rest, diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index 76eac1739c..de630e0aa6 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -361,6 +361,36 @@ describe("Image SSR rendering", () => { expect(props.srcSet).toBe(srcSet); }); + // Next.js marks data:/blob: sources unoptimized before generateImgAttrs. + it("never passes data: or blob: sources to a custom loader", () => { + const loader = vi.fn(({ src, width }: { src: string; width: number }) => `${src}?w=${width}`); + for (const src of ["data:image/png;base64,iVBORw0KGgo=", "blob:https://example.com/uuid"]) { + const imageProps = { alt: "inline", src, width: 100, height: 100, loader }; + + const html = ReactDOMServer.renderToString(React.createElement(Image, imageProps)); + expect(html).toContain(`src="${src}"`); + expect(html).not.toContain("srcSet"); + + const { props } = getImageProps(imageProps); + expect(props.src).toBe(src); + expect(props.srcSet).toBeUndefined(); + } + expect(loader).not.toHaveBeenCalled(); + }); + + // Next.js keeps `src` after `sizes`/`srcSet` so Safari doesn't fetch it early. + it("orders src after srcSet and sizes for custom loaders", () => { + const loader = ({ src, width }: { src: string; width: number }) => `${src}?w=${width}`; + const imageProps = { alt: "order", src: "/photo.jpg", width: 100, height: 100, loader }; + + const html = ReactDOMServer.renderToString(React.createElement(Image, imageProps)); + expect(html.indexOf(" src=")).toBeGreaterThan(html.indexOf(" srcSet=")); + + const keys = Object.keys(getImageProps(imageProps).props); + expect(keys.indexOf("src")).toBeGreaterThan(keys.indexOf("srcSet")); + expect(keys.indexOf("src")).toBeGreaterThan(keys.indexOf("sizes")); + }); + it("renders StaticImageData (import result)", () => { const staticImage: StaticImageData = { src: "/_next/static/media/test.abc123.png", From b27f365e960e1933b0045d5eb7db3fb97abb1886 Mon Sep 17 00:00:00 2001 From: James Date: Tue, 6 Oct 2026 05:30:58 +0100 Subject: [PATCH 06/16] fix(image): match Next.js loaderFile resolution and scope it to next/image - Join images.loaderFile onto the project root like Next.js, so a leading slash stays project-relative instead of pointing at the filesystem root. - Import the loader file as a namespace so a file without a default export reaches Next.js's missing-default-export error instead of failing to link (the browser) or to bundle (rolldown). - Keep next/legacy/image on its built-in loader: it never reads loaderFile, and its custom-mode error only fires for optimized images, as in Next.js. --- packages/vinext/src/index.ts | 3 +- packages/vinext/src/shims/image.tsx | 51 ++++++++++++---- packages/vinext/src/shims/legacy-image.tsx | 21 ++++++- tests/image-component.test.ts | 19 ++++++ tests/image-loader-file.test.ts | 67 ++++++++++++---------- tests/image-optimization-parity.test.ts | 44 ++++++++++++++ 6 files changed, 161 insertions(+), 44 deletions(-) diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index 98de33d857..88f9cf1ccd 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -1326,7 +1326,8 @@ function resolveImageLoaderFile(images: NextConfig["images"], root: string): str `Specified images.loader property (${loader}) cannot be used with images.loaderFile property. Please set images.loader to "custom".`, ); } - const absolutePath = path.resolve(root, loaderFile); + // path.join (not resolve), as in Next.js: "/loader.js" is project-relative. + const absolutePath = path.join(root, loaderFile); if (!fs.existsSync(absolutePath)) { throw new Error(`Specified images.loaderFile does not exist at "${absolutePath}".`); } diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 8463de6c39..10c272de97 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -26,9 +26,13 @@ import type { import { getDeploymentId } from "../utils/deployment-id.js"; import { hasRemoteMatch, isPrivateIp, type RemotePattern } from "./image-config.js"; import { useMergedRef } from "./use-merged-ref.js"; -// The user's `images.loaderFile` default export when next.config.js sets one -// (the vinext plugin aliases this specifier to it), otherwise `undefined`. -import configuredImageLoader from "vinext/shims/image-loader-file"; +// The user's `images.loaderFile` module when next.config.js sets one (the +// vinext plugin aliases this specifier to it). A namespace import so a file +// without a default export reaches resolveImageLoader's diagnostic instead of +// failing module linking. +import * as imageLoaderFileModule from "vinext/shims/image-loader-file"; + +const configuredImageLoader: ImageLoader | undefined = imageLoaderFileModule.default; export type { ImageLoader, StaticImageData, StaticRequire }; export type ImageLoaderProps = Parameters[0]; @@ -431,24 +435,37 @@ function generateLoaderAttributes( ); } +function missingLoaderError(src: string): Error { + return new Error( + `Image with src "${src}" is missing "loader" prop.` + + "\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader", + ); +} + /** * Pick the loader for an image: the `loader` prop, else `images.loaderFile`, * else `undefined` for the built-in /_next/image loader. Ported from the * loader checks at the top of Next.js's getImgProps (shared/lib/get-img-props.ts). + * + * `next/legacy/image` never consults `images.loaderFile` in Next.js, and its + * built-in "custom" loader only throws when asked for a URL (optimized images). */ -function resolveImageLoader(src: string, loader: ImageLoader | undefined): ImageLoader | undefined { +function resolveImageLoader( + src: string, + loader: ImageLoader | undefined, + legacy?: { unoptimized: boolean }, +): ImageLoader | undefined { + if (legacy) { + if (!loader && __customImageLoader && !legacy.unoptimized) throw missingLoaderError(src); + return loader; + } if (__hasImageLoaderFile && typeof configuredImageLoader === "undefined") { throw new Error( "images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config", ); } const effectiveLoader = loader ?? configuredImageLoader; - if (!effectiveLoader && __customImageLoader) { - throw new Error( - `Image with src "${src}" is missing "loader" prop.` + - "\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader", - ); - } + if (!effectiveLoader && __customImageLoader) throw missingLoaderError(src); return effectiveLoader; } @@ -456,8 +473,12 @@ function isInlineSrc(src: string): boolean { return src.startsWith("data:") || src.startsWith("blob:"); } -const Image = forwardRef(function Image( +/** Internal: set by shims/legacy-image.tsx, which wraps this component. */ +type InternalImageProps = ImageProps & { __vinextLegacyImage?: boolean }; + +const Image = forwardRef(function Image( { + __vinextLegacyImage, src: srcProp, alt, width, @@ -529,7 +550,13 @@ const Image = forwardRef(function Image( height: imgHeight, blurDataURL: imgBlurDataURL, } = resolveImageSource({ src: srcProp, width, height, blurDataURL }); - const effectiveLoader = resolveImageLoader(src, loader); + const effectiveLoader = resolveImageLoader( + src, + loader, + __vinextLegacyImage + ? { unoptimized: _unoptimized === true || __globallyUnoptimized || isInlineSrc(src) } + : undefined, + ); const shouldPreload = preload === true || priority === true; const priorityFetchPriority = priority ? "high" : undefined; const imageLoading = priority ? "eager" : shouldPreload ? loading : (loading ?? "lazy"); diff --git a/packages/vinext/src/shims/legacy-image.tsx b/packages/vinext/src/shims/legacy-image.tsx index aa49d9607c..f1e15e56f8 100644 --- a/packages/vinext/src/shims/legacy-image.tsx +++ b/packages/vinext/src/shims/legacy-image.tsx @@ -52,7 +52,16 @@ function LegacyImage(props: ImageProps): React.ReactElement { : onLoad; if (layout === "fill") { - return {alt; + return ( + {alt + ); } if (layout === "responsive") { @@ -66,7 +75,15 @@ function LegacyImage(props: ImageProps): React.ReactElement { const h = typeof height === "string" ? parseInt(height, 10) : height; return ( - {alt + {alt ); } diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index de630e0aa6..62c906ba6f 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -154,6 +154,25 @@ describe("images.loader config validation", () => { shim.getImageProps({ alt: "a", src: "/photo.jpg", width: 100, height: 100 }), ).toThrow("images.loaderFile detected but the file is missing default export."); }); + + // Next.js's next/legacy/image never reads loaderFile, and its "custom" loader + // only throws when it has to build a URL (client/legacy/image.tsx). + it("keeps next/legacy/image off loaderFile and lets unoptimized images through", async () => { + process.env.__VINEXT_IMAGE_CUSTOM_LOADER = "true"; + process.env.__VINEXT_IMAGE_LOADER_FILE = "true"; + vi.resetModules(); + const { default: LegacyImage } = await import("../packages/vinext/src/shims/legacy-image.js"); + const imageProps = { alt: "a", src: "/photo.jpg", width: 100, height: 100 }; + + expect( + ReactDOMServer.renderToString( + React.createElement(LegacyImage, { ...imageProps, unoptimized: true }), + ), + ).toContain('src="/photo.jpg"'); + expect(() => + ReactDOMServer.renderToString(React.createElement(LegacyImage, imageProps)), + ).toThrow('Image with src "/photo.jpg" is missing "loader" prop.'); + }); }); // ─── SSR rendering ────────────────────────────────────────────────────── diff --git a/tests/image-loader-file.test.ts b/tests/image-loader-file.test.ts index 15c18c78c6..6a4fba62b9 100644 --- a/tests/image-loader-file.test.ts +++ b/tests/image-loader-file.test.ts @@ -12,38 +12,42 @@ import os from "node:os"; import path from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test"; import vinext from "../packages/vinext/src/index.js"; -import { APP_FIXTURE_DIR, aliasEntriesToRecord } from "./helpers.js"; +import { aliasEntriesToRecord } from "./helpers.js"; const SPECIFIER = "vinext/shims/image-loader-file"; const DEFAULT_MODULE_RE = /[/\\]shims[/\\]image-loader-file\.(ts|js)$/; -async function runConfigHook(images?: Record) { - // oxlint-disable-next-line typescript/no-explicit-any - const plugins = vinext({ nextConfig: () => ({ images }) }) as any[]; - const configPlugin = plugins.find((plugin) => plugin.name === "vinext:config"); - return configPlugin.config( - { root: APP_FIXTURE_DIR, plugins: [] }, - { command: "build", mode: "production" }, - ); -} - -async function resolveAliasMap(images?: Record) { - const config = await runConfigHook(images); - return aliasEntriesToRecord(config.resolve.alias); -} - describe("images.loaderFile resolve.alias wiring", () => { - let tmpDir: string; + let root: string; let loaderFile: string; + async function runConfigHook(images?: Record) { + // oxlint-disable-next-line typescript/no-explicit-any + const plugins = vinext({ nextConfig: () => ({ images }) }) as any[]; + const configPlugin = plugins.find((plugin) => plugin.name === "vinext:config"); + return configPlugin.config({ root, plugins: [] }, { command: "build", mode: "production" }); + } + + async function resolveAliasMap(images?: Record) { + const config = await runConfigHook(images); + return aliasEntriesToRecord(config.resolve.alias); + } + beforeAll(() => { - tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "vinext-image-loader-file-")); - loaderFile = path.join(tmpDir, "my-loader.js"); + root = fs.mkdtempSync(path.join(os.tmpdir(), "vinext-image-loader-file-")); + fs.symlinkSync( + path.resolve(import.meta.dirname, "../node_modules"), + path.join(root, "node_modules"), + "junction", + ); + fs.mkdirSync(path.join(root, "pages")); + fs.writeFileSync(path.join(root, "pages", "index.tsx"), "export default () => null;\n"); + loaderFile = path.join(root, "my-loader.js"); fs.writeFileSync(loaderFile, "export default ({ src }) => src;\n"); }); afterAll(() => { - fs.rmSync(tmpDir, { recursive: true, force: true }); + fs.rmSync(root, { recursive: true, force: true }); }); it("keeps vinext's undefined default when loaderFile is unset", async () => { @@ -56,7 +60,7 @@ describe("images.loaderFile resolve.alias wiring", () => { expect(unset["process.env.__VINEXT_IMAGE_CUSTOM_LOADER"]).toBe('"false"'); expect(unset["process.env.__VINEXT_IMAGE_LOADER_FILE"]).toBe('"false"'); - const custom = (await runConfigHook({ loader: "custom", loaderFile })).define; + const custom = (await runConfigHook({ loader: "custom", loaderFile: "./my-loader.js" })).define; expect(custom["process.env.__VINEXT_IMAGE_CUSTOM_LOADER"]).toBe('"true"'); expect(custom["process.env.__VINEXT_IMAGE_LOADER_FILE"]).toBe('"true"'); }); @@ -64,24 +68,29 @@ describe("images.loaderFile resolve.alias wiring", () => { it.each([undefined, "default", "custom"])( "resolves loaderFile against the project root when loader is %s", async (loader) => { - const aliasMap = await resolveAliasMap({ - loader, - loaderFile: path.relative(APP_FIXTURE_DIR, loaderFile), - }); + const aliasMap = await resolveAliasMap({ loader, loaderFile: "./my-loader.js" }); expect(aliasMap[SPECIFIER]).toBe(loaderFile); }, ); + // Next.js joins (not resolves) the path, so a leading slash stays + // project-relative, as in its loader-config named-export fixture. + it("treats a leading-slash loaderFile as project-relative", async () => { + const aliasMap = await resolveAliasMap({ loaderFile: "/my-loader.js" }); + expect(aliasMap[SPECIFIER]).toBe(loaderFile); + }); + it("rejects loaderFile combined with a built-in loader preset", async () => { - await expect(resolveAliasMap({ loader: "imgix", loaderFile })).rejects.toThrow( + await expect( + resolveAliasMap({ loader: "imgix", loaderFile: "./my-loader.js" }), + ).rejects.toThrow( 'Specified images.loader property (imgix) cannot be used with images.loaderFile property. Please set images.loader to "custom".', ); }); it("rejects a loaderFile that does not exist", async () => { - const missing = path.join(tmpDir, "missing-loader.js"); - await expect(resolveAliasMap({ loaderFile: missing })).rejects.toThrow( - `Specified images.loaderFile does not exist at "${missing}".`, + await expect(resolveAliasMap({ loaderFile: "./missing-loader.js" })).rejects.toThrow( + `Specified images.loaderFile does not exist at "${path.join(root, "missing-loader.js")}".`, ); }); }); diff --git a/tests/image-optimization-parity.test.ts b/tests/image-optimization-parity.test.ts index fafc17f6f8..6e5f13ac70 100644 --- a/tests/image-optimization-parity.test.ts +++ b/tests/image-optimization-parity.test.ts @@ -279,6 +279,7 @@ describe("App Router next/image with images.loaderFile", () => { } `, "app/image-parity/loader-file-variants/page.tsx": `import Image from "next/image"; +import LegacyImage from "next/legacy/image"; export default function Page() { return ( @@ -287,6 +288,7 @@ export default function Page() { fill override + ); } @@ -325,6 +327,48 @@ export default function Page() { "/hello world.png#w:64,q:50 1x, /hello world.png#w:128,q:50 2x", ); }); + + // Next.js's next/legacy/image has its own built-in loader and never imports + // the aliased image-loader module, so loaderFile leaves it untouched. + it("leaves next/legacy/image on the built-in loader", async () => { + const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/loader-file-variants"); + + expect(getImageSrcFromHtml(html, "legacy")).toBe( + "/_next/image?url=%2Fhello%20world.png&w=128&q=75", + ); + }); +}); + +// Ported from Next.js: test/e2e/app-dir/loader-file-named-export-custom-loader-error +// https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir/loader-file-named-export-custom-loader-error/loader-file-named-export-custom-loader-error.test.ts +describe("App Router next/image with a loaderFile lacking a default export", () => { + let server: ViteDevServer; + let baseUrl: string; + let fixtureDir: string; + + beforeAll(async () => { + fixtureDir = await createImageFixture("app", { + // Leading slash is project-relative, as in the upstream fixture's config. + nextConfig: 'export default { images: { loaderFile: "/named-loader.mjs" } };\n', + files: { + "named-loader.mjs": "export function namedLoader({ src }) {\n return src;\n}\n", + }, + }); + ({ server, baseUrl } = await startFixtureServer(fixtureDir, { appRouter: true })); + }, 30000); + + afterAll(async () => { + await server?.close(); + await fs.rm(fixtureDir, { recursive: true, force: true }); + }); + + it("reports Next.js's missing default export error", async () => { + const res = await fetch(`${baseUrl}/image-parity`); + const body = await res.text(); + + expect(res.status).toBe(500); + expect(body).toContain("images.loaderFile detected but the file is missing default export."); + }); }); runLocalImageUrlParitySuite("app"); From ea6fda7a2517e9f78b62e187d261917ff4fe6f15 Mon Sep 17 00:00:00 2001 From: James Date: Tue, 6 Oct 2026 05:47:20 +0100 Subject: [PATCH 07/16] fix(image): keep priority, data-nimg and blur styles on custom-loader images Next.js applies fetchPriority, data-nimg and the blur placeholder background independently of which loader produced the URL; the custom-loader branch (loader prop or images.loaderFile) dropped all three. --- packages/vinext/src/shims/image.tsx | 14 +++++++++++++- tests/image-component.test.ts | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 10c272de97..ace022ae68 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -703,6 +703,16 @@ const Image = forwardRef(function Image( sizes, ); const resolvedSrc = overrideSrc || loaderAttributes.src; + const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; + const blurStyle = + !blurComplete && placeholder === "blur" && sanitizedBlur + ? { + backgroundImage: `url(${sanitizedBlur})`, + backgroundSize: "cover", + backgroundRepeat: "no-repeat", + backgroundPosition: "center", + } + : undefined; preloadImageResource({ shouldPreload, src: resolvedSrc, @@ -717,6 +727,7 @@ const Image = forwardRef(function Image( width={fill ? undefined : imgWidth} height={fill ? undefined : imgHeight} loading={imageLoading} + fetchPriority={priorityFetchPriority} decoding="async" srcSet={loaderAttributes.srcSet} sizes={loaderAttributes.sizes} @@ -724,9 +735,10 @@ const Image = forwardRef(function Image( // fetching `src` before it sees the responsive candidates. src={resolvedSrc} className={className} + data-nimg={fill ? "fill" : "1"} onLoad={handleLoad} onError={handleError} - style={fill ? getFillStyle(style) : style} + style={fill ? getFillStyle(style, blurStyle) : { ...blurStyle, ...style }} {...rest} /> ); diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index 62c906ba6f..14abe26084 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -397,6 +397,27 @@ describe("Image SSR rendering", () => { expect(loader).not.toHaveBeenCalled(); }); + // Next.js applies these attributes regardless of which loader built the URL. + it("keeps priority, data-nimg and blur placeholder styles for custom loaders", () => { + const loader = ({ src, width }: { src: string; width: number }) => `${src}?w=${width}`; + const html = ReactDOMServer.renderToString( + React.createElement(Image, { + alt: "blur", + src: "/photo.jpg", + width: 100, + height: 100, + loader, + priority: true, + placeholder: "blur", + blurDataURL: "data:image/png;base64,iVBORw0KGgo=", + }), + ); + const img = html.match(/]*>/)?.[0] ?? ""; + expect(img).toContain('fetchPriority="high"'); + expect(img).toContain('data-nimg="1"'); + expect(img).toContain("background-image:url(data:image/png;base64,iVBORw0KGgo=)"); + }); + // Next.js keeps `src` after `sizes`/`srcSet` so Safari doesn't fetch it early. it("orders src after srcSet and sizes for custom loaders", () => { const loader = ({ src, width }: { src: string; width: number }) => `${src}?w=${width}`; From c08f0b3b992a8b5e7a95209d79e14b07189e0e3f Mon Sep 17 00:00:00 2001 From: James Date: Tue, 6 Oct 2026 06:07:25 +0100 Subject: [PATCH 08/16] fix(image): treat empty sources as unoptimized and ignore caller srcSet --- packages/vinext/src/shims/image.tsx | 7 ++++++- tests/image-component.test.ts | 26 +++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index ace022ae68..1aa59114dc 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -469,8 +469,9 @@ function resolveImageLoader( return effectiveLoader; } +/** Sources Next.js always treats as unoptimized (empty, data: and blob:). */ function isInlineSrc(src: string): boolean { - return src.startsWith("data:") || src.startsWith("blob:"); + return !src || src.startsWith("data:") || src.startsWith("blob:"); } /** Internal: set by shims/legacy-image.tsx, which wraps this component. */ @@ -503,6 +504,9 @@ const Image = forwardRef(function Image( }, ref, ) { + // Next.js drops a caller-provided srcSet (`delete rest.srcSet` in getImgProps) + // so it can't override the generated candidates. + delete (rest as { srcSet?: unknown }).srcSet; // Dedup refs: ensure onLoad and onError fire at most once per src per mount. // Matches Next.js behavior — prevents double-firing from React re-renders, // strict-mode double-invocation, or state updates inside the handler itself. @@ -943,6 +947,7 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { loading, ...rest } = props; + delete (rest as { srcSet?: unknown }).srcSet; const { src, diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index 14abe26084..91695c2026 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -381,13 +381,14 @@ describe("Image SSR rendering", () => { }); // Next.js marks data:/blob: sources unoptimized before generateImgAttrs. - it("never passes data: or blob: sources to a custom loader", () => { + it("never passes data:, blob: or empty sources to a custom loader", () => { const loader = vi.fn(({ src, width }: { src: string; width: number }) => `${src}?w=${width}`); - for (const src of ["data:image/png;base64,iVBORw0KGgo=", "blob:https://example.com/uuid"]) { + for (const src of ["data:image/png;base64,iVBORw0KGgo=", "blob:https://example.com/uuid", ""]) { const imageProps = { alt: "inline", src, width: 100, height: 100, loader }; const html = ReactDOMServer.renderToString(React.createElement(Image, imageProps)); - expect(html).toContain(`src="${src}"`); + // React omits an empty src attribute entirely. + if (src) expect(html).toContain(`src="${src}"`); expect(html).not.toContain("srcSet"); const { props } = getImageProps(imageProps); @@ -397,6 +398,25 @@ describe("Image SSR rendering", () => { expect(loader).not.toHaveBeenCalled(); }); + // Next.js deletes a caller-provided srcSet before building the attributes. + it("ignores a caller-provided srcSet", () => { + const loader = ({ src, width }: { src: string; width: number }) => `${src}?w=${width}`; + const imageProps = { + alt: "srcset", + src: "/photo.jpg", + width: 100, + height: 100, + loader, + srcSet: "/evil.jpg 1x", + } as Parameters[0]; + const srcSet = "/photo.jpg?w=128 1x, /photo.jpg?w=256 2x"; + + const html = ReactDOMServer.renderToString(React.createElement(Image, imageProps)); + expect(html).toContain(`srcSet="${srcSet}"`); + expect(html).not.toContain("/evil.jpg"); + expect(getImageProps(imageProps).props.srcSet).toBe(srcSet); + }); + // Next.js applies these attributes regardless of which loader built the URL. it("keeps priority, data-nimg and blur placeholder styles for custom loaders", () => { const loader = ({ src, width }: { src: string; width: number }) => `${src}?w=${width}`; From 873ef6958a23617200c7cf7050b0616c39bce5f2 Mon Sep 17 00:00:00 2001 From: James Date: Wed, 7 Oct 2026 01:06:15 +0100 Subject: [PATCH 09/16] refactor(image): share the unoptimized and custom loader render path --- packages/vinext/src/index.ts | 10 ++-- packages/vinext/src/shims/image.tsx | 78 ++++++++--------------------- 2 files changed, 27 insertions(+), 61 deletions(-) diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index 88f9cf1ccd..08c2d08b6e 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -1311,6 +1311,11 @@ const _appRscCombinedHandlerPath = resolveShimModulePath(_serverDir, "app-rsc-co const _appRscHandlerPath = resolveShimModulePath(_serverDir, "app-rsc-handler"); const _pagesClientAssetsPath = resolveShimModulePath(_serverDir, "pages-client-assets"); const _imageLoaderFilePath = resolveShimModulePath(_shimsDir, "image-loader-file"); +// Source checkouts resolve to TypeScript and must stay in Vite's graph so tests +// do not execute a stale dist build. Published packages resolve to emitted JS, +// which Node can load natively outside the RSC transform graph. +const _canExternalizeAppRscHandler = + _appRscHandlerPath.endsWith(".js") && _appRscCombinedHandlerPath.endsWith(".js"); /** * Resolve the module behind `vinext/shims/image-loader-file`. Ported from @@ -1333,11 +1338,6 @@ function resolveImageLoaderFile(images: NextConfig["images"], root: string): str } return absolutePath; } -// Source checkouts resolve to TypeScript and must stay in Vite's graph so tests -// do not execute a stale dist build. Published packages resolve to emitted JS, -// which Node can load natively outside the RSC transform graph. -const _canExternalizeAppRscHandler = - _appRscHandlerPath.endsWith(".js") && _appRscCombinedHandlerPath.endsWith(".js"); function isValidExportIdentifier(name: string): boolean { return /^[$A-Z_a-z][$\w]*$/.test(name); diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 1aa59114dc..c8827d21cc 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -652,61 +652,27 @@ const Image = forwardRef(function Image( // Next.js treats data:/blob: sources as unoptimized, so even a custom loader // never sees them. - if (_unoptimized === true || __globallyUnoptimized || (effectiveLoader && isInlineSrc(src))) { + const unoptimized = + _unoptimized === true || __globallyUnoptimized || (!!effectiveLoader && isInlineSrc(src)); + if (unoptimized || effectiveLoader) { // Unoptimized images are fetched directly by the browser, so intentionally // skip remote URL validation: there is no server-side optimizer fetch and - // therefore no SSRF surface. This matches Next.js behavior. - const renderedSrc = overrideSrc || src; - const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; - const blurStyle = - !blurComplete && placeholder === "blur" && sanitizedBlur - ? { - backgroundImage: `url(${sanitizedBlur})`, - backgroundSize: "cover", - backgroundRepeat: "no-repeat", - backgroundPosition: "center", - } + // therefore no SSRF surface. This matches Next.js behavior. A custom + // loader (the `loader` prop, or `images.loaderFile` when no prop is given) + // owns the URL the same way, and gets the built-in loader's per-width + // srcSet. `quality` is passed through as given (possibly undefined); only + // the built-in loader defaults it to 75. + const loaderAttributes = + effectiveLoader && !unoptimized + ? generateLoaderAttributes( + effectiveLoader, + src, + fill ? undefined : imgWidth, + typeof quality === "string" ? Number(quality) : quality, + sizes, + ) : undefined; - preloadImageResource({ - shouldPreload, - src: renderedSrc, - fetchPriority: priorityFetchPriority, - }); - return ( - {alt} - ); - } - - // A custom loader — either the `loader` prop, or `images.loaderFile` from - // next.config.js when no per-image prop was given — takes full - // responsibility for the URL, bypassing remotePatterns validation and the - // /_next/image endpoint. `quality` is passed through as given (possibly - // undefined); only the built-in loader defaults it to 75. - if (effectiveLoader) { - const resolvedQuality = typeof quality === "string" ? Number(quality) : quality; - const loaderAttributes = generateLoaderAttributes( - effectiveLoader, - src, - fill ? undefined : imgWidth, - resolvedQuality, - sizes, - ); - const resolvedSrc = overrideSrc || loaderAttributes.src; + const resolvedSrc = overrideSrc || (loaderAttributes ? loaderAttributes.src : src); const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; const blurStyle = !blurComplete && placeholder === "blur" && sanitizedBlur @@ -720,8 +686,8 @@ const Image = forwardRef(function Image( preloadImageResource({ shouldPreload, src: resolvedSrc, - srcSet: loaderAttributes.srcSet, - sizes: loaderAttributes.sizes, + srcSet: loaderAttributes?.srcSet, + sizes: loaderAttributes?.sizes, fetchPriority: priorityFetchPriority, }); return ( @@ -733,8 +699,8 @@ const Image = forwardRef(function Image( loading={imageLoading} fetchPriority={priorityFetchPriority} decoding="async" - srcSet={loaderAttributes.srcSet} - sizes={loaderAttributes.sizes} + srcSet={loaderAttributes?.srcSet} + sizes={loaderAttributes?.sizes} // After srcSet/sizes, as in Next.js: Safari would otherwise start // fetching `src` before it sees the responsive candidates. src={resolvedSrc} From d927ceb7bc1badfa3f738766aea9279c01b23a2a Mon Sep 17 00:00:00 2001 From: James Date: Wed, 7 Oct 2026 01:39:33 +0100 Subject: [PATCH 10/16] fix(image): keep next/legacy/image from importing images.loaderFile next/image now resolves to shims/image-external.tsx, which applies the loaderFile loader and Next.js's loader checks before delegating to the shared shim. next/legacy/image imports the shared shim directly, so, as in Next.js, legacy-only pages never evaluate the loader file. --- .../vinext/src/build/client-build-config.ts | 1 + packages/vinext/src/index.ts | 4 +- packages/vinext/src/shims/image-external.tsx | 64 ++++++++++++ .../vinext/src/shims/image-loader-file.ts | 2 +- packages/vinext/src/shims/image.tsx | 98 +++++-------------- packages/vinext/src/shims/legacy-image.tsx | 21 +--- .../vinext/src/shims/public-shim-map.json | 2 +- packages/vinext/vite.config.ts | 2 +- tests/image-component.test.ts | 44 ++++++--- tests/image-loader-file.test.ts | 2 +- 10 files changed, 126 insertions(+), 114 deletions(-) create mode 100644 packages/vinext/src/shims/image-external.tsx diff --git a/packages/vinext/src/build/client-build-config.ts b/packages/vinext/src/build/client-build-config.ts index f6560d6f31..97904a83d6 100644 --- a/packages/vinext/src/build/client-build-config.ts +++ b/packages/vinext/src/build/client-build-config.ts @@ -14,6 +14,7 @@ const ROUTE_OWNED_CLIENT_SHIMS = new Set([ "dynamic-preload-chunks", "form", "image", + "image-external", "internal/hybrid-client-route-owner", "layout-segment-context", "legacy-image", diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index c4b9ac74a4..0697b9c5c8 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -2908,7 +2908,7 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { String(nextConfig.images?.unoptimized === true), ); // images.loader / images.loaderFile modes the next/image shim validates - // against at render time (see resolveImageLoader in shims/image.tsx). + // against at render time (shims/image-external.tsx, shims/image.tsx). defines["process.env.__VINEXT_IMAGE_CUSTOM_LOADER"] = JSON.stringify( String(nextConfig.images?.loader === "custom"), ); @@ -3562,7 +3562,7 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { ...nextConfig.aliases, ...nextShimMap, "vinext/server/pages-client-assets": _pagesClientAssetsPath, - // shims/image.tsx imports this slot for `images.loaderFile`. + // shims/image-external.tsx imports this slot for `images.loaderFile`. // Like Next.js (which aliases next/dist/shared/lib/image-loader // to the file), point it at the user's file, resolved against // the project root; otherwise keep vinext's `undefined` default. diff --git a/packages/vinext/src/shims/image-external.tsx b/packages/vinext/src/shims/image-external.tsx new file mode 100644 index 0000000000..b38241e924 --- /dev/null +++ b/packages/vinext/src/shims/image-external.tsx @@ -0,0 +1,64 @@ +"use client"; + +/** + * next/image entry: the shared shim in ./image.tsx plus `images.loaderFile`. + * + * Mirrors Next.js, where next/image (shared/lib/image-external.tsx) imports + * the default image-loader module that `images.loaderFile` is aliased over, + * while next/legacy/image never imports it. shims/legacy-image.tsx imports + * ./image.tsx directly, so legacy-only pages never evaluate the loader file. + */ +import { forwardRef } from "react"; +// The vinext plugin aliases this specifier to the user's `images.loaderFile`. +// A namespace import, so a file without a default export reaches the +// diagnostic below instead of failing module linking. +import * as imageLoaderFileModule from "vinext/shims/image-loader-file"; +import ImageWithoutLoaderFile, { + getImageProps as getImagePropsWithoutLoaderFile, + missingLoaderError, + type ImageLoader, + type ImageProps, +} from "./image.js"; + +export type { + ImageLoader, + ImageLoaderProps, + ImageProps, + StaticImageData, + StaticRequire, +} from "./image.js"; + +const configuredImageLoader: ImageLoader | undefined = imageLoaderFileModule.default; +/** `images.loaderFile` is set, so `configuredImageLoader` must be its default export. */ +const __hasImageLoaderFile = process.env.__VINEXT_IMAGE_LOADER_FILE === "true"; +/** `images.loader: "custom"`: images need a loader prop or `images.loaderFile`. */ +const __customImageLoader = process.env.__VINEXT_IMAGE_CUSTOM_LOADER === "true"; + +/** Ported from the loader checks at the top of Next.js's getImgProps. */ +function withConfiguredLoader(props: ImageProps): ImageProps { + if (__hasImageLoaderFile && typeof configuredImageLoader === "undefined") { + throw new Error( + "images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config", + ); + } + const loader = props.loader || configuredImageLoader; + if (!loader && __customImageLoader) { + const { src } = props; + throw missingLoaderError( + typeof src === "string" ? src : ("default" in src ? src.default : src).src, + ); + } + return loader === props.loader ? props : { ...props, loader }; +} + +const ImageWithLoaderFile = forwardRef(function Image(props, ref) { + return ; +}); + +export function getImageProps( + props: ImageProps, +): ReturnType { + return getImagePropsWithoutLoaderFile(withConfiguredLoader(props)); +} + +export default ImageWithLoaderFile; diff --git a/packages/vinext/src/shims/image-loader-file.ts b/packages/vinext/src/shims/image-loader-file.ts index e0f819a1ff..13ec0e9c35 100644 --- a/packages/vinext/src/shims/image-loader-file.ts +++ b/packages/vinext/src/shims/image-loader-file.ts @@ -1,5 +1,5 @@ /** - * The `images.loaderFile` slot imported by shims/image.tsx. + * The `images.loaderFile` slot imported by shims/image-external.tsx (next/image). * * This module exports `undefined` (no configured loader file, so the built-in * /_next/image loader applies). When next.config.js sets `images.loaderFile`, diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index c8827d21cc..532716c139 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -26,13 +26,6 @@ import type { import { getDeploymentId } from "../utils/deployment-id.js"; import { hasRemoteMatch, isPrivateIp, type RemotePattern } from "./image-config.js"; import { useMergedRef } from "./use-merged-ref.js"; -// The user's `images.loaderFile` module when next.config.js sets one (the -// vinext plugin aliases this specifier to it). A namespace import so a file -// without a default export reaches resolveImageLoader's diagnostic instead of -// failing module linking. -import * as imageLoaderFileModule from "vinext/shims/image-loader-file"; - -const configuredImageLoader: ImageLoader | undefined = imageLoaderFileModule.default; export type { ImageLoader, StaticImageData, StaticRequire }; export type ImageLoaderProps = Parameters[0]; @@ -89,10 +82,8 @@ const __dangerouslyAllowSVG = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG = */ const __dangerouslyAllowLocalIP = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_LOCAL_IP === "true"; const __globallyUnoptimized = process.env.__VINEXT_IMAGE_UNOPTIMIZED === "true"; -/** `images.loader: "custom"` — images without a loader prop or loaderFile throw. */ +/** `images.loader: "custom"`: optimized images need a loader prop. */ const __customImageLoader = process.env.__VINEXT_IMAGE_CUSTOM_LOADER === "true"; -/** `images.loaderFile` is set, so `configuredImageLoader` must be its default export. */ -const __hasImageLoaderFile = process.env.__VINEXT_IMAGE_LOADER_FILE === "true"; /** * Whether trailingSlash is enabled in next.config.js. Mirrors the define * consumed by the Link/Router shims (shims/link.tsx, shims/router.ts, @@ -354,7 +345,7 @@ function getImageWidths(width: number): number[] { ]; } -function generateAttributesWithResolver( +function generateImageAttributes( resolveUrl: (src: string, width: number, quality?: number) => string, src: string, width: number | undefined, @@ -401,17 +392,8 @@ function generateAttributesWithResolver( }; } -function generateImageAttributes( - src: string, - width: number, - quality: number = 75, - sizes?: string, -): { src: string; srcSet: string } { - return generateAttributesWithResolver(imageOptimizationUrl, src, width, quality, sizes); -} - /** - * Same per-width srcSet treatment as generateImageAttributes, but routed + * Same per-width srcSet treatment as the built-in loader, but routed * through a user-supplied loader (the `loader` prop or `images.loaderFile`) * instead of the built-in /_next/image endpoint. Unlike the built-in loader, * `quality` is passed through as given — including `undefined` — so a @@ -425,7 +407,7 @@ function generateLoaderAttributes( quality: number | undefined, sizes?: string, ): { src: string; srcSet: string; sizes?: string } { - return generateAttributesWithResolver( + return generateImageAttributes( (loaderSrc, loaderWidth, loaderQuality) => loader({ src: loaderSrc, width: loaderWidth, quality: loaderQuality }), src, @@ -435,51 +417,21 @@ function generateLoaderAttributes( ); } -function missingLoaderError(src: string): Error { +/** Internal: also thrown by shims/image-external.tsx for next/image. */ +export function missingLoaderError(src: string): Error { return new Error( `Image with src "${src}" is missing "loader" prop.` + "\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader", ); } -/** - * Pick the loader for an image: the `loader` prop, else `images.loaderFile`, - * else `undefined` for the built-in /_next/image loader. Ported from the - * loader checks at the top of Next.js's getImgProps (shared/lib/get-img-props.ts). - * - * `next/legacy/image` never consults `images.loaderFile` in Next.js, and its - * built-in "custom" loader only throws when asked for a URL (optimized images). - */ -function resolveImageLoader( - src: string, - loader: ImageLoader | undefined, - legacy?: { unoptimized: boolean }, -): ImageLoader | undefined { - if (legacy) { - if (!loader && __customImageLoader && !legacy.unoptimized) throw missingLoaderError(src); - return loader; - } - if (__hasImageLoaderFile && typeof configuredImageLoader === "undefined") { - throw new Error( - "images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config", - ); - } - const effectiveLoader = loader ?? configuredImageLoader; - if (!effectiveLoader && __customImageLoader) throw missingLoaderError(src); - return effectiveLoader; -} - /** Sources Next.js always treats as unoptimized (empty, data: and blob:). */ function isInlineSrc(src: string): boolean { return !src || src.startsWith("data:") || src.startsWith("blob:"); } -/** Internal: set by shims/legacy-image.tsx, which wraps this component. */ -type InternalImageProps = ImageProps & { __vinextLegacyImage?: boolean }; - -const Image = forwardRef(function Image( +const Image = forwardRef(function Image( { - __vinextLegacyImage, src: srcProp, alt, width, @@ -554,13 +506,13 @@ const Image = forwardRef(function Image( height: imgHeight, blurDataURL: imgBlurDataURL, } = resolveImageSource({ src: srcProp, width, height, blurDataURL }); - const effectiveLoader = resolveImageLoader( - src, - loader, - __vinextLegacyImage - ? { unoptimized: _unoptimized === true || __globallyUnoptimized || isInlineSrc(src) } - : undefined, - ); + // next/legacy/image's built-in "custom" loader only throws when it has to + // build a URL. next/image rejects a missing loader earlier, regardless of + // `unoptimized` (shims/image-external.tsx). + const unoptimizedProp = _unoptimized === true || __globallyUnoptimized; + if (!loader && __customImageLoader && !unoptimizedProp && !isInlineSrc(src)) { + throw missingLoaderError(src); + } const shouldPreload = preload === true || priority === true; const priorityFetchPriority = priority ? "high" : undefined; const imageLoading = priority ? "eager" : shouldPreload ? loading : (loading ?? "lazy"); @@ -652,9 +604,8 @@ const Image = forwardRef(function Image( // Next.js treats data:/blob: sources as unoptimized, so even a custom loader // never sees them. - const unoptimized = - _unoptimized === true || __globallyUnoptimized || (!!effectiveLoader && isInlineSrc(src)); - if (unoptimized || effectiveLoader) { + const unoptimized = unoptimizedProp || (!!loader && isInlineSrc(src)); + if (unoptimized || loader) { // Unoptimized images are fetched directly by the browser, so intentionally // skip remote URL validation: there is no server-side optimizer fetch and // therefore no SSRF surface. This matches Next.js behavior. A custom @@ -663,9 +614,9 @@ const Image = forwardRef(function Image( // srcSet. `quality` is passed through as given (possibly undefined); only // the built-in loader defaults it to 75. const loaderAttributes = - effectiveLoader && !unoptimized + loader && !unoptimized ? generateLoaderAttributes( - effectiveLoader, + loader, src, fill ? undefined : imgWidth, typeof quality === "string" ? Number(quality) : quality, @@ -822,7 +773,7 @@ const Image = forwardRef(function Image( // Each entry points to /_next/image with the appropriate width. const optimizedAttributes = imgWidth && !fill && !skipOptimization - ? generateImageAttributes(src, imgWidth, imgQuality, sizes) + ? generateImageAttributes(imageOptimizationUrl, src, imgWidth, imgQuality, sizes) : undefined; const srcSet = optimizedAttributes ? optimizedAttributes.srcSet @@ -921,10 +872,9 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { height: imgHeight, blurDataURL: imgBlurDataURL, } = resolveImageSource({ src: srcProp, width, height, blurDataURL: blurDataURLProp }); - const effectiveLoader = resolveImageLoader(src, loader); const shouldPreload = _preload === true || priority === true; - if (_unoptimized === true || __globallyUnoptimized || (effectiveLoader && isInlineSrc(src))) { + if (_unoptimized === true || __globallyUnoptimized || (loader && isInlineSrc(src))) { // As in the component path, unoptimized images never reach the server-side // optimizer, so remote URL validation is intentionally unnecessary. const renderedSrc = overrideSrc || src; @@ -965,7 +915,7 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { // path (and Next.js's default loader), a custom loader owns the URL, so // remotePatterns don't apply to it. let blockedInProd = false; - if (!effectiveLoader && isRemoteUrl(src)) { + if (!loader && isRemoteUrl(src)) { const validation = validateRemoteUrl(src); if (!validation.allowed) { if (__isDev) { @@ -982,9 +932,9 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { if (blockedInProd) { optimizedSrc = ""; srcSet = undefined; - } else if (effectiveLoader) { + } else if (loader) { const loaderAttributes = generateLoaderAttributes( - effectiveLoader, + loader, src, fill ? undefined : imgWidth, imgQuality, @@ -1002,7 +952,7 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { const skipOpt = (isSvg && !__dangerouslyAllowSVG) || isRemoteUrl(src); const optimizedAttributes = imgWidth && !fill && !skipOpt - ? generateImageAttributes(src, imgWidth, resolvedQuality, sizes) + ? generateImageAttributes(imageOptimizationUrl, src, imgWidth, resolvedQuality, sizes) : null; optimizedSrc = skipOpt ? src diff --git a/packages/vinext/src/shims/legacy-image.tsx b/packages/vinext/src/shims/legacy-image.tsx index f1e15e56f8..aa49d9607c 100644 --- a/packages/vinext/src/shims/legacy-image.tsx +++ b/packages/vinext/src/shims/legacy-image.tsx @@ -52,16 +52,7 @@ function LegacyImage(props: ImageProps): React.ReactElement { : onLoad; if (layout === "fill") { - return ( - {alt - ); + return {alt; } if (layout === "responsive") { @@ -75,15 +66,7 @@ function LegacyImage(props: ImageProps): React.ReactElement { const h = typeof height === "string" ? parseInt(height, 10) : height; return ( - {alt + {alt ); } diff --git a/packages/vinext/src/shims/public-shim-map.json b/packages/vinext/src/shims/public-shim-map.json index 0696548183..1ba3b071af 100644 --- a/packages/vinext/src/shims/public-shim-map.json +++ b/packages/vinext/src/shims/public-shim-map.json @@ -3,7 +3,7 @@ "next/head": { "shim": "head", "types": "upstream" }, "next/router": { "shim": "router", "types": "upstream" }, "next/compat/router": { "shim": "compat-router", "types": "upstream" }, - "next/image": { "shim": "image", "types": "upstream" }, + "next/image": { "shim": "image-external", "types": "upstream" }, "next/legacy/image": { "shim": "legacy-image", "types": "upstream" }, "next/dynamic": { "shim": "dynamic", "types": "upstream" }, "next/app": { "shim": "app", "types": "upstream" }, diff --git a/packages/vinext/vite.config.ts b/packages/vinext/vite.config.ts index 73ed21a8f9..c13b374970 100644 --- a/packages/vinext/vite.config.ts +++ b/packages/vinext/vite.config.ts @@ -66,7 +66,7 @@ const externalizeBareThirdPartySpecifiers = ( isResolved: boolean, ) => { if (isResolved) return false; - // shims/image.tsx imports the `images.loaderFile` slot by this bare + // shims/image-external.tsx imports the `images.loaderFile` slot by this bare // specifier so the vinext plugin can alias it to the user's loader file. // Keep it bare in `dist` instead of rewriting it to a relative import. if (id === "vinext/shims/image-loader-file") return true; diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index 91695c2026..ba6b6446b5 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -131,7 +131,7 @@ describe("images.loader config validation", () => { it('throws for an image without a loader prop when images.loader is "custom"', async () => { process.env.__VINEXT_IMAGE_CUSTOM_LOADER = "true"; vi.resetModules(); - const shim = await import("../packages/vinext/src/shims/image.js"); + const shim = await import("../packages/vinext/src/shims/image-external.js"); const imageProps = { alt: "a", src: "/photo.jpg", width: 100, height: 100 }; const message = 'Image with src "/photo.jpg" is missing "loader" prop.'; @@ -148,30 +148,44 @@ describe("images.loader config validation", () => { it("throws when images.loaderFile has no default export", async () => { process.env.__VINEXT_IMAGE_LOADER_FILE = "true"; vi.resetModules(); - const shim = await import("../packages/vinext/src/shims/image.js"); + const shim = await import("../packages/vinext/src/shims/image-external.js"); expect(() => shim.getImageProps({ alt: "a", src: "/photo.jpg", width: 100, height: 100 }), ).toThrow("images.loaderFile detected but the file is missing default export."); }); - // Next.js's next/legacy/image never reads loaderFile, and its "custom" loader - // only throws when it has to build a URL (client/legacy/image.tsx). + // Next.js's next/legacy/image never imports the loaderFile module, and its + // "custom" loader only throws when it has to build a URL (client/legacy/image.tsx). it("keeps next/legacy/image off loaderFile and lets unoptimized images through", async () => { process.env.__VINEXT_IMAGE_CUSTOM_LOADER = "true"; process.env.__VINEXT_IMAGE_LOADER_FILE = "true"; vi.resetModules(); - const { default: LegacyImage } = await import("../packages/vinext/src/shims/legacy-image.js"); - const imageProps = { alt: "a", src: "/photo.jpg", width: 100, height: 100 }; - - expect( - ReactDOMServer.renderToString( - React.createElement(LegacyImage, { ...imageProps, unoptimized: true }), - ), - ).toContain('src="/photo.jpg"'); - expect(() => - ReactDOMServer.renderToString(React.createElement(LegacyImage, imageProps)), - ).toThrow('Image with src "/photo.jpg" is missing "loader" prop.'); + const loaderFileEvaluated = vi.fn(); + vi.doMock("vinext/shims/image-loader-file", () => { + loaderFileEvaluated(); + return { default: undefined }; + }); + try { + const { default: LegacyImage } = await import("../packages/vinext/src/shims/legacy-image.js"); + const imageProps = { alt: "a", src: "/photo.jpg", width: 100, height: 100 }; + + expect( + ReactDOMServer.renderToString( + React.createElement(LegacyImage, { ...imageProps, unoptimized: true }), + ), + ).toContain('src="/photo.jpg"'); + expect(() => + ReactDOMServer.renderToString(React.createElement(LegacyImage, imageProps)), + ).toThrow('Image with src "/photo.jpg" is missing "loader" prop.'); + expect(loaderFileEvaluated).not.toHaveBeenCalled(); + + // The next/image entry is the only importer of the loader file. + await import("../packages/vinext/src/shims/image-external.js"); + expect(loaderFileEvaluated).toHaveBeenCalledOnce(); + } finally { + vi.doUnmock("vinext/shims/image-loader-file"); + } }); }); diff --git a/tests/image-loader-file.test.ts b/tests/image-loader-file.test.ts index 6a4fba62b9..9c7354987a 100644 --- a/tests/image-loader-file.test.ts +++ b/tests/image-loader-file.test.ts @@ -1,7 +1,7 @@ /** * `images.loaderFile` config wiring. * - * shims/image.tsx imports `vinext/shims/image-loader-file`; the vinext plugin + * shims/image-external.tsx imports `vinext/shims/image-loader-file`; the vinext plugin * aliases that specifier to the configured loader file, mirroring how Next.js * aliases `next/dist/shared/lib/image-loader` to it. The rules come from the * `images.loaderFile` normalization in Next.js's server/config.ts. See From 17031fff0b537455f70defe61547fbd83e36dee9 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 8 Oct 2026 10:48:59 +0100 Subject: [PATCH 11/16] test(image): cover trailingSlash, loader srcSet and loaderFile in the static-export e2e fixture Replace the temporary-fixture dev-server tests in image-optimization-parity with a Playwright spec against the checked-in static-export fixture, which already sets trailingSlash: true. The fixture now sets images.loaderFile (Next.js's documented next/image setup for output: "export") and renders next/image with the loader file, a loader prop, overrideSrc and fill, plus next/legacy/image on the built-in loader. The fixture depends on ipaddr.js because Node SSR builds externalize it and pnpm does not hoist vinext's copy. --- pnpm-lock.yaml | 3 + tests/e2e/static-export/images.spec.ts | 77 +++++++ .../app/images/loader-prop-image.tsx | 17 ++ .../static-export/app/images/page.tsx | 25 +++ tests/fixtures/static-export/image-loader.ts | 13 ++ tests/fixtures/static-export/next.config.mjs | 3 + tests/fixtures/static-export/package.json | 1 + tests/image-optimization-parity.test.ts | 199 +----------------- 8 files changed, 140 insertions(+), 198 deletions(-) create mode 100644 tests/e2e/static-export/images.spec.ts create mode 100644 tests/fixtures/static-export/app/images/loader-prop-image.tsx create mode 100644 tests/fixtures/static-export/app/images/page.tsx create mode 100644 tests/fixtures/static-export/image-loader.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e1777bae73..c861adf6d7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2207,6 +2207,9 @@ importers: '@vitejs/plugin-rsc': specifier: 'catalog:' version: 0.5.34(@voidzero-dev/vite-plus-core@0.3.2(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(sass@1.100.0)(tsx@4.21.1)(typescript@7.0.2)(yaml@2.9.0))(react-dom@19.2.7(react@19.2.7))(react-server-dom-webpack@19.2.7(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + ipaddr.js: + specifier: 'catalog:' + version: 2.4.0 react: specifier: 'catalog:' version: 19.2.7 diff --git a/tests/e2e/static-export/images.spec.ts b/tests/e2e/static-export/images.spec.ts new file mode 100644 index 0000000000..677af881ac --- /dev/null +++ b/tests/e2e/static-export/images.spec.ts @@ -0,0 +1,77 @@ +import { test, expect, type Page } from "@playwright/test"; +import { waitForAppRouterHydration } from "../helpers"; + +/** + * next/image in a static export with `trailingSlash: true` and + * `images.loaderFile` (tests/fixtures/static-export/next.config.mjs). + * + * Ported from Next.js: + * test/e2e/next-image-new/loader-config/loader-config.test.ts + * https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/loader-config/loader-config.test.ts + * test/e2e/next-image-new/trailing-slash/trailing-slash.test.ts + * https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/trailing-slash/trailing-slash.test.ts + */ +const BASE = process.env.VINEXT_E2E_BASE_URL ?? "http://localhost:4180"; +const DEVICE_SIZES = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]; + +async function imageAttrs(page: Page, alt: string) { + const img = page.locator(`img[alt="${alt}"]`); + return { + src: await img.getAttribute("src"), + srcSet: await img.getAttribute("srcset"), + sizes: await img.getAttribute("sizes"), + }; +} + +test.describe("Static Export — next/image", () => { + test.beforeEach(async ({ page }) => { + const hydrationErrors: string[] = []; + page.on("console", (msg) => { + if (msg.type() === "error" && /hydrat/i.test(msg.text())) { + hydrationErrors.push(msg.text()); + } + }); + const response = await page.goto(`${BASE}/images/`); + expect(response?.status()).toBe(200); + await waitForAppRouterHydration(page); + expect(hydrationErrors).toEqual([]); + }); + + test("images without a loader prop use images.loaderFile", async ({ page }) => { + expect(await imageAttrs(page, "loader-file")).toEqual({ + src: "/logo.png#w:128,q:50", + srcSet: "/logo.png#w:64,q:50 1x, /logo.png#w:128,q:50 2x", + sizes: null, + }); + // overrideSrc replaces src but keeps the loader's srcSet. + expect(await imageAttrs(page, "loader-file-override")).toEqual({ + src: "/override.png", + srcSet: "/logo.png#w:64,q:50 1x, /logo.png#w:128,q:50 2x", + sizes: null, + }); + expect(await imageAttrs(page, "loader-file-fill")).toEqual({ + src: "/logo.png#w:3840,q:50", + srcSet: DEVICE_SIZES.map((w) => `/logo.png#w:${w},q:50 ${w}w`).join(", "), + sizes: "100vw", + }); + }); + + test("a loader prop gets every srcSet width and an unset quality", async ({ page }) => { + expect(await imageAttrs(page, "loader-prop")).toEqual({ + src: "/logo.png?w=128&q=auto", + srcSet: "/logo.png?w=64&q=auto 1x, /logo.png?w=128&q=auto 2x", + sizes: null, + }); + }); + + // next/legacy/image never imports images.loaderFile; its built-in loader + // uses images.path, which Next.js gives a trailing slash under trailingSlash. + test("next/legacy/image keeps the built-in loader with a trailing slash", async ({ page }) => { + expect(await imageAttrs(page, "legacy")).toEqual({ + src: "/_next/image/?url=%2Flogo.png&w=128&q=75", + srcSet: + "/_next/image/?url=%2Flogo.png&w=64&q=75 1x, /_next/image/?url=%2Flogo.png&w=128&q=75 2x", + sizes: null, + }); + }); +}); diff --git a/tests/fixtures/static-export/app/images/loader-prop-image.tsx b/tests/fixtures/static-export/app/images/loader-prop-image.tsx new file mode 100644 index 0000000000..13195b28cc --- /dev/null +++ b/tests/fixtures/static-export/app/images/loader-prop-image.tsx @@ -0,0 +1,17 @@ +"use client"; + +import Image from "next/image"; + +// A loader prop takes precedence over images.loaderFile. +export function LoaderPropImage() { + return ( + loader-prop `${src}?w=${width}&q=${quality ?? "auto"}`} + /> + ); +} diff --git a/tests/fixtures/static-export/app/images/page.tsx b/tests/fixtures/static-export/app/images/page.tsx new file mode 100644 index 0000000000..b9db9b591e --- /dev/null +++ b/tests/fixtures/static-export/app/images/page.tsx @@ -0,0 +1,25 @@ +import Image from "next/image"; +import LegacyImage from "next/legacy/image"; +import { LoaderPropImage } from "./loader-prop-image"; + +export default function ImagesPage() { + return ( +
+

Images

+ loader-file + loader-file-override +
+ loader-file-fill +
+ + +
+ ); +} diff --git a/tests/fixtures/static-export/image-loader.ts b/tests/fixtures/static-export/image-loader.ts new file mode 100644 index 0000000000..743b261dfa --- /dev/null +++ b/tests/fixtures/static-export/image-loader.ts @@ -0,0 +1,13 @@ +// Ported from Next.js: test/e2e/next-image-new/loader-config/dummy-loader.js +// https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/loader-config/dummy-loader.js +export default function dummyLoader({ + src, + width, + quality, +}: { + src: string; + width: number; + quality?: number; +}): string { + return `${src}#w:${width},q:${quality || 50}`; +} diff --git a/tests/fixtures/static-export/next.config.mjs b/tests/fixtures/static-export/next.config.mjs index 97ca800ab2..719ae0138a 100644 --- a/tests/fixtures/static-export/next.config.mjs +++ b/tests/fixtures/static-export/next.config.mjs @@ -4,4 +4,7 @@ export default { // Ported from Next.js: test/e2e/app-dir-export/test/trailing-slash.test.ts // https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir-export/test/trailing-slash.test.ts trailingSlash: true, + // Used by E2E: static-export/images.spec.ts. Next.js's documented way to use + // next/image with `output: "export"`; next/legacy/image ignores it. + images: { loaderFile: "./image-loader.ts" }, }; diff --git a/tests/fixtures/static-export/package.json b/tests/fixtures/static-export/package.json index e64856df35..21881724f3 100644 --- a/tests/fixtures/static-export/package.json +++ b/tests/fixtures/static-export/package.json @@ -4,6 +4,7 @@ "type": "module", "dependencies": { "@vitejs/plugin-rsc": "catalog:", + "ipaddr.js": "catalog:", "react": "catalog:", "react-dom": "catalog:", "react-server-dom-webpack": "catalog:", diff --git a/tests/image-optimization-parity.test.ts b/tests/image-optimization-parity.test.ts index 6e5f13ac70..072894a7e7 100644 --- a/tests/image-optimization-parity.test.ts +++ b/tests/image-optimization-parity.test.ts @@ -10,10 +10,7 @@ const PNG_1X1 = Buffer.from( "base64", ); -async function createImageFixture( - router: "app" | "pages", - options: { nextConfig?: string; files?: Record } = {}, -): Promise { +async function createImageFixture(router: "app" | "pages"): Promise { const baseFixtureDir = router === "app" ? APP_FIXTURE_DIR : PAGES_FIXTURE_DIR; const rootDir = await fs.mkdtemp(path.join(os.tmpdir(), `vinext-${router}-image-parity-`)); await fs.cp(baseFixtureDir, rootDir, { recursive: true }); @@ -66,29 +63,9 @@ export default function Page() { ); } - if (options.nextConfig !== undefined) { - // next.config.ts takes priority over other extensions, so overwrite it. - await fs.writeFile(path.join(rootDir, "next.config.ts"), options.nextConfig); - } - for (const [file, contents] of Object.entries(options.files ?? {})) { - await fs.mkdir(path.dirname(path.join(rootDir, file)), { recursive: true }); - await fs.writeFile(path.join(rootDir, file), contents); - } - return rootDir; } -function getImageSrcSetFromHtml(html: string, alt: string): string { - for (const match of html.matchAll(/]*>/g)) { - const tag = match[0]; - if (!tag.includes(`alt="${alt}"`)) continue; - const srcSetMatch = tag.match(/\ssrcSet="([^"]+)"/); - if (srcSetMatch) return srcSetMatch[1].replaceAll("&", "&"); - } - - throw new Error(`Could not find srcSet on tag for alt="${alt}"`); -} - function getImageSrcFromHtml(html: string, alt: string): string { for (const match of html.matchAll(/]*>/g)) { const tag = match[0]; @@ -197,179 +174,5 @@ describe("image deployment query parity", () => { }); }); -// Ported from Next.js: test/e2e/next-image-new/trailing-slash/trailing-slash.test.ts -// https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/trailing-slash/trailing-slash.test.ts -describe("App Router next/image with trailingSlash: true", () => { - let server: ViteDevServer; - let baseUrl: string; - let fixtureDir: string; - - beforeAll(async () => { - fixtureDir = await createImageFixture("app", { - nextConfig: "export default { trailingSlash: true };\n", - files: { - "app/image-parity/loader-prop/page.tsx": `"use client"; -import Image from "next/image"; - -export default function Page() { - return ( - loader-prop \`https://cdn.example.com\${src}?w=\${width}&q=\${quality ?? "auto"}\`} - /> - ); -} -`, - }, - }); - ({ server, baseUrl } = await startFixtureServer(fixtureDir, { appRouter: true })); - }, 30000); - - afterAll(async () => { - await server?.close(); - await fs.rm(fixtureDir, { recursive: true, force: true }); - }); - - it("emits /_next/image/ URLs that reach the image endpoint directly", async () => { - const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/"); - const src = getImageSrcFromHtml(html, "space"); - - expect(src).toBe("/_next/image/?url=%2Fhello%20world.png&w=128&q=75"); - expect(getImageSrcSetFromHtml(html, "space")).toBe( - "/_next/image/?url=%2Fhello%20world.png&w=64&q=75 1x, /_next/image/?url=%2Fhello%20world.png&w=128&q=75 2x", - ); - - // The dev image endpoint 302s to the source file; no trailing-slash 308 first. - const res = await fetch(new URL(src, baseUrl), { redirect: "manual" }); - expect(res.status).toBe(302); - expect(res.headers.get("location")).toBe("/hello%20world.png"); - }); - - // Next.js runs a custom loader through the same generateImgAttrs as the - // default loader (shared/lib/get-img-props.ts), passing quality unchanged. - it("gives a custom loader prop every srcSet width and an unset quality", async () => { - const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/loader-prop/"); - - expect(getImageSrcFromHtml(html, "loader-prop")).toBe( - "https://cdn.example.com/hello world.png?w=128&q=auto", - ); - expect(getImageSrcSetFromHtml(html, "loader-prop")).toBe( - "https://cdn.example.com/hello world.png?w=64&q=auto 1x, https://cdn.example.com/hello world.png?w=128&q=auto 2x", - ); - }); -}); - -// Ported from Next.js: test/e2e/next-image-new/loader-config/loader-config.test.ts -// https://github.com/vercel/next.js/blob/canary/test/e2e/next-image-new/loader-config/loader-config.test.ts -describe("App Router next/image with images.loaderFile", () => { - let server: ViteDevServer; - let baseUrl: string; - let fixtureDir: string; - - beforeAll(async () => { - fixtureDir = await createImageFixture("app", { - // Next.js applies loaderFile when images.loader is unset, "default" or "custom". - nextConfig: 'export default { images: { loaderFile: "./dummy-loader.mjs" } };\n', - files: { - "dummy-loader.mjs": `export default function dummyLoader({ src, width, quality }) { - return \`\${src}#w:\${width},q:\${quality || 50}\`; -} -`, - "app/image-parity/loader-file-variants/page.tsx": `import Image from "next/image"; -import LegacyImage from "next/legacy/image"; - -export default function Page() { - return ( -
-
- fill -
- override - -
- ); -} -`, - }, - }); - ({ server, baseUrl } = await startFixtureServer(fixtureDir, { appRouter: true })); - }, 30000); - - afterAll(async () => { - await server?.close(); - await fs.rm(fixtureDir, { recursive: true, force: true }); - }); - - it("routes images without a loader prop through the configured loader file", async () => { - const html = await fetchHtmlWithRetry(baseUrl, "/image-parity"); - - expect(getImageSrcFromHtml(html, "space")).toBe("/hello world.png#w:128,q:50"); - expect(getImageSrcSetFromHtml(html, "space")).toBe( - "/hello world.png#w:64,q:50 1x, /hello world.png#w:128,q:50 2x", - ); - }); - - it("gives fill images every device width and honors overrideSrc", async () => { - const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/loader-file-variants"); - const deviceSizes = [640, 750, 828, 1080, 1200, 1920, 2048, 3840]; - - expect(getImageSrcFromHtml(html, "fill")).toBe("/hello world.png#w:3840,q:50"); - expect(getImageSrcSetFromHtml(html, "fill")).toBe( - deviceSizes.map((w) => `/hello world.png#w:${w},q:50 ${w}w`).join(", "), - ); - expect(html).toMatch(/]*alt="fill"[^>]*sizes="100vw"/); - - expect(getImageSrcFromHtml(html, "override")).toBe("/override.png"); - expect(getImageSrcSetFromHtml(html, "override")).toBe( - "/hello world.png#w:64,q:50 1x, /hello world.png#w:128,q:50 2x", - ); - }); - - // Next.js's next/legacy/image has its own built-in loader and never imports - // the aliased image-loader module, so loaderFile leaves it untouched. - it("leaves next/legacy/image on the built-in loader", async () => { - const html = await fetchHtmlWithRetry(baseUrl, "/image-parity/loader-file-variants"); - - expect(getImageSrcFromHtml(html, "legacy")).toBe( - "/_next/image?url=%2Fhello%20world.png&w=128&q=75", - ); - }); -}); - -// Ported from Next.js: test/e2e/app-dir/loader-file-named-export-custom-loader-error -// https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir/loader-file-named-export-custom-loader-error/loader-file-named-export-custom-loader-error.test.ts -describe("App Router next/image with a loaderFile lacking a default export", () => { - let server: ViteDevServer; - let baseUrl: string; - let fixtureDir: string; - - beforeAll(async () => { - fixtureDir = await createImageFixture("app", { - // Leading slash is project-relative, as in the upstream fixture's config. - nextConfig: 'export default { images: { loaderFile: "/named-loader.mjs" } };\n', - files: { - "named-loader.mjs": "export function namedLoader({ src }) {\n return src;\n}\n", - }, - }); - ({ server, baseUrl } = await startFixtureServer(fixtureDir, { appRouter: true })); - }, 30000); - - afterAll(async () => { - await server?.close(); - await fs.rm(fixtureDir, { recursive: true, force: true }); - }); - - it("reports Next.js's missing default export error", async () => { - const res = await fetch(`${baseUrl}/image-parity`); - const body = await res.text(); - - expect(res.status).toBe(500); - expect(body).toContain("images.loaderFile detected but the file is missing default export."); - }); -}); - runLocalImageUrlParitySuite("app"); runLocalImageUrlParitySuite("pages"); From 94458479cc315d14327cdfe38d70064b977bece3 Mon Sep 17 00:00:00 2001 From: James Date: Thu, 8 Oct 2026 11:35:19 +0100 Subject: [PATCH 12/16] fix(image): never send data:, blob: or empty sources through /_next/image Next.js's getImgProps and next/legacy/image mark these sources unoptimized before building any URL. vinext only did that when a custom loader was present, so next/legacy/image under images.loader: "custom" (and the built-in loader generally) emitted /_next/image?url=data%3A... instead. Also make the static-export image spec fail on any console or page error, so production's minified hydration errors are caught. --- packages/vinext/src/shims/image.tsx | 8 ++--- tests/e2e/static-export/images.spec.ts | 17 ++++++++--- tests/image-component.test.ts | 42 +++++++++++++++++++------- 3 files changed, 48 insertions(+), 19 deletions(-) diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 532716c139..035108a70b 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -602,9 +602,9 @@ const Image = forwardRef(function Image( } : undefined; - // Next.js treats data:/blob: sources as unoptimized, so even a custom loader - // never sees them. - const unoptimized = unoptimizedProp || (!!loader && isInlineSrc(src)); + // Next.js (getImgProps and next/legacy/image) treats empty, data: and blob: + // sources as unoptimized, so neither a custom loader nor /_next/image sees them. + const unoptimized = unoptimizedProp || isInlineSrc(src); if (unoptimized || loader) { // Unoptimized images are fetched directly by the browser, so intentionally // skip remote URL validation: there is no server-side optimizer fetch and @@ -874,7 +874,7 @@ export function getImageProps(props: ImageProps): { props: ImgProps } { } = resolveImageSource({ src: srcProp, width, height, blurDataURL: blurDataURLProp }); const shouldPreload = _preload === true || priority === true; - if (_unoptimized === true || __globallyUnoptimized || (loader && isInlineSrc(src))) { + if (_unoptimized === true || __globallyUnoptimized || isInlineSrc(src)) { // As in the component path, unoptimized images never reach the server-side // optimizer, so remote URL validation is intentionally unnecessary. const renderedSrc = overrideSrc || src; diff --git a/tests/e2e/static-export/images.spec.ts b/tests/e2e/static-export/images.spec.ts index 677af881ac..71ca3b3c10 100644 --- a/tests/e2e/static-export/images.spec.ts +++ b/tests/e2e/static-export/images.spec.ts @@ -24,17 +24,26 @@ async function imageAttrs(page: Page, alt: string) { } test.describe("Static Export — next/image", () => { + let pageErrors: string[]; + test.beforeEach(async ({ page }) => { - const hydrationErrors: string[] = []; + // Every console error counts (production React reports a hydration + // mismatch as minified error #418), except the fixture's image URLs + // failing to load: the static host has no image files or optimizer. + pageErrors = []; page.on("console", (msg) => { - if (msg.type() === "error" && /hydrat/i.test(msg.text())) { - hydrationErrors.push(msg.text()); + if (msg.type() === "error" && !msg.text().startsWith("Failed to load resource")) { + pageErrors.push(msg.text()); } }); + page.on("pageerror", (error) => pageErrors.push(error.message)); const response = await page.goto(`${BASE}/images/`); expect(response?.status()).toBe(200); await waitForAppRouterHydration(page); - expect(hydrationErrors).toEqual([]); + }); + + test.afterEach(() => { + expect(pageErrors).toEqual([]); }); test("images without a loader prop use images.loaderFile", async ({ page }) => { diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index ba6b6446b5..43cd811b65 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -187,6 +187,22 @@ describe("images.loader config validation", () => { vi.doUnmock("vinext/shims/image-loader-file"); } }); + + // Next.js's legacy image marks data: and blob: sources unoptimized before + // it builds a URL, so its "custom" loader neither throws nor runs for them. + it("renders inline next/legacy/image sources as-is when images.loader is custom", async () => { + process.env.__VINEXT_IMAGE_CUSTOM_LOADER = "true"; + vi.resetModules(); + const { default: LegacyImage } = await import("../packages/vinext/src/shims/legacy-image.js"); + + for (const src of ["data:image/png;base64,iVBORw0KGgo=", "blob:https://example.com/id"]) { + const html = ReactDOMServer.renderToString( + React.createElement(LegacyImage, { alt: "a", src, width: 100, height: 100 }), + ); + expect(html).toContain(`src="${src}"`); + expect(html).not.toContain("/_next/image"); + } + }); }); // ─── SSR rendering ────────────────────────────────────────────────────── @@ -395,19 +411,23 @@ describe("Image SSR rendering", () => { }); // Next.js marks data:/blob: sources unoptimized before generateImgAttrs. - it("never passes data:, blob: or empty sources to a custom loader", () => { + it("never passes data:, blob: or empty sources to a custom loader or /_next/image", () => { const loader = vi.fn(({ src, width }: { src: string; width: number }) => `${src}?w=${width}`); for (const src of ["data:image/png;base64,iVBORw0KGgo=", "blob:https://example.com/uuid", ""]) { - const imageProps = { alt: "inline", src, width: 100, height: 100, loader }; - - const html = ReactDOMServer.renderToString(React.createElement(Image, imageProps)); - // React omits an empty src attribute entirely. - if (src) expect(html).toContain(`src="${src}"`); - expect(html).not.toContain("srcSet"); - - const { props } = getImageProps(imageProps); - expect(props.src).toBe(src); - expect(props.srcSet).toBeUndefined(); + for (const imageProps of [ + { alt: "inline", src, width: 100, height: 100, loader }, + { alt: "inline", src, width: 100, height: 100 }, + ]) { + const html = ReactDOMServer.renderToString(React.createElement(Image, imageProps)); + // React omits an empty src attribute entirely. + if (src) expect(html).toContain(`src="${src}"`); + expect(html).not.toContain("srcSet"); + expect(html).not.toContain("/_next/image"); + + const { props } = getImageProps(imageProps); + expect(props.src).toBe(src); + expect(props.srcSet).toBeUndefined(); + } } expect(loader).not.toHaveBeenCalled(); }); From ba15bbc4a6ae0aa4a1c3777f6dc36438b92ed9c1 Mon Sep 17 00:00:00 2001 From: AhmedElBanna80 Date: Wed, 14 Oct 2026 03:23:26 +0300 Subject: [PATCH 13/16] fix(image): keep next/legacy/image layout rules for custom-loader srcSet Legacy responsive images get every device width with w descriptors and sizes=100vw, and fixed/intrinsic images keep 1x/2x candidates even when given sizes, matching getWidths() in Next.js's client/legacy/image.tsx. --- packages/vinext/src/shims/image.tsx | 21 +++++++++-- packages/vinext/src/shims/legacy-image.tsx | 17 +++++++-- tests/image-component.test.ts | 41 ++++++++++++++++++++++ 3 files changed, 75 insertions(+), 4 deletions(-) diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index 035108a70b..b54136a6cd 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -351,8 +351,13 @@ function generateImageAttributes( width: number | undefined, quality: number | undefined, sizes?: string, + legacyLayout?: string, ): { src: string; srcSet: string; sizes?: string } { - if (sizes) { + // next/legacy/image (client/legacy/image.tsx getWidths): "responsive" and + // "fill" layouts always get `w` candidates, while "fixed" and "intrinsic" + // keep 1x/2x candidates and ignore `sizes` when choosing widths. + const legacyFluid = legacyLayout === "responsive" || legacyLayout === "fill"; + if (sizes && (!legacyLayout || legacyFluid)) { const viewportWidthPattern = /(^|\s)(1?\d?\d)vw/g; const viewportPercentages = Array.from(sizes.matchAll(viewportWidthPattern), (match) => Number.parseInt(match[2], 10), @@ -373,7 +378,7 @@ function generateImageAttributes( // No intrinsic width (e.g. `fill`): Next.js's getWidths() offers every // device size and defaults `sizes` to 100vw. - if (width === undefined) { + if (width === undefined || legacyFluid) { return { src: resolveUrl(src, RESPONSIVE_WIDTHS[RESPONSIVE_WIDTHS.length - 1], quality), srcSet: RESPONSIVE_WIDTHS.map( @@ -389,6 +394,7 @@ function generateImageAttributes( srcSet: widths .map((candidateWidth, index) => `${resolveUrl(src, candidateWidth, quality)} ${index + 1}x`) .join(", "), + sizes, }; } @@ -406,6 +412,7 @@ function generateLoaderAttributes( width: number | undefined, quality: number | undefined, sizes?: string, + legacyLayout?: string, ): { src: string; srcSet: string; sizes?: string } { return generateImageAttributes( (loaderSrc, loaderWidth, loaderQuality) => @@ -414,9 +421,16 @@ function generateLoaderAttributes( width, quality, sizes, + legacyLayout, ); } +/** + * Internal prop set only by shims/legacy-image.tsx so custom-loader srcSet + * candidates follow next/legacy/image's layout rules instead of next/image's. + */ +export type LegacyLayoutProp = { __vinextLegacyLayout?: string }; + /** Internal: also thrown by shims/image-external.tsx for next/image. */ export function missingLoaderError(src: string): Error { return new Error( @@ -459,6 +473,8 @@ const Image = forwardRef(function Image( // Next.js drops a caller-provided srcSet (`delete rest.srcSet` in getImgProps) // so it can't override the generated candidates. delete (rest as { srcSet?: unknown }).srcSet; + const legacyLayout = (rest as LegacyLayoutProp).__vinextLegacyLayout; + delete (rest as LegacyLayoutProp).__vinextLegacyLayout; // Dedup refs: ensure onLoad and onError fire at most once per src per mount. // Matches Next.js behavior — prevents double-firing from React re-renders, // strict-mode double-invocation, or state updates inside the handler itself. @@ -621,6 +637,7 @@ const Image = forwardRef(function Image( fill ? undefined : imgWidth, typeof quality === "string" ? Number(quality) : quality, sizes, + legacyLayout, ) : undefined; const resolvedSrc = overrideSrc || (loaderAttributes ? loaderAttributes.src : src); diff --git a/packages/vinext/src/shims/legacy-image.tsx b/packages/vinext/src/shims/legacy-image.tsx index aa49d9607c..b03267c61a 100644 --- a/packages/vinext/src/shims/legacy-image.tsx +++ b/packages/vinext/src/shims/legacy-image.tsx @@ -9,7 +9,7 @@ * codemod when upgrading from Next.js 12. */ import React from "react"; -import Image from "./image.js"; +import ModernImage, { type LegacyLayoutProp } from "./image.js"; import type { ImageLoader, ImageLoaderProps, @@ -18,6 +18,11 @@ import type { export type { ImageLoader, ImageLoaderProps, ImageProps }; +// The shared shim, plus the internal prop that selects legacy srcSet rules. +const Image = ModernImage as React.ComponentType< + React.ComponentProps & LegacyLayoutProp +>; + function LegacyImage(props: ImageProps): React.ReactElement { const { layout = "intrinsic", @@ -66,7 +71,15 @@ function LegacyImage(props: ImageProps): React.ReactElement { const h = typeof height === "string" ? parseInt(height, 10) : height; return ( - {alt + {alt ); } diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index 43cd811b65..5a768cf655 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -205,6 +205,47 @@ describe("images.loader config validation", () => { }); }); +// Ported from getWidths() in Next.js's client/legacy/image.tsx: a responsive +// legacy image gets every device width with `w` descriptors and sizes=100vw, +// while fixed/intrinsic images keep 1x/2x candidates even when given `sizes`. +describe("next/legacy/image layout semantics with a loader prop", () => { + const loader = ({ src, width }: { src: string; width: number }) => `${src}?w=${width}`; + + async function renderLegacy(props: Record): Promise { + const { default: LegacyImage } = await import("../packages/vinext/src/shims/legacy-image.js"); + return ReactDOMServer.renderToString( + React.createElement(LegacyImage, { + alt: "a", + src: "/photo.jpg", + width: 100, + height: 100, + loader, + ...props, + }), + ); + } + + it('uses every device width and sizes="100vw" for layout="responsive"', async () => { + const html = await renderLegacy({ layout: "responsive" }); + expect(html).toContain( + 'srcSet="/photo.jpg?w=640 640w, /photo.jpg?w=750 750w, /photo.jpg?w=828 828w, ' + + "/photo.jpg?w=1080 1080w, /photo.jpg?w=1200 1200w, /photo.jpg?w=1920 1920w, " + + '/photo.jpg?w=2048 2048w, /photo.jpg?w=3840 3840w"', + ); + expect(html).toContain('sizes="100vw"'); + expect(html).toContain('src="/photo.jpg?w=3840"'); + }); + + it("keeps 1x/2x candidates for fixed and intrinsic layouts given sizes", async () => { + for (const layout of ["fixed", "intrinsic"]) { + const html = await renderLegacy({ layout, sizes: "50vw" }); + expect(html).toContain('srcSet="/photo.jpg?w=128 1x, /photo.jpg?w=256 2x"'); + expect(html).toContain('sizes="50vw"'); + expect(html).toContain('src="/photo.jpg?w=256"'); + } + }); +}); + // ─── SSR rendering ────────────────────────────────────────────────────── describe("Image SSR rendering", () => { From 254502d6740023539aeb48e68c90026532935f37 Mon Sep 17 00:00:00 2001 From: AhmedElBanna80 Date: Thu, 15 Oct 2026 21:08:40 +0200 Subject: [PATCH 14/16] chore: re-run CI (Windows create-next-app job hung) From 7f9bbffb9b2b2de2e9fe94cb628fa9ed5a1ba8f0 Mon Sep 17 00:00:00 2001 From: AhmedElBanna80 Date: Sat, 17 Oct 2026 10:59:38 +0200 Subject: [PATCH 15/16] ci: retrigger (codspeed installer download failed) From ad41a5fe824ea29b004d747fb55dc09c84449f95 Mon Sep 17 00:00:00 2001 From: AhmedElBanna80 Date: Mon, 16 Nov 2026 02:18:16 +0100 Subject: [PATCH 16/16] fix(image): keep images.loaderFile out of next/legacy/image next/legacy/image again evaluated the images.loaderFile module on legacy-only pages: image-props.ts imported the loader-file slot, and legacy-image renders the shared component, which imports image-props. Next.js's client/legacy/image.tsx never imports the aliased image-loader module. - shims/image-loader.ts (new, server-safe) owns the loader-file import, withConfiguredLoader and next/image's getImageProps. - shims/image-base.tsx is the loader-agnostic component, moved from image.tsx. next/legacy/image renders it directly. - shims/image.tsx stays the next/image entry (same alias target): it wraps image-base with withConfiguredLoader. The RSC next/image entry takes getImageProps from image-loader. - image-props keeps buildImageProps (getImageProps without the loader file). Test: importing next/legacy/image does not evaluate the loader-file slot, and importing next/image does. It fails if legacy-image imports image.tsx. --- .../vinext/src/build/client-build-config.ts | 4 + packages/vinext/src/index.ts | 5 +- packages/vinext/src/shims/image-base.tsx | 534 ++++++++++++++++++ .../vinext/src/shims/image-loader-file.ts | 2 +- packages/vinext/src/shims/image-loader.ts | 50 ++ packages/vinext/src/shims/image-props.ts | 42 +- packages/vinext/src/shims/image.tsx | 527 +---------------- packages/vinext/src/shims/legacy-image.tsx | 2 +- packages/vinext/vite.config.ts | 2 +- tests/image-component.test.ts | 20 + 10 files changed, 633 insertions(+), 555 deletions(-) create mode 100644 packages/vinext/src/shims/image-base.tsx create mode 100644 packages/vinext/src/shims/image-loader.ts diff --git a/packages/vinext/src/build/client-build-config.ts b/packages/vinext/src/build/client-build-config.ts index 0b5f65e209..0a84ed1119 100644 --- a/packages/vinext/src/build/client-build-config.ts +++ b/packages/vinext/src/build/client-build-config.ts @@ -18,9 +18,11 @@ const ROUTE_OWNED_CLIENT_SHIMS = new Set([ "dynamic-preload-chunks", "form", "image", + "image-base", // Only image-props imports it. A group also takes in its modules' // dependencies, so in "vinext" it would load ipaddr.js on every page. "image-config", + "image-loader", "image-props", "internal/hybrid-client-route-owner", "layout-segment-context", @@ -43,7 +45,9 @@ const PAGE_OWNED_CLIENT_SHIMS = new Set([ "dynamic-preload-chunks", "form", "image", + "image-base", "image-config", + "image-loader", "image-props", "legacy-image", "offline", diff --git a/packages/vinext/src/index.ts b/packages/vinext/src/index.ts index dc2dbcbf37..235dbd5e93 100644 --- a/packages/vinext/src/index.ts +++ b/packages/vinext/src/index.ts @@ -3737,7 +3737,7 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { ...nextConfig.aliases, ...nextShimMap, "vinext/server/pages-client-assets": _pagesClientAssetsPath, - // shims/image-props.ts imports this slot for `images.loaderFile`. + // shims/image-loader.ts imports this slot for `images.loaderFile`. // Like Next.js (which aliases next/dist/shared/lib/image-loader // to the file), point it at the user's file, resolved against // the project root; otherwise keep vinext's `undefined` default. @@ -5566,7 +5566,8 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { // gives plugin-rsc a package client reference, like vinext's other // client shims. return [ - `export { getImageProps, imageOptimizationUrl } from "vinext/shims/image-props";`, + `export { getImageProps } from "vinext/shims/image-loader";`, + `export { imageOptimizationUrl } from "vinext/shims/image-props";`, `export { default } from "vinext/shims/image";`, "", ].join("\n"); diff --git a/packages/vinext/src/shims/image-base.tsx b/packages/vinext/src/shims/image-base.tsx new file mode 100644 index 0000000000..a70455cce0 --- /dev/null +++ b/packages/vinext/src/shims/image-base.tsx @@ -0,0 +1,534 @@ +"use client"; + +/** + * next/image shim + * + * Translates Next.js Image props to @unpic/react Image component. + * @unpic/react auto-detects CDN from URL and uses native transforms. + * For local images (relative paths), routes through `/_next/image` + * for server-side optimization (resize, format negotiation, quality). + * + * Remote images are validated against `images.remotePatterns` and + * `images.domains` from next.config.js. Unmatched URLs are blocked + * in production and warn in development, matching Next.js behavior. + * + * This is the loader-agnostic component shared by next/image (shims/image.tsx, + * which adds `images.loaderFile`) and next/legacy/image. It never imports the + * loader file, so legacy-only pages never evaluate it, as in Next.js. + * + * Prop building lives in the server-safe `image-props.ts`. + */ +import React, { forwardRef, useEffect, useLayoutEffect, useRef, useState } from "react"; +import * as ReactDOM from "react-dom"; +import { Image as UnpicImage } from "@unpic/react"; +import type { + ImageLoader, + ImageProps as UpstreamImageProps, + StaticImageData, + StaticRequire, +} from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; +import { + __customImageLoader, + __dangerouslyAllowSVG, + __globallyUnoptimized, + __isDev, + RESPONSIVE_WIDTHS, + generateImageAttributes, + generateLoaderAttributes, + getFillStyle, + imageOptimizationUrl, + isInlineSrc, + isRemoteUrl, + isSvgUrl, + parseImageQuality, + resolveImageSource, + sanitizeBlurDataURL, + missingLoaderError, + type LegacyLayoutProp, + validateRemoteUrl, +} from "./image-props.js"; +import { useMergedRef } from "./use-merged-ref.js"; + +export type { ImageLoader, StaticImageData, StaticRequire }; +export type ImageLoaderProps = Parameters[0]; +export type ImageProps = UpstreamImageProps; + +/** + * A version of useLayoutEffect that doesn't warn during SSR. + * Do not rename this to "isomorphic layout effect". There is no such thing as + * an isomorphic Layout Effect since there is no Layout on the server. + * Ported from Next.js: https://github.com/vercel/next.js/pull/93209 + */ +const useNonWarningLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect; + +/** + * Create a synthetic React load event for replaying onLoad/onLoadingComplete + * during hydration when the image already completed loading. + * + * This function creates a native Event("load") via the DOM Event constructor + * and must only be called in a browser context (client-side layout effect). + * It mirrors the pattern used in Next.js `handleLoading`. + */ +function createSyntheticLoadEvent(img: HTMLImageElement): React.SyntheticEvent { + const nativeEvent = new Event("load"); + Object.defineProperty(nativeEvent, "target", { writable: false, value: img }); + let prevented = false; + let stopped = false; + return { + bubbles: nativeEvent.bubbles, + cancelable: nativeEvent.cancelable, + currentTarget: img, + defaultPrevented: false, + eventPhase: nativeEvent.eventPhase, + isTrusted: false, + nativeEvent, + target: img, + timeStamp: nativeEvent.timeStamp, + type: "load", + isDefaultPrevented: () => prevented, + isPropagationStopped: () => stopped, + persist: () => {}, + preventDefault: () => { + prevented = true; + nativeEvent.preventDefault(); + }, + stopPropagation: () => { + stopped = true; + nativeEvent.stopPropagation(); + }, + }; +} + +function preloadImageResource(input: { + shouldPreload: boolean; + src: string; + srcSet?: string; + sizes?: string; + fetchPriority?: ReactDOM.PreloadOptions["fetchPriority"]; +}): void { + if (!input.shouldPreload) return; + if (typeof ReactDOM.preload !== "function") return; + ReactDOM.preload(input.src, { + as: "image", + imageSrcSet: input.srcSet, + imageSizes: input.sizes, + fetchPriority: input.fetchPriority, + }); +} + +const ImageImpl = forwardRef(function Image( + { + src: srcProp, + alt, + width, + height, + fill, + preload, + priority, + quality, + placeholder, + blurDataURL, + loader, + sizes, + className, + style, + onLoad, + onLoadingComplete, + onError, + unoptimized: _unoptimized, + overrideSrc, + loading, + ...rest + }, + ref, +) { + // Next.js drops a caller-provided srcSet (`delete rest.srcSet` in getImgProps) + // so it can't override the generated candidates. + delete (rest as { srcSet?: unknown }).srcSet; + const legacyLayout = (rest as LegacyLayoutProp).__vinextLegacyLayout; + delete (rest as LegacyLayoutProp).__vinextLegacyLayout; + // Dedup refs: ensure onLoad and onError fire at most once per src per mount. + // Matches Next.js behavior — prevents double-firing from React re-renders, + // strict-mode double-invocation, or state updates inside the handler itself. + // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 + const lastLoadedSrcRef = useRef(undefined); + const lastErrorSrcRef = useRef(undefined); + + // Hydration-level onError replay: when an image fails to load during SSR + // streaming or initial HTML parse (before React hydrates), the native browser + // error event is lost. Re-trigger it via `img.src = img.src` in a layout + // effect once hydration completes, mirroring the upstream Next.js fix. + // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 + const didInsertRef = useRef(false); + const imgElementRef = useRef(null); + + // Merge forwarded ref with internal img ref for layout effect access. + const mergedRef = useMergedRef(ref, imgElementRef); + + // Stable refs for onLoad / onError / onLoadingComplete so the layout effect + // does not re-run (and re-assign img.src) when handler identity changes. + // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 + // + // IMPORTANT: The useRef+useEffect sync pattern has a subtle timing gap: + // during the first render, onLoadRef.current holds the initial value from + // useRef(onLoad), and the useEffect to sync it runs AFTER the layout effect. + // This means on first mount the layout effect reads the correct initial + // value (passed to useRef). If someone changes useRef(onLoad) to + // useRef(undefined), the layout effect would read undefined on first mount. + const onLoadRef = useRef(onLoad); + useEffect(() => { + onLoadRef.current = onLoad; + }, [onLoad]); + const onErrorRef = useRef(onError); + useEffect(() => { + onErrorRef.current = onError; + }, [onError]); + const onLoadingCompleteRef = useRef(onLoadingComplete); + useEffect(() => { + onLoadingCompleteRef.current = onLoadingComplete; + }, [onLoadingComplete]); + + const { + src, + width: imgWidth, + height: imgHeight, + blurDataURL: imgBlurDataURL, + } = resolveImageSource({ src: srcProp, width, height, blurDataURL }); + // next/legacy/image's built-in "custom" loader only throws when it has to + // build a URL. next/image rejects a missing loader earlier, regardless of + // `unoptimized` (shims/image-loader.ts). + const unoptimizedProp = _unoptimized === true || __globallyUnoptimized; + if (!loader && __customImageLoader && !unoptimizedProp && !isInlineSrc(src)) { + throw missingLoaderError(src); + } + const shouldPreload = preload === true || priority === true; + const priorityFetchPriority = priority ? "high" : undefined; + const imageLoading = priority ? "eager" : shouldPreload ? loading : (loading ?? "lazy"); + + const [completedBlurSrc, setCompletedBlurSrc] = useState(undefined); + const blurComplete = completedBlurSrc === src; + + const markBlurComplete = () => { + if (placeholder !== "blur") return; + setCompletedBlurSrc((current) => (current === src ? current : src)); + }; + + useNonWarningLayoutEffect(() => { + if (!didInsertRef.current && imgElementRef.current !== null) { + const img = imgElementRef.current; + // Replay error events lost during SSR/hydration. + if (onErrorRef.current) { + // eslint-disable-next-line no-self-assign + img.src = img.src; + } + // Replay onLoad for images that completed loading before React hydrated + // (e.g. SSR streaming where the image arrives and renders before hydration + // finishes). Without this, onLoad never fires for those images. + // + // img.complete is true for both successfully-loaded and errored images + // (the HTML spec defines complete as true when the browser finished + // fetching, regardless of outcome). We must check naturalWidth > 0 to + // distinguish success from error — a failed image has naturalWidth === 0. + // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 + if (img.complete && img.naturalWidth > 0) { + markBlurComplete(); + const currentOnLoad = onLoadRef.current; + const currentOnLoadingComplete = onLoadingCompleteRef.current; + if (currentOnLoad || currentOnLoadingComplete) { + // Dedup — fire at most once per src per mount, matching onLoad dedup + if (lastLoadedSrcRef.current !== src) { + lastLoadedSrcRef.current = src; + // Create a synthetic React event with the expected shape. + // next/image uses a similar pattern in `handleLoading`. + const syntheticEvent = createSyntheticLoadEvent(img); + currentOnLoad?.(syntheticEvent); + currentOnLoadingComplete?.(img); + } + } + } + didInsertRef.current = true; + } + }, [placeholder, sizes, _unoptimized]); + + // Wire onLoadingComplete (deprecated) into onLoad — matches Next.js behavior. + // onLoad fires first, then onLoadingComplete receives the HTMLImageElement. + const handleLoad = onLoadingComplete + ? (e: React.SyntheticEvent) => { + if (lastLoadedSrcRef.current === src) return; + lastLoadedSrcRef.current = src; + markBlurComplete(); + onLoad?.(e); + onLoadingComplete(e.currentTarget); + } + : onLoad + ? (e: React.SyntheticEvent) => { + if (lastLoadedSrcRef.current === src) return; + lastLoadedSrcRef.current = src; + markBlurComplete(); + onLoad(e); + } + : placeholder === "blur" + ? () => { + if (lastLoadedSrcRef.current === src) return; + lastLoadedSrcRef.current = src; + markBlurComplete(); + } + : undefined; + + const handleError = onError + ? (e: React.SyntheticEvent) => { + if (lastErrorSrcRef.current === src) return; + lastErrorSrcRef.current = src; + markBlurComplete(); + onError(e); + } + : placeholder === "blur" + ? () => { + if (lastErrorSrcRef.current === src) return; + lastErrorSrcRef.current = src; + markBlurComplete(); + } + : undefined; + + // Next.js (getImgProps and next/legacy/image) treats empty, data: and blob: + // sources as unoptimized, so neither a custom loader nor /_next/image sees them. + const unoptimized = unoptimizedProp || isInlineSrc(src); + if (unoptimized || loader) { + // Unoptimized images are fetched directly by the browser, so intentionally + // skip remote URL validation: there is no server-side optimizer fetch and + // therefore no SSRF surface. This matches Next.js behavior. A custom + // loader (the `loader` prop, or `images.loaderFile` when no prop is given) + // owns the URL the same way, and gets the built-in loader's per-width + // srcSet. `quality` is passed through as given (possibly undefined); only + // the built-in loader defaults it to 75. + const loaderAttributes = + loader && !unoptimized + ? generateLoaderAttributes( + loader, + src, + fill ? undefined : imgWidth, + typeof quality === "string" ? Number(quality) : quality, + sizes, + legacyLayout, + ) + : undefined; + const resolvedSrc = overrideSrc || (loaderAttributes ? loaderAttributes.src : src); + const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; + const blurStyle = + !blurComplete && placeholder === "blur" && sanitizedBlur + ? { + backgroundImage: `url(${sanitizedBlur})`, + backgroundSize: "cover", + backgroundRepeat: "no-repeat", + backgroundPosition: "center", + } + : undefined; + preloadImageResource({ + shouldPreload, + src: resolvedSrc, + srcSet: loaderAttributes?.srcSet, + sizes: loaderAttributes?.sizes, + fetchPriority: priorityFetchPriority, + }); + return ( + {alt} + ); + } + + // For remote URLs, validate against remotePatterns. Non-fill images use + // @unpic/react for CDN URL transforms; fill uses a plain img so the DOM + // element keeps Next.js's absolute-positioned fill contract. + if (isRemoteUrl(src)) { + const validation = validateRemoteUrl(src); + if (!validation.allowed) { + if (__isDev) { + console.warn(`[next/image] ${validation.reason}`); + // In dev, render the image but with a warning — matches Next.js dev behavior + } else { + // In production, block the image entirely + console.error(`[next/image] ${validation.reason}`); + return null; + } + } + + const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; + const showBlur = !blurComplete && placeholder === "blur" && sanitizedBlur; + const blurStyle = showBlur + ? { + backgroundImage: `url(${sanitizedBlur})`, + backgroundSize: "cover", + backgroundRepeat: "no-repeat", + backgroundPosition: "center", + } + : undefined; + const bg = showBlur ? `url(${sanitizedBlur})` : undefined; + + if (fill) { + const imageSizes = sizes ?? "100vw"; + preloadImageResource({ + shouldPreload, + src, + sizes: imageSizes, + fetchPriority: priorityFetchPriority, + }); + return ( + {alt} + ); + } + // constrained layout requires width+height or aspectRatio + if (imgWidth && imgHeight) { + // @unpic/react forwards additional image props through transformProps and + // merges `style` with generated layout styles at runtime, but its public + // React type omits `style`. + const unpicRuntimeStyleProps: { style?: React.CSSProperties } = { style }; + preloadImageResource({ + shouldPreload, + src, + sizes, + fetchPriority: priorityFetchPriority, + }); + return ( + + ); + } + // Fall through to basic if dimensions not provided + // (unpic requires them for constrained layout) + } + + // Route local images through the /_next/image optimization endpoint. + // In production on Cloudflare Workers, this resizes and transcodes via + // the Images binding. In dev, it serves the original file as a passthrough. + // When `unoptimized` is true, bypass the endpoint entirely (Next.js compat). + // SVG sources auto-skip unless dangerouslyAllowSVG is enabled, matching + // Next.js behavior where .svg triggers unoptimized=true by default. + const imgQuality = parseImageQuality(quality) ?? 75; + const isSvg = isSvgUrl(src); + const skipOptimization = isSvg && !__dangerouslyAllowSVG; + + // Build srcSet for responsive local images (common breakpoints). + // Each entry points to /_next/image with the appropriate width. + const optimizedAttributes = + imgWidth && !fill && !skipOptimization + ? generateImageAttributes(imageOptimizationUrl, src, imgWidth, imgQuality, sizes) + : undefined; + const srcSet = optimizedAttributes + ? optimizedAttributes.srcSet + : imgWidth && !fill + ? RESPONSIVE_WIDTHS.filter((w) => w <= imgWidth * 2) + .map((w) => `${src} ${w}w`) + .join(", ") || `${src} ${imgWidth}w` + : undefined; + + // The main `src` also goes through the optimization endpoint. Use the + // declared width (or the first responsive width as fallback). + const optimizedSrc = skipOptimization + ? src + : optimizedAttributes + ? optimizedAttributes.src + : imageOptimizationUrl(src, RESPONSIVE_WIDTHS[0], imgQuality); + + // Blur placeholder: show a low-quality background while the image loads. + // Sanitize blurDataURL to prevent CSS injection via crafted data URLs. + const sanitizedLocalBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; + const blurStyle = + !blurComplete && placeholder === "blur" && sanitizedLocalBlur + ? { + backgroundImage: `url(${sanitizedLocalBlur})`, + backgroundSize: "cover", + backgroundRepeat: "no-repeat", + backgroundPosition: "center", + } + : undefined; + + const imageSizes = sizes ?? (fill ? "100vw" : undefined); + preloadImageResource({ + shouldPreload, + src: optimizedSrc, + srcSet, + sizes: imageSizes, + fetchPriority: priorityFetchPriority, + }); + + // For local images, render a standard tag with srcSet and blur support. + // The src and srcSet point to the /_next/image optimization endpoint. + return ( + {alt} + ); +}); + +// Annotated so declaration emit references ImageProps by name and keeps its +// @deprecated tags (https://github.com/vercel/next.js/pull/98597). +const Image: React.ForwardRefExoticComponent> = + ImageImpl; + +export default Image; diff --git a/packages/vinext/src/shims/image-loader-file.ts b/packages/vinext/src/shims/image-loader-file.ts index 13ec0e9c35..f5dab5cff5 100644 --- a/packages/vinext/src/shims/image-loader-file.ts +++ b/packages/vinext/src/shims/image-loader-file.ts @@ -1,5 +1,5 @@ /** - * The `images.loaderFile` slot imported by shims/image-external.tsx (next/image). + * The `images.loaderFile` slot imported by shims/image-loader.ts (next/image only). * * This module exports `undefined` (no configured loader file, so the built-in * /_next/image loader applies). When next.config.js sets `images.loaderFile`, diff --git a/packages/vinext/src/shims/image-loader.ts b/packages/vinext/src/shims/image-loader.ts new file mode 100644 index 0000000000..99881a6a2a --- /dev/null +++ b/packages/vinext/src/shims/image-loader.ts @@ -0,0 +1,50 @@ +/** + * `images.loaderFile` for next/image, kept out of the shared image modules. + * + * Server-safe. next/image (shims/image.tsx) and the RSC next/image entry import + * it; next/legacy/image never does, so a legacy-only page never evaluates the + * loader file, as in Next.js, where client/legacy/image.tsx never imports the + * aliased `next/dist/shared/lib/image-loader` module. + */ +import type { + ImageLoader, + ImageProps, + ImgProps, +} from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; +// The vinext plugin aliases this specifier to the user's `images.loaderFile`. +// A namespace import, so a file without a default export reaches the +// diagnostic in withConfiguredLoader instead of failing module linking. +import * as imageLoaderFileModule from "vinext/shims/image-loader-file"; +import { __customImageLoader, buildImageProps, missingLoaderError } from "./image-props.js"; + +const configuredImageLoader: ImageLoader | undefined = imageLoaderFileModule.default; +/** `images.loaderFile` is set, so `configuredImageLoader` must be its default export. */ +const __hasImageLoaderFile = process.env.__VINEXT_IMAGE_LOADER_FILE === "true"; + +/** + * Fall back to the configured loader file when no `loader` prop is given. + * Ported from the loader checks at the top of Next.js's getImgProps. + */ +export function withConfiguredLoader(props: ImageProps): ImageProps { + if (__hasImageLoaderFile && typeof configuredImageLoader === "undefined") { + throw new Error( + "images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config", + ); + } + const loader = props.loader || configuredImageLoader; + if (!loader && __customImageLoader) { + const { src } = props; + throw missingLoaderError( + typeof src === "string" ? src : ("default" in src ? src.default : src).src, + ); + } + return loader === props.loader ? props : { ...props, loader }; +} + +/** + * getImageProps — for advanced use cases (picture elements, background images). + * Returns the props that would be passed to the underlying element. + */ +export function getImageProps(imageProps: ImageProps): { props: ImgProps } { + return buildImageProps(withConfiguredLoader(imageProps)); +} diff --git a/packages/vinext/src/shims/image-props.ts b/packages/vinext/src/shims/image-props.ts index dcd59a6e35..964e1c71fc 100644 --- a/packages/vinext/src/shims/image-props.ts +++ b/packages/vinext/src/shims/image-props.ts @@ -1,8 +1,9 @@ /** * Server-safe next/image helpers. * - * Holds the image config, URL builders, and `getImageProps`. This module has - * no "use client" directive so `getImageProps` can run in Server Components, + * Holds the image config, URL builders, and `buildImageProps` (getImageProps + * without `images.loaderFile`; next/image adds it in shims/image-loader.ts). + * This module has no "use client" directive so getImageProps can run in Server Components, * matching Next.js where `next/image` (shared/lib/image-external.tsx) is * server-safe and only the Image component is a client reference. * @@ -17,10 +18,6 @@ import type { ImgProps, StaticImport, } from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; -// The vinext plugin aliases this specifier to the user's `images.loaderFile`. -// A namespace import, so a file without a default export reaches the -// diagnostic in withConfiguredLoader instead of failing module linking. -import * as imageLoaderFileModule from "vinext/shims/image-loader-file"; import { getDeploymentId } from "../utils/deployment-id.js"; import { hasRemoteMatch, isPrivateIp, type RemotePattern } from "./image-config.js"; @@ -400,7 +397,7 @@ export function generateLoaderAttributes( */ export type LegacyLayoutProp = { __vinextLegacyLayout?: string }; -/** Internal: also thrown by shims/image-external.tsx for next/image. */ +/** Internal: also thrown by shims/image-loader.ts for next/image. */ export function missingLoaderError(src: string): Error { return new Error( `Image with src "${src}" is missing "loader" prop.` + @@ -408,42 +405,17 @@ export function missingLoaderError(src: string): Error { ); } -const configuredImageLoader: ImageLoader | undefined = imageLoaderFileModule.default; -/** `images.loaderFile` is set, so `configuredImageLoader` must be its default export. */ -const __hasImageLoaderFile = process.env.__VINEXT_IMAGE_LOADER_FILE === "true"; - -/** - * next/image only (next/legacy/image never evaluates `images.loaderFile`): - * fall back to the configured loader file when no `loader` prop is given. - * Ported from the loader checks at the top of Next.js's getImgProps. - */ -export function withConfiguredLoader(props: ImageProps): ImageProps { - if (__hasImageLoaderFile && typeof configuredImageLoader === "undefined") { - throw new Error( - "images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config", - ); - } - const loader = props.loader || configuredImageLoader; - if (!loader && __customImageLoader) { - const { src } = props; - throw missingLoaderError( - typeof src === "string" ? src : ("default" in src ? src.default : src).src, - ); - } - return loader === props.loader ? props : { ...props, loader }; -} - /** Sources Next.js always treats as unoptimized (empty, data: and blob:). */ export function isInlineSrc(src: string): boolean { return !src || src.startsWith("data:") || src.startsWith("blob:"); } /** - * getImageProps — for advanced use cases (picture elements, background images). + * getImageProps without `images.loaderFile`. next/image's getImageProps + * (shims/image-loader.ts) applies the loader file and then calls this. * Returns the props that would be passed to the underlying element. */ -export function getImageProps(imagePropsInput: ImageProps): { props: ImgProps } { - const props = withConfiguredLoader(imagePropsInput); +export function buildImageProps(props: ImageProps): { props: ImgProps } { const { src: srcProp, alt, diff --git a/packages/vinext/src/shims/image.tsx b/packages/vinext/src/shims/image.tsx index c8cc19e85e..aee24baf9c 100644 --- a/packages/vinext/src/shims/image.tsx +++ b/packages/vinext/src/shims/image.tsx @@ -3,539 +3,36 @@ /** * next/image shim * - * Translates Next.js Image props to @unpic/react Image component. - * @unpic/react auto-detects CDN from URL and uses native transforms. - * For local images (relative paths), routes through `/_next/image` - * for server-side optimization (resize, format negotiation, quality). + * The shared component (shims/image-base.tsx) plus `images.loaderFile` + * (shims/image-loader.ts). next/legacy/image renders image-base.tsx directly, + * so only next/image evaluates the loader file, as in Next.js. * - * Remote images are validated against `images.remotePatterns` and - * `images.domains` from next.config.js. Unmatched URLs are blocked - * in production and warn in development, matching Next.js behavior. - * - * Prop building lives in the server-safe `image-props.ts`. In the RSC - * environment, next/image resolves to a server entry that exports - * `getImageProps` from there and this module's Image as a client reference. + * In the RSC environment, next/image resolves to a server entry that exports + * `getImageProps` from image-loader.ts and this module's Image as a client + * reference. */ -import React, { forwardRef, useEffect, useLayoutEffect, useRef, useState } from "react"; -import * as ReactDOM from "react-dom"; -import { Image as UnpicImage } from "@unpic/react"; +import React, { forwardRef } from "react"; import type { ImageLoader, ImageProps as UpstreamImageProps, StaticImageData, StaticRequire, } from "@vinext/types/next/upstream/dist/shared/lib/get-img-props"; -import { - __customImageLoader, - __dangerouslyAllowSVG, - __globallyUnoptimized, - __isDev, - RESPONSIVE_WIDTHS, - generateImageAttributes, - generateLoaderAttributes, - getFillStyle, - imageOptimizationUrl, - isInlineSrc, - isRemoteUrl, - isSvgUrl, - parseImageQuality, - resolveImageSource, - sanitizeBlurDataURL, - missingLoaderError, - type LegacyLayoutProp, - withConfiguredLoader, - validateRemoteUrl, -} from "./image-props.js"; -import { useMergedRef } from "./use-merged-ref.js"; +import ImageBase from "./image-base.js"; +import { withConfiguredLoader } from "./image-loader.js"; export type { ImageLoader, StaticImageData, StaticRequire }; export type ImageLoaderProps = Parameters[0]; export type ImageProps = UpstreamImageProps; -export { getImageProps, imageOptimizationUrl } from "./image-props.js"; - -/** - * A version of useLayoutEffect that doesn't warn during SSR. - * Do not rename this to "isomorphic layout effect". There is no such thing as - * an isomorphic Layout Effect since there is no Layout on the server. - * Ported from Next.js: https://github.com/vercel/next.js/pull/93209 - */ -const useNonWarningLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect; - -/** - * Create a synthetic React load event for replaying onLoad/onLoadingComplete - * during hydration when the image already completed loading. - * - * This function creates a native Event("load") via the DOM Event constructor - * and must only be called in a browser context (client-side layout effect). - * It mirrors the pattern used in Next.js `handleLoading`. - */ -function createSyntheticLoadEvent(img: HTMLImageElement): React.SyntheticEvent { - const nativeEvent = new Event("load"); - Object.defineProperty(nativeEvent, "target", { writable: false, value: img }); - let prevented = false; - let stopped = false; - return { - bubbles: nativeEvent.bubbles, - cancelable: nativeEvent.cancelable, - currentTarget: img, - defaultPrevented: false, - eventPhase: nativeEvent.eventPhase, - isTrusted: false, - nativeEvent, - target: img, - timeStamp: nativeEvent.timeStamp, - type: "load", - isDefaultPrevented: () => prevented, - isPropagationStopped: () => stopped, - persist: () => {}, - preventDefault: () => { - prevented = true; - nativeEvent.preventDefault(); - }, - stopPropagation: () => { - stopped = true; - nativeEvent.stopPropagation(); - }, - }; -} - -function preloadImageResource(input: { - shouldPreload: boolean; - src: string; - srcSet?: string; - sizes?: string; - fetchPriority?: ReactDOM.PreloadOptions["fetchPriority"]; -}): void { - if (!input.shouldPreload) return; - if (typeof ReactDOM.preload !== "function") return; - ReactDOM.preload(input.src, { - as: "image", - imageSrcSet: input.srcSet, - imageSizes: input.sizes, - fetchPriority: input.fetchPriority, - }); -} - -const ImageImpl = forwardRef(function Image( - { - src: srcProp, - alt, - width, - height, - fill, - preload, - priority, - quality, - placeholder, - blurDataURL, - loader, - sizes, - className, - style, - onLoad, - onLoadingComplete, - onError, - unoptimized: _unoptimized, - overrideSrc, - loading, - ...rest - }, - ref, -) { - // Next.js drops a caller-provided srcSet (`delete rest.srcSet` in getImgProps) - // so it can't override the generated candidates. - delete (rest as { srcSet?: unknown }).srcSet; - const legacyLayout = (rest as LegacyLayoutProp).__vinextLegacyLayout; - delete (rest as LegacyLayoutProp).__vinextLegacyLayout; - // Dedup refs: ensure onLoad and onError fire at most once per src per mount. - // Matches Next.js behavior — prevents double-firing from React re-renders, - // strict-mode double-invocation, or state updates inside the handler itself. - // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 - const lastLoadedSrcRef = useRef(undefined); - const lastErrorSrcRef = useRef(undefined); - - // Hydration-level onError replay: when an image fails to load during SSR - // streaming or initial HTML parse (before React hydrates), the native browser - // error event is lost. Re-trigger it via `img.src = img.src` in a layout - // effect once hydration completes, mirroring the upstream Next.js fix. - // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 - const didInsertRef = useRef(false); - const imgElementRef = useRef(null); - - // Merge forwarded ref with internal img ref for layout effect access. - const mergedRef = useMergedRef(ref, imgElementRef); - - // Stable refs for onLoad / onError / onLoadingComplete so the layout effect - // does not re-run (and re-assign img.src) when handler identity changes. - // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 - // - // IMPORTANT: The useRef+useEffect sync pattern has a subtle timing gap: - // during the first render, onLoadRef.current holds the initial value from - // useRef(onLoad), and the useEffect to sync it runs AFTER the layout effect. - // This means on first mount the layout effect reads the correct initial - // value (passed to useRef). If someone changes useRef(onLoad) to - // useRef(undefined), the layout effect would read undefined on first mount. - const onLoadRef = useRef(onLoad); - useEffect(() => { - onLoadRef.current = onLoad; - }, [onLoad]); - const onErrorRef = useRef(onError); - useEffect(() => { - onErrorRef.current = onError; - }, [onError]); - const onLoadingCompleteRef = useRef(onLoadingComplete); - useEffect(() => { - onLoadingCompleteRef.current = onLoadingComplete; - }, [onLoadingComplete]); - - const { - src, - width: imgWidth, - height: imgHeight, - blurDataURL: imgBlurDataURL, - } = resolveImageSource({ src: srcProp, width, height, blurDataURL }); - // next/legacy/image's built-in "custom" loader only throws when it has to - // build a URL. next/image rejects a missing loader earlier, regardless of - // `unoptimized` (shims/image-external.tsx). - const unoptimizedProp = _unoptimized === true || __globallyUnoptimized; - if (!loader && __customImageLoader && !unoptimizedProp && !isInlineSrc(src)) { - throw missingLoaderError(src); - } - const shouldPreload = preload === true || priority === true; - const priorityFetchPriority = priority ? "high" : undefined; - const imageLoading = priority ? "eager" : shouldPreload ? loading : (loading ?? "lazy"); - - const [completedBlurSrc, setCompletedBlurSrc] = useState(undefined); - const blurComplete = completedBlurSrc === src; - - const markBlurComplete = () => { - if (placeholder !== "blur") return; - setCompletedBlurSrc((current) => (current === src ? current : src)); - }; - - useNonWarningLayoutEffect(() => { - if (!didInsertRef.current && imgElementRef.current !== null) { - const img = imgElementRef.current; - // Replay error events lost during SSR/hydration. - if (onErrorRef.current) { - // eslint-disable-next-line no-self-assign - img.src = img.src; - } - // Replay onLoad for images that completed loading before React hydrated - // (e.g. SSR streaming where the image arrives and renders before hydration - // finishes). Without this, onLoad never fires for those images. - // - // img.complete is true for both successfully-loaded and errored images - // (the HTML spec defines complete as true when the browser finished - // fetching, regardless of outcome). We must check naturalWidth > 0 to - // distinguish success from error — a failed image has naturalWidth === 0. - // Ported from Next.js: https://github.com/vercel/next.js/pull/93209 - if (img.complete && img.naturalWidth > 0) { - markBlurComplete(); - const currentOnLoad = onLoadRef.current; - const currentOnLoadingComplete = onLoadingCompleteRef.current; - if (currentOnLoad || currentOnLoadingComplete) { - // Dedup — fire at most once per src per mount, matching onLoad dedup - if (lastLoadedSrcRef.current !== src) { - lastLoadedSrcRef.current = src; - // Create a synthetic React event with the expected shape. - // next/image uses a similar pattern in `handleLoading`. - const syntheticEvent = createSyntheticLoadEvent(img); - currentOnLoad?.(syntheticEvent); - currentOnLoadingComplete?.(img); - } - } - } - didInsertRef.current = true; - } - }, [placeholder, sizes, _unoptimized]); - - // Wire onLoadingComplete (deprecated) into onLoad — matches Next.js behavior. - // onLoad fires first, then onLoadingComplete receives the HTMLImageElement. - const handleLoad = onLoadingComplete - ? (e: React.SyntheticEvent) => { - if (lastLoadedSrcRef.current === src) return; - lastLoadedSrcRef.current = src; - markBlurComplete(); - onLoad?.(e); - onLoadingComplete(e.currentTarget); - } - : onLoad - ? (e: React.SyntheticEvent) => { - if (lastLoadedSrcRef.current === src) return; - lastLoadedSrcRef.current = src; - markBlurComplete(); - onLoad(e); - } - : placeholder === "blur" - ? () => { - if (lastLoadedSrcRef.current === src) return; - lastLoadedSrcRef.current = src; - markBlurComplete(); - } - : undefined; - - const handleError = onError - ? (e: React.SyntheticEvent) => { - if (lastErrorSrcRef.current === src) return; - lastErrorSrcRef.current = src; - markBlurComplete(); - onError(e); - } - : placeholder === "blur" - ? () => { - if (lastErrorSrcRef.current === src) return; - lastErrorSrcRef.current = src; - markBlurComplete(); - } - : undefined; - - // Next.js (getImgProps and next/legacy/image) treats empty, data: and blob: - // sources as unoptimized, so neither a custom loader nor /_next/image sees them. - const unoptimized = unoptimizedProp || isInlineSrc(src); - if (unoptimized || loader) { - // Unoptimized images are fetched directly by the browser, so intentionally - // skip remote URL validation: there is no server-side optimizer fetch and - // therefore no SSRF surface. This matches Next.js behavior. A custom - // loader (the `loader` prop, or `images.loaderFile` when no prop is given) - // owns the URL the same way, and gets the built-in loader's per-width - // srcSet. `quality` is passed through as given (possibly undefined); only - // the built-in loader defaults it to 75. - const loaderAttributes = - loader && !unoptimized - ? generateLoaderAttributes( - loader, - src, - fill ? undefined : imgWidth, - typeof quality === "string" ? Number(quality) : quality, - sizes, - legacyLayout, - ) - : undefined; - const resolvedSrc = overrideSrc || (loaderAttributes ? loaderAttributes.src : src); - const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; - const blurStyle = - !blurComplete && placeholder === "blur" && sanitizedBlur - ? { - backgroundImage: `url(${sanitizedBlur})`, - backgroundSize: "cover", - backgroundRepeat: "no-repeat", - backgroundPosition: "center", - } - : undefined; - preloadImageResource({ - shouldPreload, - src: resolvedSrc, - srcSet: loaderAttributes?.srcSet, - sizes: loaderAttributes?.sizes, - fetchPriority: priorityFetchPriority, - }); - return ( - {alt} - ); - } - - // For remote URLs, validate against remotePatterns. Non-fill images use - // @unpic/react for CDN URL transforms; fill uses a plain img so the DOM - // element keeps Next.js's absolute-positioned fill contract. - if (isRemoteUrl(src)) { - const validation = validateRemoteUrl(src); - if (!validation.allowed) { - if (__isDev) { - console.warn(`[next/image] ${validation.reason}`); - // In dev, render the image but with a warning — matches Next.js dev behavior - } else { - // In production, block the image entirely - console.error(`[next/image] ${validation.reason}`); - return null; - } - } - - const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; - const showBlur = !blurComplete && placeholder === "blur" && sanitizedBlur; - const blurStyle = showBlur - ? { - backgroundImage: `url(${sanitizedBlur})`, - backgroundSize: "cover", - backgroundRepeat: "no-repeat", - backgroundPosition: "center", - } - : undefined; - const bg = showBlur ? `url(${sanitizedBlur})` : undefined; - - if (fill) { - const imageSizes = sizes ?? "100vw"; - preloadImageResource({ - shouldPreload, - src, - sizes: imageSizes, - fetchPriority: priorityFetchPriority, - }); - return ( - {alt} - ); - } - // constrained layout requires width+height or aspectRatio - if (imgWidth && imgHeight) { - // @unpic/react forwards additional image props through transformProps and - // merges `style` with generated layout styles at runtime, but its public - // React type omits `style`. - const unpicRuntimeStyleProps: { style?: React.CSSProperties } = { style }; - preloadImageResource({ - shouldPreload, - src, - sizes, - fetchPriority: priorityFetchPriority, - }); - return ( - - ); - } - // Fall through to basic if dimensions not provided - // (unpic requires them for constrained layout) - } - - // Route local images through the /_next/image optimization endpoint. - // In production on Cloudflare Workers, this resizes and transcodes via - // the Images binding. In dev, it serves the original file as a passthrough. - // When `unoptimized` is true, bypass the endpoint entirely (Next.js compat). - // SVG sources auto-skip unless dangerouslyAllowSVG is enabled, matching - // Next.js behavior where .svg triggers unoptimized=true by default. - const imgQuality = parseImageQuality(quality) ?? 75; - const isSvg = isSvgUrl(src); - const skipOptimization = isSvg && !__dangerouslyAllowSVG; - - // Build srcSet for responsive local images (common breakpoints). - // Each entry points to /_next/image with the appropriate width. - const optimizedAttributes = - imgWidth && !fill && !skipOptimization - ? generateImageAttributes(imageOptimizationUrl, src, imgWidth, imgQuality, sizes) - : undefined; - const srcSet = optimizedAttributes - ? optimizedAttributes.srcSet - : imgWidth && !fill - ? RESPONSIVE_WIDTHS.filter((w) => w <= imgWidth * 2) - .map((w) => `${src} ${w}w`) - .join(", ") || `${src} ${imgWidth}w` - : undefined; - - // The main `src` also goes through the optimization endpoint. Use the - // declared width (or the first responsive width as fallback). - const optimizedSrc = skipOptimization - ? src - : optimizedAttributes - ? optimizedAttributes.src - : imageOptimizationUrl(src, RESPONSIVE_WIDTHS[0], imgQuality); - - // Blur placeholder: show a low-quality background while the image loads. - // Sanitize blurDataURL to prevent CSS injection via crafted data URLs. - const sanitizedLocalBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined; - const blurStyle = - !blurComplete && placeholder === "blur" && sanitizedLocalBlur - ? { - backgroundImage: `url(${sanitizedLocalBlur})`, - backgroundSize: "cover", - backgroundRepeat: "no-repeat", - backgroundPosition: "center", - } - : undefined; - - const imageSizes = sizes ?? (fill ? "100vw" : undefined); - preloadImageResource({ - shouldPreload, - src: optimizedSrc, - srcSet, - sizes: imageSizes, - fetchPriority: priorityFetchPriority, - }); - - // For local images, render a standard tag with srcSet and blur support. - // The src and srcSet point to the /_next/image optimization endpoint. - return ( - {alt} - ); -}); +export { getImageProps } from "./image-loader.js"; +export { imageOptimizationUrl } from "./image-props.js"; // Annotated so declaration emit references ImageProps by name and keeps its // @deprecated tags (https://github.com/vercel/next.js/pull/98597). -// -// next/image applies `images.loaderFile`; next/legacy/image (which sets the -// internal layout prop) does not, as in Next.js. const Image: React.ForwardRefExoticComponent> = forwardRef(function Image(props, ref) { - const isLegacy = (props as LegacyLayoutProp).__vinextLegacyLayout !== undefined; - return ; + return ; }); export default Image; diff --git a/packages/vinext/src/shims/legacy-image.tsx b/packages/vinext/src/shims/legacy-image.tsx index 519a003c8a..4c92a05cc6 100644 --- a/packages/vinext/src/shims/legacy-image.tsx +++ b/packages/vinext/src/shims/legacy-image.tsx @@ -9,7 +9,7 @@ * codemod when upgrading from Next.js 12. */ import React from "react"; -import ModernImage from "./image.js"; +import ModernImage from "./image-base.js"; import type { LegacyLayoutProp } from "./image-props.js"; import type { ImageLoader, diff --git a/packages/vinext/vite.config.ts b/packages/vinext/vite.config.ts index b2f41f6e76..88cd12fd0f 100644 --- a/packages/vinext/vite.config.ts +++ b/packages/vinext/vite.config.ts @@ -68,7 +68,7 @@ const externalizeBareThirdPartySpecifiers = ( isResolved: boolean, ) => { if (isResolved) return false; - // shims/image-props.ts imports the `images.loaderFile` slot by this bare + // shims/image-loader.ts imports the `images.loaderFile` slot by this bare // specifier so the vinext plugin can alias it to the user's loader file. // Keep it bare in `dist` instead of rewriting it to a relative import. if (id === "vinext/shims/image-loader-file") return true; diff --git a/tests/image-component.test.ts b/tests/image-component.test.ts index a96039ff0c..8eee73480a 100644 --- a/tests/image-component.test.ts +++ b/tests/image-component.test.ts @@ -218,6 +218,26 @@ describe("images.loader config validation", () => { } }); + // Next.js's client/legacy/image.tsx never imports the aliased image-loader + // module, so a legacy-only page never evaluates images.loaderFile: its side + // effects and top-level errors cannot reach that page. next/image does. + it("evaluates images.loaderFile for next/image only, never for next/legacy/image", async () => { + const evaluated = vi.fn(); + vi.resetModules(); + vi.doMock("vinext/shims/image-loader-file", () => { + evaluated(); + return { default: undefined }; + }); + try { + await import("../packages/vinext/src/shims/legacy-image.js"); + expect(evaluated).not.toHaveBeenCalled(); + await import("../packages/vinext/src/shims/image.js"); + expect(evaluated).toHaveBeenCalledTimes(1); + } finally { + vi.doUnmock("vinext/shims/image-loader-file"); + } + }); + // Next.js's legacy image marks data: and blob: sources unoptimized before // it builds a URL, so its "custom" loader neither throws nor runs for them. it("renders inline next/legacy/image sources as-is when images.loader is custom", async () => {