JonasKruckenberg / imagetools

Load and transform images using a toolbox :toolbox: of custom import directives!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

generateImageID causes tests to fail on CI

liegeandlief opened this issue · comments

When running tests using vitest the generateImageID is causing problems because it returns a different value when running in different environments.

function generateImageID(url, config) {
    const baseURL = url.host ? new URL(url.origin + url.pathname) : new URL(url.protocol + url.pathname);
    return createHash('sha1').update(baseURL.href).update(JSON.stringify(config)).digest('hex');
}

Local images imported in my files get different IDs when running tests locally to when running them on CI because the pathname used in new URL(url.protocol + url.pathname) is different.

For instance if I am importing the image @lib/images/example.png then url.pathname when running tests locally might be Users/my_username/repositories/my_project/src/lib/images/example.png. But when running on CI it might be /home/runner/work/my_project/src/lib/images/example.png.

The different paths result in different IDs, meaning that tests which check the image src pass when running locally but then fail on CI.

Today I used patch-package to patch imagetools-core@4.0.5 for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/imagetools-core/dist/index.js b/node_modules/imagetools-core/dist/index.js
index 4bace58..e823bab 100644
--- a/node_modules/imagetools-core/dist/index.js
+++ b/node_modules/imagetools-core/dist/index.js
@@ -1,5 +1,6 @@
 import { createHash } from 'node:crypto';
 import sharp from 'sharp';
+import path from 'path'
 
 const METADATA = Symbol('image metadata');
 function setMetadata(image, key, value) {
@@ -464,7 +465,7 @@ function loadImage(path) {
     return sharp(path);
 }
 function generateImageID(url, config) {
-    const baseURL = url.host ? new URL(url.origin + url.pathname) : new URL(url.protocol + url.pathname);
+    const baseURL = url.host ? new URL(url.origin + url.pathname) : new URL(url.protocol + path.relative(process.cwd(), url.pathname));
     return createHash('sha1').update(baseURL.href).update(JSON.stringify(config)).digest('hex');
 }
 

This issue body was partially generated by patch-package.

Feel free to open a PR with this 👍🏻 it seems like its solving a genuine issue in a good way