-
Notifications
You must be signed in to change notification settings - Fork 435
fix: refactor image handling to use @netlify/images
#7584
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
keanu-a
wants to merge
9
commits into
main
Choose a base branch
from
keanualoua/ex-536-use-imagehandler-from-netlifyimages
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+58
β232
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
50c6b3f
refactor: change initializeProxy to use ImageHandler
keanu-a bda921a
refactor: removed unused functions and tests
keanu-a 02e0e3d
format imports in correct place
keanu-a 425313a
specified type import for ImageHandler
keanu-a 8b4ea46
Merge branch 'main' into keanualoua/ex-536-use-imagehandler-from-netlβ¦
keanu-a b86710a
Merge branch 'main' into keanualoua/ex-536-use-imagehandler-from-netlβ¦
khendrikse 5e06052
Merge branch 'main' into keanualoua/ex-536-use-imagehandler-from-netlβ¦
khendrikse bf10b31
Merge branch 'main' into keanualoua/ex-536-use-imagehandler-from-netlβ¦
keanu-a 2cb49f4
fix: remove ipx dependency (now indirect via @netlify/images) (#7802)
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,184 +1,42 @@ | ||
| import type { IncomingMessage } from 'http' | ||
| import type { IncomingMessage, ServerResponse } from 'http' | ||
|
|
||
| import express from 'express' | ||
| import { createIPX, ipxFSStorage, ipxHttpStorage, createIPXNodeServer } from 'ipx' | ||
| import { type ImageHandler } from '@netlify/images' | ||
|
|
||
| import { log, NETLIFYDEVERR, type NormalizedCachedConfigConfig } from '../../utils/command-helpers.js' | ||
| import { getProxyUrl } from '../../utils/proxy.js' | ||
| import type { ServerSettings } from '../../utils/types.d.ts' | ||
| import { fromWebResponse, toWebRequest } from '@netlify/dev-utils' | ||
|
|
||
| export const IMAGE_URL_PATTERN = '/.netlify/images' | ||
|
|
||
| interface QueryParams { | ||
| w?: string | ||
| width?: string | ||
| h?: string | ||
| height?: string | ||
| q?: string | ||
| quality?: string | ||
| fm?: string | ||
| fit?: string | ||
| position?: string | ||
| } | ||
|
|
||
| interface IpxParams { | ||
| w?: string | null | ||
| h?: string | null | ||
| s?: string | null | ||
| quality?: string | null | ||
| format?: string | null | ||
| fit?: string | null | ||
| position?: string | null | ||
| } | ||
|
|
||
| export const parseAllRemoteImages = function (config: Pick<NormalizedCachedConfigConfig, 'images'>): { | ||
| errors: ErrorObject[] | ||
| remotePatterns: RegExp[] | ||
| } { | ||
| const remotePatterns = [] as RegExp[] | ||
| const errors = [] as ErrorObject[] | ||
| const remoteImages = config?.images?.remote_images | ||
|
|
||
| if (!remoteImages) { | ||
| return { errors, remotePatterns } | ||
| } | ||
|
|
||
| for (const patternString of remoteImages) { | ||
| try { | ||
| const urlRegex = new RegExp(patternString) | ||
| remotePatterns.push(urlRegex) | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : 'An unknown error occurred' | ||
|
|
||
| errors.push({ message }) | ||
| } | ||
| } | ||
|
|
||
| return { errors, remotePatterns } | ||
| } | ||
|
|
||
| interface ErrorObject { | ||
| message: string | ||
| } | ||
|
|
||
| const getErrorMessage = function ({ message }: { message: string }): string { | ||
| return message | ||
| } | ||
|
|
||
| const handleRemoteImagesErrors = function (errors: ErrorObject[]) { | ||
| if (errors.length === 0) { | ||
| return | ||
| } | ||
|
|
||
| const errorMessage = errors.map(getErrorMessage).join('\n\n') | ||
| log(NETLIFYDEVERR, `Remote images syntax errors:\n${errorMessage}`) | ||
| } | ||
|
|
||
| const parseRemoteImages = function ({ config }: { config: NormalizedCachedConfigConfig }) { | ||
| if (!config) { | ||
| return [] | ||
| } | ||
|
|
||
| const { errors, remotePatterns } = parseAllRemoteImages(config) | ||
| handleRemoteImagesErrors(errors) | ||
|
|
||
| return remotePatterns | ||
| } | ||
|
|
||
| export const isImageRequest = function (req: IncomingMessage): boolean { | ||
| return req.url?.startsWith(IMAGE_URL_PATTERN) ?? false | ||
| } | ||
|
|
||
| export const transformImageParams = function (query: QueryParams): string { | ||
| const params: IpxParams = {} | ||
|
|
||
| const width = query.w || query.width || null | ||
| const height = query.h || query.height || null | ||
|
|
||
| if (width && height) { | ||
| params.s = `${width}x${height}` | ||
| } else { | ||
| params.w = width | ||
| params.h = height | ||
| } | ||
|
|
||
| params.quality = query.q || query.quality || null | ||
| params.format = query.fm || null | ||
|
|
||
| const fit = query.fit || null | ||
| params.fit = fit === 'contain' ? 'inside' : fit | ||
|
|
||
| params.position = query.position || null | ||
|
|
||
| return Object.entries(params) | ||
| .filter(([, value]) => value !== null) | ||
| .map(([key, value]) => `${key}_${value}`) | ||
| .join(',') | ||
| } | ||
|
|
||
| export const initializeProxy = function ({ | ||
| config, | ||
| settings, | ||
| imageHandler, | ||
| }: { | ||
| config: NormalizedCachedConfigConfig | ||
| settings: ServerSettings | ||
| imageHandler: ImageHandler | ||
| }) { | ||
| const remoteImages = parseRemoteImages({ config }) | ||
| const devServerUrl = getProxyUrl(settings) | ||
|
|
||
| const ipx = createIPX({ | ||
| storage: ipxFSStorage({ dir: ('publish' in config.build ? config.build.publish : undefined) ?? './public' }), | ||
| httpStorage: ipxHttpStorage({ | ||
| allowAllDomains: true, | ||
| }), | ||
| }) | ||
|
|
||
| const handler = createIPXNodeServer(ipx) | ||
| const app = express() | ||
|
|
||
| let lastTimeRemoteImagesConfigurationDetailsMessageWasLogged = 0 | ||
|
|
||
| app.use(IMAGE_URL_PATTERN, (req, res) => { | ||
| const { url, ...query } = req.query | ||
| const sourceImagePath = url as string | ||
| const modifiers = transformImageParams(query) || `_` | ||
| if (!sourceImagePath.startsWith('http://') && !sourceImagePath.startsWith('https://')) { | ||
| // Construct the full URL for relative paths to request from development server | ||
| const sourceImagePathWithLeadingSlash = sourceImagePath.startsWith('/') ? sourceImagePath : `/${sourceImagePath}` | ||
| const fullImageUrl = `${devServerUrl}${encodeURIComponent(sourceImagePathWithLeadingSlash)}` | ||
| req.url = `/${modifiers}/${fullImageUrl}` | ||
| } else { | ||
| // If the image is remote, we first check if it's allowed by any of patterns | ||
| if (!remoteImages.some((remoteImage) => remoteImage.test(sourceImagePath))) { | ||
| const remoteImageNotAllowedLogMessage = `Remote image "${sourceImagePath}" source for Image CDN is not allowed.` | ||
|
|
||
| // Contextual information about the remote image configuration is throttled | ||
| // to avoid spamming the console as it's quite verbose | ||
| // Each not allowed remote image will still be logged, just without configuration details | ||
| if (Date.now() - lastTimeRemoteImagesConfigurationDetailsMessageWasLogged > 1000 * 30) { | ||
| log( | ||
| `${remoteImageNotAllowedLogMessage}\n\n${ | ||
| remoteImages.length === 0 | ||
| ? 'Currently no remote images are allowed.' | ||
| : `Currently allowed remote images configuration details:\n${remoteImages | ||
| .map((pattern) => ` - ${pattern}`) | ||
| .join('\n')}` | ||
| }\n\nRefer to https://ntl.fyi/remote-images for information about how to configure allowed remote images.`, | ||
| ) | ||
| lastTimeRemoteImagesConfigurationDetailsMessageWasLogged = Date.now() | ||
| } else { | ||
| log(remoteImageNotAllowedLogMessage) | ||
| } | ||
|
|
||
| res.status(400).end() | ||
| return async (req: IncomingMessage, res: ServerResponse) => { | ||
| try { | ||
| const webRequest = toWebRequest(req) | ||
| const match = imageHandler.match(webRequest) | ||
| if (!match) { | ||
| res.statusCode = 404 | ||
| res.end('Image not found') | ||
| return | ||
| } | ||
| // Construct the full URL for remote paths | ||
| req.url = `/${modifiers}/${encodeURIComponent(sourceImagePath)}` | ||
| } | ||
|
|
||
| handler(req, res) | ||
| }) | ||
|
|
||
| return app | ||
| const response = await match.handle(devServerUrl) | ||
| await fromWebResponse(response, res) | ||
| } catch (error) { | ||
| console.error('Image proxy error:', error) | ||
| res.statusCode = 500 | ||
| res.end('Internal server error') | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we can remove the ipx dep (it's used indirectly in
@netlify/imagesnow)