@websolutespa/bom-mixer-image 1.8.4 → 2.0.1-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/index.d.ts +16 -8
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +221 -304
- package/dist/index.js.map +1 -0
- package/package.json +43 -22
- package/src/__tests/example.test.ts +1 -1
- package/src/image/image.handler.ts +8 -2
- package/dist/index.mjs +0 -294
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @websolutespa/bom-mixer-image
|
|
2
2
|
|
|
3
|
+
## 2.0.1-next.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updating: dependencies and build step
|
|
8
|
+
|
|
9
|
+
## 2.0.1-next.0
|
|
10
|
+
|
|
11
|
+
### Major Changes
|
|
12
|
+
|
|
13
|
+
- e74b305: Release: Payload 3.7.0
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- Updated dependencies [e74b305]
|
|
18
|
+
- @websolutespa/bom-core@2.0.1-next.0
|
|
19
|
+
|
|
3
20
|
## 1.8.4
|
|
4
21
|
|
|
5
22
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,23 @@
|
|
|
1
|
-
import { IImageResize } from
|
|
1
|
+
import { IImageResize } from "@websolutespa/bom-core";
|
|
2
2
|
|
|
3
|
+
//#region src/image/image.handler.d.ts
|
|
3
4
|
type IImageHandlerOptions = {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
domains: string[];
|
|
6
|
+
sizes: number[];
|
|
7
|
+
quality: number;
|
|
7
8
|
};
|
|
8
9
|
type IImageOptions = IImageResize & {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
origin: string;
|
|
11
|
+
search: string;
|
|
12
|
+
url: string;
|
|
12
13
|
};
|
|
13
|
-
declare function imageHandler({
|
|
14
|
+
declare function imageHandler({
|
|
15
|
+
domains,
|
|
16
|
+
sizes,
|
|
17
|
+
quality
|
|
18
|
+
}: IImageHandlerOptions): any;
|
|
19
|
+
//# sourceMappingURL=image.handler.d.ts.map
|
|
14
20
|
|
|
21
|
+
//#endregion
|
|
15
22
|
export { IImageHandlerOptions, IImageOptions, imageHandler };
|
|
23
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/image/image.handler.ts"],"sourcesContent":[],"mappings":";;;KAsBY,oBAAA;;EAAA,KAAA,EAAA,MAAA,EAAA;EAMA,OAAA,EAAA,MAAA;AAOZ,CAAA;AAA4B,KAPhB,aAAA,GAAgB,YAOA,GAAA;EAAA,MAC1B,EAAA,MAAA;EAAY,MACZ,EAAA,MAAA;EAAU,GACV,EAAA,MAAA;CAAuB;AACF,iBAJP,YAAA,CAIO;EAAA,OAAA;EAAA,KAAA;EAAA;AAAA,CAAA,EAApB,oBAAoB,CAAA,EAAA,GAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,331 +1,248 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import sharp from "sharp";
|
|
4
|
+
import { ImageStrategy, decryptImageResize } from "@websolutespa/bom-core";
|
|
29
5
|
|
|
30
|
-
|
|
31
|
-
var src_exports = {};
|
|
32
|
-
__export(src_exports, {
|
|
33
|
-
imageHandler: () => imageHandler
|
|
34
|
-
});
|
|
35
|
-
module.exports = __toCommonJS(src_exports);
|
|
36
|
-
|
|
37
|
-
// src/image/image.handler.ts
|
|
38
|
-
var fs = __toESM(require("fs"));
|
|
39
|
-
var path = __toESM(require("path"));
|
|
40
|
-
var import_sharp = __toESM(require("sharp"));
|
|
41
|
-
var import_bom_core = require("@websolutespa/bom-core");
|
|
42
|
-
|
|
43
|
-
// src/api/api.handler.ts
|
|
6
|
+
//#region src/api/api.handler.ts
|
|
44
7
|
function apiHandler(handler) {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
};
|
|
8
|
+
return async (request, response) => {
|
|
9
|
+
const method = (request.method || "GET").toLowerCase();
|
|
10
|
+
if (!handler[method]) return response.status(405).end(`Method ${method} Not Allowed`);
|
|
11
|
+
try {
|
|
12
|
+
await handler[method](request, response);
|
|
13
|
+
} catch (error) {
|
|
14
|
+
return errorHandler(error, response);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
56
17
|
}
|
|
57
18
|
function errorHandler(error, response) {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
console.error(error);
|
|
67
|
-
return response.status(500).json({ message: error.message });
|
|
19
|
+
if (typeof error === "string") {
|
|
20
|
+
const is404 = error.toLowerCase().endsWith("not found");
|
|
21
|
+
const statusCode = is404 ? 404 : 400;
|
|
22
|
+
return response.status(statusCode).json({ message: error });
|
|
23
|
+
}
|
|
24
|
+
if (error.name === "UnauthorizedError") return response.status(401).json({ message: "Invalid Token" });
|
|
25
|
+
console.error(error);
|
|
26
|
+
return response.status(500).json({ message: error.message });
|
|
68
27
|
}
|
|
69
28
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
} catch (error) {
|
|
125
|
-
console.error("imageHandler.error", error);
|
|
126
|
-
return response.status(error.status || 500).json({
|
|
127
|
-
errors: [{
|
|
128
|
-
message: error.message || error.name || error.statusText || "An error occurred"
|
|
129
|
-
}]
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
});
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/image/image.handler.ts
|
|
31
|
+
const IMAGE_STRATEGY = process.env.IMAGE_STRATEGY ? process.env.IMAGE_STRATEGY : ImageStrategy.Mixer;
|
|
32
|
+
const IMAGE_MAX_AGE = 604800;
|
|
33
|
+
const IMAGE_FOCAL_X = 50;
|
|
34
|
+
const IMAGE_FOCAL_Y = 50;
|
|
35
|
+
const IMAGE_QUALITY = 90;
|
|
36
|
+
function imageHandler({ domains = [], sizes = [], quality = IMAGE_QUALITY }) {
|
|
37
|
+
return apiHandler({ get: async (request, response) => {
|
|
38
|
+
try {
|
|
39
|
+
let imageOptions;
|
|
40
|
+
try {
|
|
41
|
+
imageOptions = IMAGE_STRATEGY === ImageStrategy.Token ? getEncryptedImageOptions(request, {
|
|
42
|
+
domains,
|
|
43
|
+
sizes,
|
|
44
|
+
quality
|
|
45
|
+
}) : getImageOptions(request, {
|
|
46
|
+
domains,
|
|
47
|
+
sizes,
|
|
48
|
+
quality
|
|
49
|
+
});
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return response.status(400).json({ errors: [{ message: error }] });
|
|
52
|
+
}
|
|
53
|
+
const cachedName = urlToCachedName(imageOptions);
|
|
54
|
+
if (fs.existsSync(cachedName)) {
|
|
55
|
+
const cachedImage = await getCachedImage(cachedName);
|
|
56
|
+
response.setHeader("Content-Type", "image/webp");
|
|
57
|
+
response.setHeader("Expires", new Date(Date.now() + IMAGE_MAX_AGE * 1e3).toUTCString());
|
|
58
|
+
response.setHeader("Cache-Control", `public, max-age=${IMAGE_MAX_AGE}`);
|
|
59
|
+
return response.send(cachedImage);
|
|
60
|
+
}
|
|
61
|
+
if (isInvalidReferer(request)) return response.status(401).send("you are not authorized to perform this action");
|
|
62
|
+
if (imageOptions.url.indexOf("http") === -1 && isVercel()) response.redirect(307, imageOptions.url);
|
|
63
|
+
const originalImageBuffer = await getOriginalImage(imageOptions.url, domains, request.headers);
|
|
64
|
+
if (originalImageBuffer) {
|
|
65
|
+
const originalImage = sharp(originalImageBuffer, { animated: isGIF(imageOptions.url) });
|
|
66
|
+
const resizedImage = await resizeImage(originalImage, imageOptions);
|
|
67
|
+
const compressedImage = resizedImage.webp({ quality: imageOptions.q });
|
|
68
|
+
compressedImage.toFile(cachedName).then(() => console.log("imageHandler.sharp.cached", cachedName)).catch((error) => console.error("imageHandler.sharp.error", cachedName, error));
|
|
69
|
+
const data = await compressedImage.toBuffer();
|
|
70
|
+
response.setHeader("Content-Type", "image/webp");
|
|
71
|
+
response.setHeader("Expires", new Date(Date.now() + IMAGE_MAX_AGE * 1e3).toUTCString());
|
|
72
|
+
response.setHeader("Cache-Control", `public, max-age=${IMAGE_MAX_AGE}`);
|
|
73
|
+
return response.end(data);
|
|
74
|
+
}
|
|
75
|
+
} catch (error) {
|
|
76
|
+
console.error("imageHandler.error", error);
|
|
77
|
+
return response.status(error.status || 500).json({ errors: [{ message: error.message || error.name || error.statusText || "An error occurred" }] });
|
|
78
|
+
}
|
|
79
|
+
} });
|
|
80
|
+
}
|
|
81
|
+
function isGIF(src) {
|
|
82
|
+
return src.indexOf(".gif") !== -1;
|
|
134
83
|
}
|
|
135
84
|
function isInvalidReferer(request) {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
}
|
|
142
|
-
return false;
|
|
85
|
+
const { headers } = request;
|
|
86
|
+
const referer = headers.referer;
|
|
87
|
+
const publicUrl = process.env.NEXT_PUBLIC_URL || "";
|
|
88
|
+
if (IMAGE_STRATEGY !== ImageStrategy.Token && referer && publicUrl !== "https://" && referer.indexOf(publicUrl) !== 0) return true;
|
|
89
|
+
return false;
|
|
143
90
|
}
|
|
144
91
|
function getImageOptions(request, options) {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
} : {
|
|
175
|
-
w: width,
|
|
176
|
-
q: imageQuality,
|
|
177
|
-
src: url,
|
|
178
|
-
url,
|
|
179
|
-
origin: String(origin),
|
|
180
|
-
search: String(search)
|
|
181
|
-
};
|
|
92
|
+
const { slugs, origin = "", search = "", w, h, x, y, q } = request.query;
|
|
93
|
+
if (!Array.isArray(slugs) || slugs.length === 0) throw "missing slugs parameter";
|
|
94
|
+
const width = typeof w === "string" ? parseInt(w) : void 0;
|
|
95
|
+
if (!width) throw "missing w parameter";
|
|
96
|
+
if (!options.sizes.includes(width)) throw "invalid w parameter";
|
|
97
|
+
const height = typeof h === "string" ? parseInt(h) : void 0;
|
|
98
|
+
const focalX = typeof x === "string" ? parseInt(x) : IMAGE_FOCAL_X;
|
|
99
|
+
const focalY = typeof y === "string" ? parseInt(y) : IMAGE_FOCAL_Y;
|
|
100
|
+
const imageQuality = Math.max(30, Math.min(100, typeof q === "string" ? parseInt(q) : options.quality));
|
|
101
|
+
if (imageQuality !== options.quality) throw "invalid q parameter";
|
|
102
|
+
const url = origin + "/" + slugs.join("/") + search;
|
|
103
|
+
return height ? {
|
|
104
|
+
w: width,
|
|
105
|
+
h: height,
|
|
106
|
+
x: focalX,
|
|
107
|
+
y: focalY,
|
|
108
|
+
q: imageQuality,
|
|
109
|
+
src: url,
|
|
110
|
+
url,
|
|
111
|
+
origin: String(origin),
|
|
112
|
+
search: String(search)
|
|
113
|
+
} : {
|
|
114
|
+
w: width,
|
|
115
|
+
q: imageQuality,
|
|
116
|
+
src: url,
|
|
117
|
+
url,
|
|
118
|
+
origin: String(origin),
|
|
119
|
+
search: String(search)
|
|
120
|
+
};
|
|
182
121
|
}
|
|
183
122
|
function getEncryptedImageOptions(request, options) {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return {
|
|
198
|
-
...imageResize,
|
|
199
|
-
url,
|
|
200
|
-
origin: String(origin),
|
|
201
|
-
search: String(search)
|
|
202
|
-
};
|
|
123
|
+
const { slugs, origin = "", search = "", t } = request.query;
|
|
124
|
+
if (!Array.isArray(slugs) || slugs.length === 0) throw "missing slugs parameter";
|
|
125
|
+
if (typeof t !== "string") throw "missing t parameter";
|
|
126
|
+
const imageResize = decryptImageResize(t);
|
|
127
|
+
imageResize.src = decodeURIComponent(imageResize.src);
|
|
128
|
+
const url = decodeURIComponent(origin + "/" + slugs.join("/") + search);
|
|
129
|
+
if (imageResize.src !== url) throw `invalid src parameter ${imageResize.src} ${url}`;
|
|
130
|
+
return {
|
|
131
|
+
...imageResize,
|
|
132
|
+
url,
|
|
133
|
+
origin: String(origin),
|
|
134
|
+
search: String(search)
|
|
135
|
+
};
|
|
203
136
|
}
|
|
204
137
|
async function resizeImage(originalImage, imageOptions) {
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
height: extractHeight
|
|
247
|
-
});
|
|
248
|
-
} else {
|
|
249
|
-
return defaultResizeOptions();
|
|
250
|
-
}
|
|
251
|
-
} else {
|
|
252
|
-
return defaultResizeOptions();
|
|
253
|
-
}
|
|
138
|
+
const { w: resizeWidth, h: resizeHeight, x: focalX = IMAGE_FOCAL_X, y: focalY = IMAGE_FOCAL_Y } = imageOptions;
|
|
139
|
+
const defaultResizeOptions = () => {
|
|
140
|
+
return originalImage.resize({
|
|
141
|
+
width: resizeWidth,
|
|
142
|
+
height: resizeHeight ? resizeHeight : void 0,
|
|
143
|
+
fit: sharp.fit.cover,
|
|
144
|
+
position: sharp.strategy.attention,
|
|
145
|
+
withoutEnlargement: true
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
if (resizeHeight && (focalX !== IMAGE_FOCAL_X || focalY !== IMAGE_FOCAL_Y)) {
|
|
149
|
+
const { width: originalWidth, height: originalHeight } = await originalImage.metadata();
|
|
150
|
+
if (originalWidth && originalHeight) {
|
|
151
|
+
const resizeAspectRatio = resizeWidth / resizeHeight;
|
|
152
|
+
const originalAspectRatio = originalWidth / originalHeight;
|
|
153
|
+
const prioritizeHeight = resizeAspectRatio < originalAspectRatio;
|
|
154
|
+
const imageToResize = originalImage.clone();
|
|
155
|
+
const scaledImage = imageToResize.resize(prioritizeHeight ? {
|
|
156
|
+
height: resizeHeight,
|
|
157
|
+
fit: sharp.fit.cover
|
|
158
|
+
} : {
|
|
159
|
+
width: resizeWidth,
|
|
160
|
+
fit: sharp.fit.cover
|
|
161
|
+
});
|
|
162
|
+
const { info: scaledImageInfo } = await scaledImage.toBuffer({ resolveWithObject: true });
|
|
163
|
+
const extractWidth = resizeWidth ?? scaledImageInfo.width;
|
|
164
|
+
const maxOffsetX = scaledImageInfo.width - extractWidth;
|
|
165
|
+
const leftFocalEdge = Math.round(scaledImageInfo.width * (focalX / 100) - extractWidth / 2);
|
|
166
|
+
const extractX = Math.min(Math.max(0, leftFocalEdge), maxOffsetX);
|
|
167
|
+
const extractHeight = resizeHeight ?? scaledImageInfo.height;
|
|
168
|
+
const maxOffsetY = scaledImageInfo.height - extractHeight;
|
|
169
|
+
const topFocalEdge = Math.round(scaledImageInfo.height * (focalY / 100) - extractHeight / 2);
|
|
170
|
+
const extractY = Math.min(Math.max(0, topFocalEdge), maxOffsetY);
|
|
171
|
+
return scaledImage.extract({
|
|
172
|
+
left: extractX,
|
|
173
|
+
top: extractY,
|
|
174
|
+
width: extractWidth,
|
|
175
|
+
height: extractHeight
|
|
176
|
+
});
|
|
177
|
+
} else return defaultResizeOptions();
|
|
178
|
+
} else return defaultResizeOptions();
|
|
254
179
|
}
|
|
255
180
|
function getOriginalImage(url, domains, headers) {
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
}
|
|
288
|
-
});
|
|
181
|
+
return new Promise((resolve, reject) => {
|
|
182
|
+
if (url.indexOf("http") === 0) {
|
|
183
|
+
if (isInvalidDomain(url, domains)) return reject({
|
|
184
|
+
status: 401,
|
|
185
|
+
message: "invalid origin"
|
|
186
|
+
});
|
|
187
|
+
fetch(url, {
|
|
188
|
+
method: "GET",
|
|
189
|
+
mode: "cors",
|
|
190
|
+
headers: { "Access-Control-Allow-Origin": "*" }
|
|
191
|
+
}).then((response) => {
|
|
192
|
+
if (!response.ok) return reject({
|
|
193
|
+
status: response.status,
|
|
194
|
+
message: response.statusText
|
|
195
|
+
});
|
|
196
|
+
response.arrayBuffer().then((buffer) => {
|
|
197
|
+
return resolve(Buffer.from(buffer));
|
|
198
|
+
}).catch((error) => {
|
|
199
|
+
return reject(error);
|
|
200
|
+
});
|
|
201
|
+
}).catch((error) => {
|
|
202
|
+
return reject(error);
|
|
203
|
+
});
|
|
204
|
+
} else {
|
|
205
|
+
const filePath = path.join(process.cwd(), "public", url);
|
|
206
|
+
fs.readFile(filePath, (error, data) => {
|
|
207
|
+
if (error) return reject(error);
|
|
208
|
+
return resolve(data);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
});
|
|
289
212
|
}
|
|
290
213
|
function getCachedImage(pathname) {
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
});
|
|
298
|
-
});
|
|
214
|
+
return new Promise((resolve, reject) => {
|
|
215
|
+
fs.readFile(pathname, (error, data) => {
|
|
216
|
+
if (error) return reject(error);
|
|
217
|
+
return resolve(data);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
299
220
|
}
|
|
300
221
|
function urlToFileName(url) {
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
222
|
+
const segments = url.split("?");
|
|
223
|
+
const path$1 = segments[0];
|
|
224
|
+
const query = segments[1];
|
|
225
|
+
let uniqueName = path$1.replace("://", "_").replace(/\.|\/|\?|=/g, "_");
|
|
226
|
+
uniqueName = uniqueName.substring(0, uniqueName.lastIndexOf("_")) + (query ? "_" + query.replace(/\.|\/|\?|=/g, "_") : "") + "." + uniqueName.substring(uniqueName.lastIndexOf("_") + 1, uniqueName.length);
|
|
227
|
+
return uniqueName;
|
|
307
228
|
}
|
|
308
229
|
function isVercel() {
|
|
309
|
-
|
|
230
|
+
return process && process.env && String(process.env.VERCEL) === "1";
|
|
310
231
|
}
|
|
311
232
|
function urlToCachedName(options) {
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
const cachedName = options.h ? path.join(cacheDir, `${parsedName.name}_w_${options.w}_h_${options.h || 0}_x_${options.x || IMAGE_FOCAL_X}_y_${options.y || IMAGE_FOCAL_Y}_q_${options.q}${parsedName.ext}`) : path.join(cacheDir, `${parsedName.name}_w_${options.w}_q_${options.q}${parsedName.ext}`);
|
|
319
|
-
return cachedName;
|
|
233
|
+
const fileName = urlToFileName(options.url);
|
|
234
|
+
const parsedName = path.parse(fileName);
|
|
235
|
+
const cacheDir = isVercel() ? path.join("/tmp", ".cache") : path.join(process.cwd(), ".cache");
|
|
236
|
+
if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir);
|
|
237
|
+
const cachedName = options.h ? path.join(cacheDir, `${parsedName.name}_w_${options.w}_h_${options.h || 0}_x_${options.x || IMAGE_FOCAL_X}_y_${options.y || IMAGE_FOCAL_Y}_q_${options.q}${parsedName.ext}`) : path.join(cacheDir, `${parsedName.name}_w_${options.w}_q_${options.q}${parsedName.ext}`);
|
|
238
|
+
return cachedName;
|
|
320
239
|
}
|
|
321
240
|
function isInvalidDomain(src, domains) {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
const url = new URL(src);
|
|
326
|
-
return !domains.includes(url.hostname);
|
|
241
|
+
if (IMAGE_STRATEGY === ImageStrategy.Token) return false;
|
|
242
|
+
const url = new URL(src);
|
|
243
|
+
return !domains.includes(url.hostname);
|
|
327
244
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
245
|
+
|
|
246
|
+
//#endregion
|
|
247
|
+
export { imageHandler };
|
|
248
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["handler: IApiHandler","request: NextApiRequest","response: NextApiResponse","method: ICrudMethod","error: any","IMAGE_STRATEGY: ImageStrategy","request: NextApiRequest","response: NextApiResponse","imageOptions: IImageOptions","error: any","src: string","options: IImageHandlerOptions","originalImage: sharp.Sharp","url: string","domains: string[]","headers: IncomingHttpHeaders","pathname: string","path","options: IImageOptions"],"sources":["../src/api/api.handler.ts","../src/image/image.handler.ts"],"sourcesContent":["import { NextApiRequest, NextApiResponse } from 'next';\r\n\r\nexport type ICrudMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | string;\r\n\r\nexport type IHandler = (request: NextApiRequest, response: NextApiResponse) => Promise<any>;\r\n\r\nexport type IApiHandler = Record<ICrudMethod, IHandler>;\r\n\r\nexport function apiHandler(handler: IApiHandler): any {\r\n return async (request: NextApiRequest, response: NextApiResponse): Promise<any> => {\r\n const method: ICrudMethod = (request.method || 'GET').toLowerCase() as ICrudMethod;\r\n // check handler supports HTTP method\r\n if (!handler[method]) {\r\n return response.status(405).end(`Method ${method} Not Allowed`);\r\n }\r\n try {\r\n // global middleware\r\n // await jwtMiddleware(request, response);\r\n // route handler\r\n await handler[method](request, response);\r\n } catch (error) {\r\n // console.log('error', error);\r\n // global error handler\r\n return errorHandler(error, response);\r\n }\r\n };\r\n}\r\n\r\nexport function errorHandler(error: any, response: NextApiResponse): Promise<any> | void {\r\n if (typeof (error) === 'string') {\r\n // custom application error\r\n const is404 = error.toLowerCase().endsWith('not found');\r\n const statusCode = is404 ? 404 : 400;\r\n return response.status(statusCode).json({ message: error });\r\n }\r\n if (error.name === 'UnauthorizedError') {\r\n // jwt authentication error\r\n return response.status(401).json({ message: 'Invalid Token' });\r\n }\r\n // default to 500 server error\r\n console.error(error);\r\n return response.status(500).json({ message: error.message });\r\n}\r\n","import { IncomingHttpHeaders } from 'http';\r\n// Importing the 'fs' module to work with the file system\r\nimport * as fs from 'fs';\r\n// Importing the 'NextApiRequest' and 'NextApiResponse' from 'next' for handling API requests and responses\r\nimport { NextApiRequest, NextApiResponse } from 'next';\r\n// Importing the 'path' module to work with file and directory paths\r\nimport * as path from 'path';\r\n// Importing 'sharp' for image processing\r\nimport sharp from 'sharp';\r\n// Importing 'apiHandler' from '../api/api.handler'\r\nimport { decryptImageResize, IImageResize, ImageStrategy } from '@websolutespa/bom-core';\r\nimport { apiHandler } from '../api/api.handler';\r\n\r\nconst IMAGE_STRATEGY: ImageStrategy = process.env.IMAGE_STRATEGY ?\r\n process.env.IMAGE_STRATEGY as ImageStrategy :\r\n ImageStrategy.Mixer;\r\n\r\nconst IMAGE_MAX_AGE = 604800;\r\nconst IMAGE_FOCAL_X = 50;\r\nconst IMAGE_FOCAL_Y = 50;\r\nconst IMAGE_QUALITY = 90;\r\n\r\nexport type IImageHandlerOptions = {\r\n domains: string[];\r\n sizes: number[];\r\n quality: number;\r\n};\r\n\r\nexport type IImageOptions = IImageResize & {\r\n origin: string;\r\n search: string;\r\n url: string;\r\n};\r\n\r\n// Exporting the 'imageHandler' function\r\nexport function imageHandler({\r\n domains = [],\r\n sizes = [],\r\n quality = IMAGE_QUALITY,\r\n}: IImageHandlerOptions) {\r\n // Returning the 'apiHandler' function with a configuration object\r\n return apiHandler({\r\n // Defining the 'get' method for handling GET requests\r\n get: async (request: NextApiRequest, response: NextApiResponse) => {\r\n try {\r\n let imageOptions: IImageOptions;\r\n try {\r\n imageOptions = (IMAGE_STRATEGY === ImageStrategy.Token ?\r\n getEncryptedImageOptions(request, { domains, sizes, quality }) :\r\n getImageOptions(request, { domains, sizes, quality }));\r\n } catch (error) {\r\n return response.status(400).json({\r\n errors: [{\r\n message: error,\r\n }],\r\n });\r\n }\r\n // Generating a cached name for the image\r\n const cachedName = urlToCachedName(imageOptions);\r\n // Checking if the cached image exists\r\n if (fs.existsSync(cachedName)) {\r\n // console.log('imageHandler.fromCache', cachedName);\r\n // Reading the cached image\r\n const cachedImage = await getCachedImage(cachedName);\r\n // Setting the 'Content-Type' header to 'image/webp'\r\n response.setHeader('Content-Type', 'image/webp');\r\n // Setting the 'Expires' header to the current time plus the maximum age of the image (in seconds)\r\n response.setHeader('Expires', new Date(Date.now() + IMAGE_MAX_AGE * 1000).toUTCString());\r\n // Setting the 'Cache-Control' header to 'public' and setting 'max-age' to the maximum age of the image\r\n response.setHeader('Cache-Control', `public, max-age=${IMAGE_MAX_AGE}`);\r\n // Ending the response and sending the cached image\r\n return response.send(cachedImage);\r\n }\r\n // Check referrer\r\n if (isInvalidReferer(request)) {\r\n return response.status(401).send('you are not authorized to perform this action');\r\n }\r\n // Temporarily fix Vercel local image issue\r\n if (imageOptions.url.indexOf('http') === -1 && isVercel()) {\r\n response.redirect(307, imageOptions.url);\r\n }\r\n // Reading the original image\r\n const originalImageBuffer = await getOriginalImage(imageOptions.url, domains, request.headers);\r\n // Checking if the original image exists\r\n if (originalImageBuffer) {\r\n // Original image\r\n const originalImage = sharp(originalImageBuffer, {\r\n animated: isGIF(imageOptions.url),\r\n });\r\n // Resizing the original image and converting it to WebP format\r\n const resizedImage = await resizeImage(originalImage, imageOptions);\r\n // Converting resized image to WebP format\r\n const compressedImage = resizedImage\r\n .webp({\r\n quality: imageOptions.q,\r\n // nearLossless: true,\r\n });\r\n // Saving the resized image to the cache\r\n compressedImage.toFile(cachedName)\r\n .then(() => console.log('imageHandler.sharp.cached', cachedName))\r\n .catch((error: any) => console.error('imageHandler.sharp.error', cachedName, error));\r\n // Converting the resized image to a buffer\r\n const data = await compressedImage.toBuffer();\r\n // Setting the 'Content-Type' header to 'image/webp'\r\n response.setHeader('Content-Type', 'image/webp');\r\n // Setting the 'Expires' header to the current time plus the maximum age of the image (in seconds)\r\n response.setHeader('Expires', new Date(Date.now() + IMAGE_MAX_AGE * 1000).toUTCString());\r\n // Setting the 'Cache-Control' header to 'public' and setting 'max-age' to the maximum age of the image\r\n response.setHeader('Cache-Control', `public, max-age=${IMAGE_MAX_AGE}`);\r\n // Sending data in the response\r\n return response.end(data);\r\n }\r\n } catch (error: any) {\r\n // Logging an error message and throwing the error\r\n console.error('imageHandler.error', error);\r\n return response.status(error.status || 500).json({\r\n errors: [{\r\n message: error.message || error.name || error.statusText || 'An error occurred',\r\n }],\r\n });\r\n }\r\n },\r\n });\r\n}\r\n\r\nfunction isGIF(src: string): boolean {\r\n return src.indexOf('.gif') !== -1;\r\n}\r\n\r\nfunction isInvalidReferer(request: NextApiRequest): boolean {\r\n const { headers } = request;\r\n const referer = headers.referer;\r\n const publicUrl = process.env.NEXT_PUBLIC_URL || '';\r\n // console.log('referef', referer, 'publicUrl', publicUrl, 'IMAGE_STRATEGY', IMAGE_STRATEGY, ImageStrategy.Token);\r\n if (\r\n IMAGE_STRATEGY !== ImageStrategy.Token &&\r\n referer &&\r\n publicUrl !== 'https://' &&\r\n referer.indexOf(publicUrl) !== 0\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n}\r\n\r\nfunction getImageOptions(request: NextApiRequest, options: IImageHandlerOptions): IImageOptions {\r\n // Destructuring 'slugs', 'origin', 'search', 'w', 'h', 'x', 'y', 'q' from the request query\r\n const { slugs, origin = '', search = '', w, h, x, y, q } = request.query;\r\n // Checking slugs\r\n if (!Array.isArray(slugs) || slugs.length === 0) {\r\n // console.error('imageHandler', 'missing slugs parameter');\r\n throw 'missing slugs parameter';\r\n }\r\n // Parsing 'w' to an integer and assigning it to 'width'\r\n const width = typeof w === 'string' ? parseInt(w) : undefined;\r\n // Checking if 'width' is not defined\r\n if (!width) {\r\n // Logging an error message and returning a 400 status code with a message\r\n // console.error('imageHandler', 'missing w parameter');\r\n throw 'missing w parameter';\r\n }\r\n // if (width > 2048) {\r\n if (!options.sizes.includes(width)) {\r\n throw 'invalid w parameter';\r\n }\r\n // Parsing 'h' to an integer and assigning it to 'height'\r\n const height = typeof h === 'string' ? parseInt(h) : undefined;\r\n // Parsing 'x' to an integer and assigning it to 'focalX'\r\n const focalX = typeof x === 'string' ? parseInt(x) : IMAGE_FOCAL_X;\r\n // Parsing 'y' to an integer and assigning it to 'focalY'\r\n const focalY = typeof y === 'string' ? parseInt(y) : IMAGE_FOCAL_Y;\r\n // Parsing 'q' to an integer, ensuring it's between 30 and 100, and assigning it to 'imageQuality'\r\n const imageQuality = Math.max(30, Math.min(100, (typeof q === 'string' ? parseInt(q) : options.quality)));\r\n // if (width > 2048) {\r\n if (imageQuality !== options.quality) {\r\n throw 'invalid q parameter';\r\n }\r\n // Generating url\r\n const url = origin + '/' + slugs.join('/') + search;\r\n //\r\n return height ? {\r\n w: width,\r\n h: height,\r\n x: focalX,\r\n y: focalY,\r\n q: imageQuality,\r\n src: url,\r\n url: url,\r\n origin: String(origin),\r\n search: String(search),\r\n } : {\r\n w: width,\r\n q: imageQuality,\r\n src: url,\r\n url: url,\r\n origin: String(origin),\r\n search: String(search),\r\n };\r\n}\r\n\r\nfunction getEncryptedImageOptions(request: NextApiRequest, options: IImageHandlerOptions): IImageOptions {\r\n // Destructuring 'slugs', 'origin', 'search', 't' from the request query\r\n const { slugs, origin = '', search = '', t } = request.query;\r\n // Checking slugs\r\n if (!Array.isArray(slugs) || slugs.length === 0) {\r\n // console.error('imageHandler', 'missing slugs parameter');\r\n throw 'missing slugs parameter';\r\n }\r\n if (typeof t !== 'string') {\r\n throw 'missing t parameter';\r\n }\r\n const imageResize = decryptImageResize(t);\r\n /*\r\n // Checking if 'w' is not defined\r\n if (!imageResize.w) {\r\n throw 'missing w parameter';\r\n }\r\n // if (width > 2048) {\r\n if (!options.sizes.includes(imageResize.w)) {\r\n throw 'invalid w parameter';\r\n }\r\n // Ensuring 'q' is between 30 and 100, and assigning it to 'imageQuality'\r\n const imageQuality = Math.max(30, Math.min(100, imageResize.q || options.quality));\r\n if (imageQuality !== options.quality) {\r\n throw 'invalid q parameter';\r\n }\r\n */\r\n imageResize.src = decodeURIComponent(imageResize.src);\r\n // Generating url\r\n const url = decodeURIComponent(origin + '/' + slugs.join('/') + search);\r\n //\r\n if (imageResize.src !== url) {\r\n throw `invalid src parameter ${imageResize.src} ${url}`;\r\n }\r\n //\r\n return {\r\n ...imageResize,\r\n url: url,\r\n origin: String(origin),\r\n search: String(search),\r\n };\r\n}\r\n\r\nasync function resizeImage(originalImage: sharp.Sharp, imageOptions: IImageOptions): Promise<sharp.Sharp> {\r\n const { w: resizeWidth, h: resizeHeight, x: focalX = IMAGE_FOCAL_X, y: focalY = IMAGE_FOCAL_Y } = imageOptions;\r\n const defaultResizeOptions = () => {\r\n return originalImage.resize({\r\n width: resizeWidth,\r\n height: resizeHeight ? resizeHeight : undefined,\r\n fit: sharp.fit.cover,\r\n position: sharp.strategy.attention,\r\n withoutEnlargement: true,\r\n });\r\n };\r\n if (resizeHeight && (focalX !== IMAGE_FOCAL_X || focalY !== IMAGE_FOCAL_Y)) {\r\n const { width: originalWidth, height: originalHeight } = await originalImage.metadata();\r\n if (originalWidth && originalHeight) {\r\n const resizeAspectRatio = resizeWidth / resizeHeight;\r\n const originalAspectRatio = originalWidth / originalHeight;\r\n const prioritizeHeight = resizeAspectRatio < originalAspectRatio;\r\n const imageToResize = originalImage.clone();\r\n // Scale the image up or down to fit the resize dimensions\r\n const scaledImage = imageToResize.resize(prioritizeHeight ? {\r\n height: resizeHeight,\r\n fit: sharp.fit.cover,\r\n } : {\r\n width: resizeWidth,\r\n fit: sharp.fit.cover,\r\n });\r\n const { info: scaledImageInfo } = await scaledImage.toBuffer({ resolveWithObject: true });\r\n // extractWidth\r\n const extractWidth = resizeWidth ?? scaledImageInfo.width;\r\n const maxOffsetX = scaledImageInfo.width - extractWidth;\r\n const leftFocalEdge = Math.round(\r\n scaledImageInfo.width * (focalX / 100) - extractWidth / 2\r\n );\r\n // extractX\r\n const extractX = Math.min(Math.max(0, leftFocalEdge), maxOffsetX);\r\n // extractHeight\r\n const extractHeight = resizeHeight ?? scaledImageInfo.height;\r\n const maxOffsetY = scaledImageInfo.height - extractHeight;\r\n const topFocalEdge = Math.round(\r\n scaledImageInfo.height * (focalY / 100) - extractHeight / 2\r\n );\r\n // extractY\r\n const extractY = Math.min(Math.max(0, topFocalEdge), maxOffsetY);\r\n // Extract the focal area from the scaled image\r\n return scaledImage.extract({\r\n left: extractX,\r\n top: extractY,\r\n width: extractWidth,\r\n height: extractHeight,\r\n });\r\n } else {\r\n return defaultResizeOptions();\r\n }\r\n } else {\r\n return defaultResizeOptions();\r\n }\r\n}\r\n\r\n// Defining the 'getOriginalImage' function\r\nfunction getOriginalImage(url: string, domains: string[], headers: IncomingHttpHeaders): Promise<Buffer> {\r\n // Returning a new promise\r\n return new Promise((resolve, reject) => {\r\n // Checking if 'url' starts with 'http'\r\n if (url.indexOf('http') === 0) {\r\n if (isInvalidDomain(url, domains)) {\r\n return reject({ status: 401, message: 'invalid origin' });\r\n }\r\n // Fetching the image from the URL\r\n fetch(url, {\r\n method: 'GET',\r\n mode: 'cors',\r\n headers: {\r\n 'Access-Control-Allow-Origin': '*',\r\n },\r\n })\r\n .then(response => {\r\n if (!response.ok) {\r\n return reject({ status: response.status, message: response.statusText });\r\n }\r\n response.arrayBuffer().then(buffer => {\r\n return resolve(Buffer.from(buffer));\r\n }).catch(error => {\r\n return reject(error);\r\n });\r\n })\r\n .catch(error => {\r\n // Rejecting the promise with the error\r\n return reject(error);\r\n });\r\n } else {\r\n // Reading the image from the file system\r\n const filePath = path.join(process.cwd(), 'public', url);\r\n // console.log('imageHandler.getOriginalImage.filePath', filePath);\r\n fs.readFile(filePath, (error, data) => {\r\n if (error) {\r\n return reject(error);\r\n }\r\n // Resolving the promise with the image data\r\n return resolve(data);\r\n });\r\n }\r\n });\r\n}\r\n\r\n// Defining the 'getCachedImage' function\r\nfunction getCachedImage(pathname: string): Promise<Buffer> {\r\n // Returning a new promise\r\n return new Promise((resolve, reject) => {\r\n // Reading the image from the file system\r\n fs.readFile(pathname, (error, data) => {\r\n if (error) {\r\n // Rejecting the promise with the error\r\n return reject(error);\r\n }\r\n // Resolving the promise with the image data\r\n return resolve(data);\r\n });\r\n });\r\n}\r\n\r\n// Defining the 'urlToFileName' function\r\nfunction urlToFileName(url: string): string {\r\n // Replacing useless characters with UNDERSCORE\r\n const segments = url.split('?');\r\n const path = segments[0]!;\r\n const query = segments[1];\r\n let uniqueName = path.replace('://', '_').replace(/\\.|\\/|\\?|=/g, '_');\r\n // Replacing last UNDERSCORE with a DOT\r\n uniqueName = uniqueName.substring(0, uniqueName.lastIndexOf('_'))\r\n + (query ? '_' + query.replace(/\\.|\\/|\\?|=/g, '_') : '')\r\n + '.' + uniqueName.substring(uniqueName.lastIndexOf('_') + 1, uniqueName.length);\r\n // Returning the unique name\r\n return uniqueName;\r\n}\r\n\r\nfunction isVercel(): boolean {\r\n return process && process.env && String(process.env.VERCEL) === '1';\r\n}\r\n\r\n// Defining the 'urlToCachedName' function\r\nfunction urlToCachedName(options: IImageOptions): string {\r\n // Converting the URL to a file name\r\n const fileName = urlToFileName(options.url);\r\n // Parsing the file name\r\n const parsedName = path.parse(fileName);\r\n // Defining the cache directory\r\n const cacheDir = isVercel() ?\r\n path.join('/tmp', '.cache') :\r\n path.join(process.cwd(), '.cache');\r\n // Checking if the cache directory exists\r\n if (!fs.existsSync(cacheDir)) {\r\n // Creating the cache directory\r\n fs.mkdirSync(cacheDir);\r\n }\r\n // Generating the cached name\r\n const cachedName = options.h ?\r\n path.join(cacheDir, `${parsedName.name}_w_${options.w}_h_${options.h || 0}_x_${options.x || IMAGE_FOCAL_X}_y_${options.y || IMAGE_FOCAL_Y}_q_${options.q}${parsedName.ext}`) :\r\n path.join(cacheDir, `${parsedName.name}_w_${options.w}_q_${options.q}${parsedName.ext}`);\r\n // Returning the cached name\r\n return cachedName;\r\n}\r\n\r\nfunction isInvalidDomain(src: string, domains: string[]): boolean {\r\n if (IMAGE_STRATEGY === ImageStrategy.Token) {\r\n return false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SAAS,gBAAgBC,SAAgC;CAEvD,MAAM,WAAW,cAAc,QAAQ,IAAI;CAE3C,MAAM,aAAa,KAAK,MAAM,SAAS;CAEvC,MAAM,WAAW,UAAU,GACzB,KAAK,KAAK,QAAQ,SAAS,GAC3B,KAAK,KAAK,QAAQ,KAAK,EAAE,SAAS;AAEpC,KAAI,CAAC,GAAG,WAAW,SAAS,EAE1B,GAAG,UAAU,SAAS;CAGxB,MAAM,aAAa,QAAQ,IACzB,KAAK,KAAK,UAAU,GAAG,WAAW,KAAK,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,QAAQ,KAAK,EAAE,GAAG,EAAE,QAAQ,KAAK,cAAc,GAAG,EAAE,QAAQ,KAAK,cAAc,GAAG,EAAE,QAAQ,IAAI,WAAW,KAAK,CAAC,GAC5K,KAAK,KAAK,UAAU,GAAG,WAAW,KAAK,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,QAAQ,IAAI,WAAW,KAAK,CAAC;AAE1F,QAAO;AACR;AAED,SAAS,gBAAgBR,KAAaI,SAA4B;AAChE,KAAI,mBAAmB,cAAc,MACnC,QAAO;CAET,MAAM,MAAM,IAAI,IAAI;AACpB,QAAO,CAAC,QAAQ,SAAS,IAAI,SAAS;AACvC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@websolutespa/bom-mixer-image",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.0.1-next.2",
|
|
4
4
|
"description": "Mixer Image module of the BOM Repository",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"bom",
|
|
@@ -14,47 +14,68 @@
|
|
|
14
14
|
},
|
|
15
15
|
"scripts": {
|
|
16
16
|
"lint": "eslint *.ts*",
|
|
17
|
-
"test": "
|
|
18
|
-
"test-watch": "
|
|
19
|
-
"coverage:integration": "npm run test -- --coverage",
|
|
17
|
+
"test": "vitest run",
|
|
18
|
+
"test-watch": "vitest",
|
|
19
|
+
"coverage:integration": "npm run test -- --coverage.enabled --coverage.provider=istanbul --coverage.all",
|
|
20
20
|
"coverage": "run-s -c --silent coverage:*",
|
|
21
|
-
"compile": "
|
|
21
|
+
"compile": "tsdown",
|
|
22
22
|
"prepack": "bom prepack",
|
|
23
|
-
"postpack": "bom postpack"
|
|
23
|
+
"postpack": "bom postpack",
|
|
24
|
+
"types": "tsc --noemit"
|
|
24
25
|
},
|
|
25
26
|
"dependencies": {},
|
|
26
27
|
"peerDependencies": {
|
|
27
|
-
"@websolutespa/bom-core": "
|
|
28
|
-
"next": "
|
|
29
|
-
"sharp": "
|
|
28
|
+
"@websolutespa/bom-core": "2.0.1-next.2",
|
|
29
|
+
"next": "15.4.10",
|
|
30
|
+
"sharp": "0.34.2"
|
|
30
31
|
},
|
|
31
32
|
"devDependencies": {
|
|
32
33
|
"@types/sharp": "^0.30.4",
|
|
33
|
-
"@websolutespa/bom-cli": "
|
|
34
|
-
"@websolutespa/test": "
|
|
35
|
-
"@websolutespa/tsconfig": "
|
|
36
|
-
"eslint": "
|
|
37
|
-
"eslint-config
|
|
38
|
-
"npm-run-all": "
|
|
39
|
-
"sharp": "0.
|
|
40
|
-
"
|
|
41
|
-
"tsup": "^6.7.0",
|
|
42
|
-
"typescript": "^5.4.5"
|
|
34
|
+
"@websolutespa/bom-cli": "2.0.1-next.2",
|
|
35
|
+
"@websolutespa/test": "2.0.1-next.2",
|
|
36
|
+
"@websolutespa/tsconfig": "2.0.1-next.2",
|
|
37
|
+
"eslint": "9.31.0",
|
|
38
|
+
"@websolutespa/eslint-config": "2.0.1-next.2",
|
|
39
|
+
"npm-run-all": "4.1.5",
|
|
40
|
+
"sharp": "0.34.2",
|
|
41
|
+
"typescript": "5.8.3"
|
|
43
42
|
},
|
|
44
43
|
"publishConfig": {
|
|
45
44
|
"access": "public"
|
|
46
45
|
},
|
|
47
46
|
"sideEffects": false,
|
|
47
|
+
"type": "module",
|
|
48
48
|
"prepack": {
|
|
49
49
|
"types": "./dist/index.d.ts",
|
|
50
50
|
"main": "./dist/index.js",
|
|
51
|
-
"source": "./src/index.ts"
|
|
51
|
+
"source": "./src/index.ts",
|
|
52
|
+
"exports": {
|
|
53
|
+
".": {
|
|
54
|
+
"import": "./dist/index.js",
|
|
55
|
+
"types": "./dist/index.d.ts",
|
|
56
|
+
"default": "./dist/index.js"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
52
59
|
},
|
|
53
60
|
"postpack": {
|
|
54
61
|
"types": "./src/index.ts",
|
|
55
|
-
"main": "./src/index.ts"
|
|
62
|
+
"main": "./src/index.ts",
|
|
63
|
+
"exports": {
|
|
64
|
+
".": {
|
|
65
|
+
"import": "./src/index.ts",
|
|
66
|
+
"types": "./src/index.ts",
|
|
67
|
+
"default": "./src/index.ts"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
56
70
|
},
|
|
57
71
|
"types": "./dist/index.d.ts",
|
|
58
72
|
"main": "./dist/index.js",
|
|
59
|
-
"source": "./src/index.ts"
|
|
73
|
+
"source": "./src/index.ts",
|
|
74
|
+
"exports": {
|
|
75
|
+
".": {
|
|
76
|
+
"import": "./dist/index.js",
|
|
77
|
+
"types": "./dist/index.d.ts",
|
|
78
|
+
"default": "./dist/index.js"
|
|
79
|
+
}
|
|
80
|
+
}
|
|
60
81
|
}
|
|
@@ -84,7 +84,9 @@ export function imageHandler({
|
|
|
84
84
|
// Checking if the original image exists
|
|
85
85
|
if (originalImageBuffer) {
|
|
86
86
|
// Original image
|
|
87
|
-
const originalImage = sharp(originalImageBuffer
|
|
87
|
+
const originalImage = sharp(originalImageBuffer, {
|
|
88
|
+
animated: isGIF(imageOptions.url),
|
|
89
|
+
});
|
|
88
90
|
// Resizing the original image and converting it to WebP format
|
|
89
91
|
const resizedImage = await resizeImage(originalImage, imageOptions);
|
|
90
92
|
// Converting resized image to WebP format
|
|
@@ -121,6 +123,10 @@ export function imageHandler({
|
|
|
121
123
|
});
|
|
122
124
|
}
|
|
123
125
|
|
|
126
|
+
function isGIF(src: string): boolean {
|
|
127
|
+
return src.indexOf('.gif') !== -1;
|
|
128
|
+
}
|
|
129
|
+
|
|
124
130
|
function isInvalidReferer(request: NextApiRequest): boolean {
|
|
125
131
|
const { headers } = request;
|
|
126
132
|
const referer = headers.referer;
|
|
@@ -359,7 +365,7 @@ function getCachedImage(pathname: string): Promise<Buffer> {
|
|
|
359
365
|
function urlToFileName(url: string): string {
|
|
360
366
|
// Replacing useless characters with UNDERSCORE
|
|
361
367
|
const segments = url.split('?');
|
|
362
|
-
const path = segments[0]
|
|
368
|
+
const path = segments[0]!;
|
|
363
369
|
const query = segments[1];
|
|
364
370
|
let uniqueName = path.replace('://', '_').replace(/\.|\/|\?|=/g, '_');
|
|
365
371
|
// Replacing last UNDERSCORE with a DOT
|
package/dist/index.mjs
DELETED
|
@@ -1,294 +0,0 @@
|
|
|
1
|
-
// src/image/image.handler.ts
|
|
2
|
-
import * as fs from "fs";
|
|
3
|
-
import * as path from "path";
|
|
4
|
-
import sharp from "sharp";
|
|
5
|
-
import { decryptImageResize, ImageStrategy } from "@websolutespa/bom-core";
|
|
6
|
-
|
|
7
|
-
// src/api/api.handler.ts
|
|
8
|
-
function apiHandler(handler) {
|
|
9
|
-
return async (request, response) => {
|
|
10
|
-
const method = (request.method || "GET").toLowerCase();
|
|
11
|
-
if (!handler[method]) {
|
|
12
|
-
return response.status(405).end(`Method ${method} Not Allowed`);
|
|
13
|
-
}
|
|
14
|
-
try {
|
|
15
|
-
await handler[method](request, response);
|
|
16
|
-
} catch (error) {
|
|
17
|
-
return errorHandler(error, response);
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
function errorHandler(error, response) {
|
|
22
|
-
if (typeof error === "string") {
|
|
23
|
-
const is404 = error.toLowerCase().endsWith("not found");
|
|
24
|
-
const statusCode = is404 ? 404 : 400;
|
|
25
|
-
return response.status(statusCode).json({ message: error });
|
|
26
|
-
}
|
|
27
|
-
if (error.name === "UnauthorizedError") {
|
|
28
|
-
return response.status(401).json({ message: "Invalid Token" });
|
|
29
|
-
}
|
|
30
|
-
console.error(error);
|
|
31
|
-
return response.status(500).json({ message: error.message });
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// src/image/image.handler.ts
|
|
35
|
-
var IMAGE_STRATEGY = process.env.IMAGE_STRATEGY ? process.env.IMAGE_STRATEGY : ImageStrategy.Mixer;
|
|
36
|
-
var IMAGE_MAX_AGE = 604800;
|
|
37
|
-
var IMAGE_FOCAL_X = 50;
|
|
38
|
-
var IMAGE_FOCAL_Y = 50;
|
|
39
|
-
var IMAGE_QUALITY = 90;
|
|
40
|
-
function imageHandler({
|
|
41
|
-
domains = [],
|
|
42
|
-
sizes = [],
|
|
43
|
-
quality = IMAGE_QUALITY
|
|
44
|
-
}) {
|
|
45
|
-
return apiHandler({
|
|
46
|
-
// Defining the 'get' method for handling GET requests
|
|
47
|
-
get: async (request, response) => {
|
|
48
|
-
try {
|
|
49
|
-
let imageOptions;
|
|
50
|
-
try {
|
|
51
|
-
imageOptions = IMAGE_STRATEGY === ImageStrategy.Token ? getEncryptedImageOptions(request, { domains, sizes, quality }) : getImageOptions(request, { domains, sizes, quality });
|
|
52
|
-
} catch (error) {
|
|
53
|
-
return response.status(400).json({
|
|
54
|
-
errors: [{
|
|
55
|
-
message: error
|
|
56
|
-
}]
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
const cachedName = urlToCachedName(imageOptions);
|
|
60
|
-
if (fs.existsSync(cachedName)) {
|
|
61
|
-
const cachedImage = await getCachedImage(cachedName);
|
|
62
|
-
response.setHeader("Content-Type", "image/webp");
|
|
63
|
-
response.setHeader("Expires", new Date(Date.now() + IMAGE_MAX_AGE * 1e3).toUTCString());
|
|
64
|
-
response.setHeader("Cache-Control", `public, max-age=${IMAGE_MAX_AGE}`);
|
|
65
|
-
return response.send(cachedImage);
|
|
66
|
-
}
|
|
67
|
-
if (isInvalidReferer(request)) {
|
|
68
|
-
return response.status(401).send("you are not authorized to perform this action");
|
|
69
|
-
}
|
|
70
|
-
if (imageOptions.url.indexOf("http") === -1 && isVercel()) {
|
|
71
|
-
response.redirect(307, imageOptions.url);
|
|
72
|
-
}
|
|
73
|
-
const originalImageBuffer = await getOriginalImage(imageOptions.url, domains, request.headers);
|
|
74
|
-
if (originalImageBuffer) {
|
|
75
|
-
const originalImage = sharp(originalImageBuffer);
|
|
76
|
-
const resizedImage = await resizeImage(originalImage, imageOptions);
|
|
77
|
-
const compressedImage = resizedImage.webp({
|
|
78
|
-
quality: imageOptions.q
|
|
79
|
-
// nearLossless: true,
|
|
80
|
-
});
|
|
81
|
-
compressedImage.toFile(cachedName).then(() => console.log("imageHandler.sharp.cached", cachedName)).catch((error) => console.error("imageHandler.sharp.error", cachedName, error));
|
|
82
|
-
const data = await compressedImage.toBuffer();
|
|
83
|
-
response.setHeader("Content-Type", "image/webp");
|
|
84
|
-
response.setHeader("Expires", new Date(Date.now() + IMAGE_MAX_AGE * 1e3).toUTCString());
|
|
85
|
-
response.setHeader("Cache-Control", `public, max-age=${IMAGE_MAX_AGE}`);
|
|
86
|
-
return response.end(data);
|
|
87
|
-
}
|
|
88
|
-
} catch (error) {
|
|
89
|
-
console.error("imageHandler.error", error);
|
|
90
|
-
return response.status(error.status || 500).json({
|
|
91
|
-
errors: [{
|
|
92
|
-
message: error.message || error.name || error.statusText || "An error occurred"
|
|
93
|
-
}]
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
function isInvalidReferer(request) {
|
|
100
|
-
const { headers } = request;
|
|
101
|
-
const referer = headers.referer;
|
|
102
|
-
const publicUrl = process.env.NEXT_PUBLIC_URL || "";
|
|
103
|
-
if (IMAGE_STRATEGY !== ImageStrategy.Token && referer && publicUrl !== "https://" && referer.indexOf(publicUrl) !== 0) {
|
|
104
|
-
return true;
|
|
105
|
-
}
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
108
|
-
function getImageOptions(request, options) {
|
|
109
|
-
const { slugs, origin = "", search = "", w, h, x, y, q } = request.query;
|
|
110
|
-
if (!Array.isArray(slugs) || slugs.length === 0) {
|
|
111
|
-
throw "missing slugs parameter";
|
|
112
|
-
}
|
|
113
|
-
const width = typeof w === "string" ? parseInt(w) : void 0;
|
|
114
|
-
if (!width) {
|
|
115
|
-
throw "missing w parameter";
|
|
116
|
-
}
|
|
117
|
-
if (!options.sizes.includes(width)) {
|
|
118
|
-
throw "invalid w parameter";
|
|
119
|
-
}
|
|
120
|
-
const height = typeof h === "string" ? parseInt(h) : void 0;
|
|
121
|
-
const focalX = typeof x === "string" ? parseInt(x) : IMAGE_FOCAL_X;
|
|
122
|
-
const focalY = typeof y === "string" ? parseInt(y) : IMAGE_FOCAL_Y;
|
|
123
|
-
const imageQuality = Math.max(30, Math.min(100, typeof q === "string" ? parseInt(q) : options.quality));
|
|
124
|
-
if (imageQuality !== options.quality) {
|
|
125
|
-
throw "invalid q parameter";
|
|
126
|
-
}
|
|
127
|
-
const url = origin + "/" + slugs.join("/") + search;
|
|
128
|
-
return height ? {
|
|
129
|
-
w: width,
|
|
130
|
-
h: height,
|
|
131
|
-
x: focalX,
|
|
132
|
-
y: focalY,
|
|
133
|
-
q: imageQuality,
|
|
134
|
-
src: url,
|
|
135
|
-
url,
|
|
136
|
-
origin: String(origin),
|
|
137
|
-
search: String(search)
|
|
138
|
-
} : {
|
|
139
|
-
w: width,
|
|
140
|
-
q: imageQuality,
|
|
141
|
-
src: url,
|
|
142
|
-
url,
|
|
143
|
-
origin: String(origin),
|
|
144
|
-
search: String(search)
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
function getEncryptedImageOptions(request, options) {
|
|
148
|
-
const { slugs, origin = "", search = "", t } = request.query;
|
|
149
|
-
if (!Array.isArray(slugs) || slugs.length === 0) {
|
|
150
|
-
throw "missing slugs parameter";
|
|
151
|
-
}
|
|
152
|
-
if (typeof t !== "string") {
|
|
153
|
-
throw "missing t parameter";
|
|
154
|
-
}
|
|
155
|
-
const imageResize = decryptImageResize(t);
|
|
156
|
-
imageResize.src = decodeURIComponent(imageResize.src);
|
|
157
|
-
const url = decodeURIComponent(origin + "/" + slugs.join("/") + search);
|
|
158
|
-
if (imageResize.src !== url) {
|
|
159
|
-
throw `invalid src parameter ${imageResize.src} ${url}`;
|
|
160
|
-
}
|
|
161
|
-
return {
|
|
162
|
-
...imageResize,
|
|
163
|
-
url,
|
|
164
|
-
origin: String(origin),
|
|
165
|
-
search: String(search)
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
async function resizeImage(originalImage, imageOptions) {
|
|
169
|
-
const { w: resizeWidth, h: resizeHeight, x: focalX = IMAGE_FOCAL_X, y: focalY = IMAGE_FOCAL_Y } = imageOptions;
|
|
170
|
-
const defaultResizeOptions = () => {
|
|
171
|
-
return originalImage.resize({
|
|
172
|
-
width: resizeWidth,
|
|
173
|
-
height: resizeHeight ? resizeHeight : void 0,
|
|
174
|
-
fit: sharp.fit.cover,
|
|
175
|
-
position: sharp.strategy.attention,
|
|
176
|
-
withoutEnlargement: true
|
|
177
|
-
});
|
|
178
|
-
};
|
|
179
|
-
if (resizeHeight && (focalX !== IMAGE_FOCAL_X || focalY !== IMAGE_FOCAL_Y)) {
|
|
180
|
-
const { width: originalWidth, height: originalHeight } = await originalImage.metadata();
|
|
181
|
-
if (originalWidth && originalHeight) {
|
|
182
|
-
const resizeAspectRatio = resizeWidth / resizeHeight;
|
|
183
|
-
const originalAspectRatio = originalWidth / originalHeight;
|
|
184
|
-
const prioritizeHeight = resizeAspectRatio < originalAspectRatio;
|
|
185
|
-
const imageToResize = originalImage.clone();
|
|
186
|
-
const scaledImage = imageToResize.resize(prioritizeHeight ? {
|
|
187
|
-
height: resizeHeight,
|
|
188
|
-
fit: sharp.fit.cover
|
|
189
|
-
} : {
|
|
190
|
-
width: resizeWidth,
|
|
191
|
-
fit: sharp.fit.cover
|
|
192
|
-
});
|
|
193
|
-
const { info: scaledImageInfo } = await scaledImage.toBuffer({ resolveWithObject: true });
|
|
194
|
-
const extractWidth = resizeWidth ?? scaledImageInfo.width;
|
|
195
|
-
const maxOffsetX = scaledImageInfo.width - extractWidth;
|
|
196
|
-
const leftFocalEdge = Math.round(
|
|
197
|
-
scaledImageInfo.width * (focalX / 100) - extractWidth / 2
|
|
198
|
-
);
|
|
199
|
-
const extractX = Math.min(Math.max(0, leftFocalEdge), maxOffsetX);
|
|
200
|
-
const extractHeight = resizeHeight ?? scaledImageInfo.height;
|
|
201
|
-
const maxOffsetY = scaledImageInfo.height - extractHeight;
|
|
202
|
-
const topFocalEdge = Math.round(
|
|
203
|
-
scaledImageInfo.height * (focalY / 100) - extractHeight / 2
|
|
204
|
-
);
|
|
205
|
-
const extractY = Math.min(Math.max(0, topFocalEdge), maxOffsetY);
|
|
206
|
-
return scaledImage.extract({
|
|
207
|
-
left: extractX,
|
|
208
|
-
top: extractY,
|
|
209
|
-
width: extractWidth,
|
|
210
|
-
height: extractHeight
|
|
211
|
-
});
|
|
212
|
-
} else {
|
|
213
|
-
return defaultResizeOptions();
|
|
214
|
-
}
|
|
215
|
-
} else {
|
|
216
|
-
return defaultResizeOptions();
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
function getOriginalImage(url, domains, headers) {
|
|
220
|
-
return new Promise((resolve, reject) => {
|
|
221
|
-
if (url.indexOf("http") === 0) {
|
|
222
|
-
if (isInvalidDomain(url, domains)) {
|
|
223
|
-
return reject({ status: 401, message: "invalid origin" });
|
|
224
|
-
}
|
|
225
|
-
fetch(url, {
|
|
226
|
-
method: "GET",
|
|
227
|
-
mode: "cors",
|
|
228
|
-
headers: {
|
|
229
|
-
"Access-Control-Allow-Origin": "*"
|
|
230
|
-
}
|
|
231
|
-
}).then((response) => {
|
|
232
|
-
if (!response.ok) {
|
|
233
|
-
return reject({ status: response.status, message: response.statusText });
|
|
234
|
-
}
|
|
235
|
-
response.arrayBuffer().then((buffer) => {
|
|
236
|
-
return resolve(Buffer.from(buffer));
|
|
237
|
-
}).catch((error) => {
|
|
238
|
-
return reject(error);
|
|
239
|
-
});
|
|
240
|
-
}).catch((error) => {
|
|
241
|
-
return reject(error);
|
|
242
|
-
});
|
|
243
|
-
} else {
|
|
244
|
-
const filePath = path.join(process.cwd(), "public", url);
|
|
245
|
-
fs.readFile(filePath, (error, data) => {
|
|
246
|
-
if (error) {
|
|
247
|
-
return reject(error);
|
|
248
|
-
}
|
|
249
|
-
return resolve(data);
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
function getCachedImage(pathname) {
|
|
255
|
-
return new Promise((resolve, reject) => {
|
|
256
|
-
fs.readFile(pathname, (error, data) => {
|
|
257
|
-
if (error) {
|
|
258
|
-
return reject(error);
|
|
259
|
-
}
|
|
260
|
-
return resolve(data);
|
|
261
|
-
});
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
function urlToFileName(url) {
|
|
265
|
-
const segments = url.split("?");
|
|
266
|
-
const path2 = segments[0];
|
|
267
|
-
const query = segments[1];
|
|
268
|
-
let uniqueName = path2.replace("://", "_").replace(/\.|\/|\?|=/g, "_");
|
|
269
|
-
uniqueName = uniqueName.substring(0, uniqueName.lastIndexOf("_")) + (query ? "_" + query.replace(/\.|\/|\?|=/g, "_") : "") + "." + uniqueName.substring(uniqueName.lastIndexOf("_") + 1, uniqueName.length);
|
|
270
|
-
return uniqueName;
|
|
271
|
-
}
|
|
272
|
-
function isVercel() {
|
|
273
|
-
return process && process.env && String(process.env.VERCEL) === "1";
|
|
274
|
-
}
|
|
275
|
-
function urlToCachedName(options) {
|
|
276
|
-
const fileName = urlToFileName(options.url);
|
|
277
|
-
const parsedName = path.parse(fileName);
|
|
278
|
-
const cacheDir = isVercel() ? path.join("/tmp", ".cache") : path.join(process.cwd(), ".cache");
|
|
279
|
-
if (!fs.existsSync(cacheDir)) {
|
|
280
|
-
fs.mkdirSync(cacheDir);
|
|
281
|
-
}
|
|
282
|
-
const cachedName = options.h ? path.join(cacheDir, `${parsedName.name}_w_${options.w}_h_${options.h || 0}_x_${options.x || IMAGE_FOCAL_X}_y_${options.y || IMAGE_FOCAL_Y}_q_${options.q}${parsedName.ext}`) : path.join(cacheDir, `${parsedName.name}_w_${options.w}_q_${options.q}${parsedName.ext}`);
|
|
283
|
-
return cachedName;
|
|
284
|
-
}
|
|
285
|
-
function isInvalidDomain(src, domains) {
|
|
286
|
-
if (IMAGE_STRATEGY === ImageStrategy.Token) {
|
|
287
|
-
return false;
|
|
288
|
-
}
|
|
289
|
-
const url = new URL(src);
|
|
290
|
-
return !domains.includes(url.hostname);
|
|
291
|
-
}
|
|
292
|
-
export {
|
|
293
|
-
imageHandler
|
|
294
|
-
};
|