imgproxyjs
Version:
ImgProxy javascript client for node/browser
519 lines (514 loc) • 14.6 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
ImgProxy: () => ImgProxy
});
module.exports = __toCommonJS(src_exports);
// src/lib/imgproxy.ts
var import_buffer = require("buffer");
var import_crypto = require("crypto");
// src/lib/transformer.ts
var Transformers = class {
isObject(val) {
if (!val || typeof val !== "object") {
throw new Error("Need to be an object param");
}
}
stringify(option) {
return option.map((o) => o ?? "").join(":");
}
tresize(val) {
this.isObject(val);
const { resizing_type, width, height, enlarge, extend } = val ?? {};
return this.stringify([resizing_type, width, height, enlarge, extend]);
}
tsize(val) {
this.isObject(val);
const { width, height, enlarge, extend } = val ?? {};
return this.stringify([width, height, enlarge, extend]);
}
textend(val) {
this.isObject(val);
const { extend, gravity, x_offset, y_offset } = val ?? {};
return this.stringify([extend, gravity, x_offset, y_offset]);
}
textendAspectRatio(val) {
this.isObject(val);
const { extend, gravity, x_offset, y_offset } = val ?? {};
return this.stringify([extend, gravity, x_offset, y_offset]);
}
tgravity(val) {
this.isObject(val);
const { gravity_type, x_offset, y_offset } = val ?? {};
return this.stringify([gravity_type, x_offset, y_offset]);
}
tcrop(val) {
this.isObject(val);
const { width, height, gravity, x_offset, y_offset } = val ?? {};
return this.stringify([width, height, gravity, x_offset, y_offset]);
}
ttrim(val) {
this.isObject(val);
const { threshold, color, equal_hor, equal_ver } = val ?? {};
return this.stringify([threshold, color, equal_hor, equal_ver]);
}
tpadding(val) {
this.isObject(val);
const { top, right, bottom, left } = val ?? {};
return this.stringify([top, right, bottom, left]);
}
tbackground(val) {
if (typeof val === "object" && "r" in val && "g" in val && "b" in val) {
return `${val.r}:${val.g}:${val.b}`;
}
return val?.replace?.("#", "");
}
tadjust(val) {
this.isObject(val);
const { brightness, contrast, saturation } = val ?? {};
return this.stringify([brightness, contrast, saturation]);
}
tunsharpMasking(val) {
this.isObject(val);
const { mode, weight, divider } = val ?? {};
return this.stringify([mode, weight, divider]);
}
tblurDetections(val) {
this.isObject(val);
const { sigma, classNames } = val ?? {};
return this.stringify([sigma, ...classNames ?? []]);
}
tdrawDetections(val) {
this.isObject(val);
const { draw, classNames } = val ?? {};
return this.stringify([draw, ...classNames ?? []]);
}
tgradient(val) {
this.isObject(val);
const { opacity, color, direction, start, stop } = val ?? {};
return this.stringify([opacity, color, direction, start, stop]);
}
tskipProcessing(val) {
return this.stringify([...val ?? []]);
}
tpreset(val) {
return this.stringify([...val ?? []]);
}
twatermark(val) {
this.isObject(val);
const { opacity, position, x_offset, y_offset, scale } = val ?? {};
return this.stringify([opacity, position, x_offset, y_offset, scale]);
}
tformatQuality(val) {
this.isObject(val);
const options = val ?? {};
return this.stringify(Object.entries(options).flat());
}
tjpegOptions(val) {
this.isObject(val);
const { progressive, no_subsample, trellis_quant, overshoot_deringing, optimize_scans, quant_table } = val ?? {};
return this.stringify([progressive, no_subsample, trellis_quant, overshoot_deringing, optimize_scans, quant_table]);
}
tpngOptions(val) {
this.isObject(val);
const { png_interlaced, png_quantize, png_quantization_colors } = val ?? {};
return this.stringify([png_interlaced, png_quantize, png_quantization_colors]);
}
tgifOptions(val) {
this.isObject(val);
const { gif_optimize_frames, gif_optimize_transparency } = val ?? {};
return this.stringify([gif_optimize_frames, gif_optimize_transparency]);
}
zoomOptions(val) {
this.isObject(val);
const { zoom_x_y, zoom_x, zoom_y } = val ?? {};
if (zoom_x_y !== void 0) {
return this.stringify([zoom_x_y]);
} else if (zoom_x !== void 0 && zoom_y !== void 0) {
return this.stringify([zoom_x, zoom_y]);
}
return this.stringify([1]);
}
};
// src/lib/imgproxy.ts
var ImgProxy = class _ImgProxy extends Transformers {
options = {
config: {
url: "",
autoreset: true
},
defaultOpts: {},
settings: {}
};
abbreviations = {
resize: "rs",
size: "size",
resizing_type: "rt",
resizing_algorithm: "ra",
width: "w",
height: "h",
min_width: "mw",
min_height: "mh",
zoom: "z",
enlarge: "el",
extend: "ex",
extend_aspect_ratio: "exar",
gravity: "g",
crop: "c",
padding: "pd",
trim: "t",
quality: "q",
max_bytes: "mb",
background: "bg",
adjust: "a",
brightness: "br",
contrast: "co",
saturation: "sa",
blur: "bl",
sharpen: "sh",
pixelate: "pix",
unsharpening: "ush",
watermark: "wm",
watermark_url: "wmu",
video_thumbnail_second: "vts",
style: "st",
jpeg_options: "jpgo",
png_options: "pngo",
gif_options: "gifo",
webp_options: "webpo",
preset: "pr",
cachebuster: "cb",
strip_metadata: "sm",
strip_color_profile: "scp",
unsharp_masking: "ush",
blur_detections: "bd",
auto_rotate: "ar",
rotate: "rot",
filename: "fn",
format: "ext",
enforce_thumbnail: "eth",
format_quality: "fq",
skip_processing: "skp",
expires: "exp",
return_attachment: "att",
max_src_resolution: "msr",
max_src_file_size: "msfs",
max_animation_frames: "maf",
max_animation_frame_resolution: "mafr",
fallback_image_url: "fiu"
};
transformers = {
resize: this.tresize,
size: this.tsize,
extend: this.textend,
extend_aspect_ratio: this.textendAspectRatio,
gravity: this.tgravity,
crop: this.tcrop,
padding: this.tpadding,
background: this.tbackground,
trim: this.ttrim,
adjust: this.tadjust,
watermark: this.twatermark,
jpeg_options: this.tjpegOptions,
png_options: this.tpngOptions,
gif_options: this.tgifOptions,
unsharp_masking: this.tunsharpMasking,
blur_detections: this.tblurDetections,
draw_detections: this.tdrawDetections,
skip_processing: this.tskipProcessing,
zoom: this.zoomOptions,
gradient: this.tgradient
};
constructor({ url, key, salt, autoreset }, options = {}) {
super();
this.options.config = { key, salt, url, autoreset: autoreset !== true ? !!autoreset : true };
this.isObject(options);
for (const key2 in options) {
this.setOption(key2, options[key2]);
}
}
setAutoreset(autoreset) {
this.options.config.autoreset = autoreset;
return this;
}
setOption(option, value) {
if (value === null) {
return this.resetOption(option);
}
this.options.settings[option] = `${this.abbreviations?.[option] ?? option}:${this.transformers?.[option]?.call?.(this, value) ?? value}`;
return this;
}
setOptions(options) {
this.isObject(options);
for (const key in options) {
this.setOption(key, options[key]);
}
}
setDefaultOptions(options) {
this.isObject(options);
this.options.defaultOpts = options;
this.setOptions(options);
return this;
}
resetDefaultOptions() {
this.options.defaultOpts = {};
return this;
}
resetOptions() {
this.options.settings = {};
this.setOptions(this.options.defaultOpts);
return this;
}
resetOption(option) {
delete this.options.settings?.[this.abbreviations?.[option] ?? option];
return this;
}
resize(val) {
return this.setOption("resize", val);
}
crop(val) {
return this.setOption("crop", val);
}
size(val) {
return this.setOption("size", val);
}
fallbackImageUrl(val) {
return this.setOption("fallback_image_url", val);
}
skipProcessing(val) {
return this.setOption("skip_processing", val);
}
expires(val) {
return this.setOption("expires", val);
}
extend(val) {
return this.setOption("extend", val);
}
trim(val) {
return this.setOption("trim", val);
}
adjust(val) {
return this.setOption("adjust", val);
}
maxSrcResolution(val) {
return this.setOption("max_src_resolution", `${val}`);
}
maxSrcFileSize(val) {
return this.setOption("max_src_file_size", `${val}`);
}
maxAnimationFrames(val) {
return this.setOption("max_animation_frames", `${val}`);
}
maxAnimationFramesResolution(val) {
return this.setOption("max_animation_frame_resolution", `${val}`);
}
resizingType(val) {
return this.setOption("resizing_type", val);
}
enforceThumbnail(val) {
return this.setOption("enforce_thumbnail", `${val}`);
}
formatQuality(val) {
return this.setOption("format_quality", val);
}
resizingAlgorithm(val) {
return this.setOption("resizing_algorithm", val);
}
width(width) {
return this.setOption("width", `${width}`);
}
height(height) {
return this.setOption("height", `${height}`);
}
minWidth(minWidth) {
return this.setOption("min_width", `${minWidth}`);
}
minHeight(minHeight) {
return this.setOption("min_height", `${minHeight}`);
}
dpr(val) {
if (Number(val) > 0) {
return this.setOption("dpr", `${val}`);
}
return this;
}
dpi(val) {
if (Number(val) > 0) {
return this.setOption("dpi", `${val}`);
}
return this;
}
gradient(val) {
if (Number(val) > 0) {
return this.setOption("gradient", val);
}
return this;
}
maxBytes(val) {
return this.setOption("max_bytes", `${val}`);
}
padding(val) {
return this.setOption("padding", val);
}
enlarge(val) {
return this.setOption("enlarge", `${val}`);
}
pixelate(val) {
return this.setOption("pixelate", `${val}`);
}
gravity(val) {
return this.setOption("gravity", val);
}
quality(quality) {
return this.setOption("quality", `${quality}`);
}
background(color) {
return this.setOption("background", color);
}
backgroundAlpha(val) {
return this.setOption("background_alpha", `${val}`);
}
blur(val) {
return this.setOption("blur", `${val}`);
}
blurDetections(val) {
return this.setOption("blur_detections", val);
}
unsharpMasking(val) {
return this.setOption("unsharp_masking", val);
}
drawDetections(val) {
return this.setOption("draw_detections", val);
}
raw(val) {
return this.setOption("raw", `${val}`);
}
returnAttachment(val) {
return this.setOption("return_attachment", `${val}`);
}
saturation(val) {
return this.setOption("saturation", `${val}`);
}
contrast(val) {
return this.setOption("contrast", `${val}`);
}
brightness(val) {
return this.setOption("brightness", `${val}`);
}
sharpen(val) {
return this.setOption("sharpen", `${val}`);
}
watermark(val) {
return this.setOption("watermark", val);
}
watermarkUrl(val) {
return this.setOption("watermark_url", val);
}
preset(val) {
return this.setOption("preset", val);
}
cacheBuster(val) {
return this.setOption("cachebuster", val);
}
format(val) {
return this.setOption("format", val);
}
filename(val) {
return this.setOption("filename", val);
}
rotate(val) {
return this.setOption("rotate", val);
}
autoRotate(val) {
return this.setOption("auto_rotate", val);
}
style(val) {
return this.setOption("style", val);
}
page(val) {
return this.setOption("page", `${val}`);
}
zoom(val) {
return this.setOption("zoom", val);
}
videoThumbnailSecond(val) {
return this.setOption("video_thumbnail_second", `${val}`);
}
webpOptions(val) {
return this.setOption("webp_options", `${val}`);
}
stripMetadata(val) {
return this.setOption("strip_metadata", `${val}`);
}
keepCopyright(val) {
return this.setOption("keep_copyright", `${val}`);
}
stripColorProfile(val) {
return this.setOption("strip_color_profile", `${val}`);
}
gifOptions(val) {
return this.setOption("gif_options", val);
}
pngOptions(val) {
return this.setOption("png_options", val);
}
sign(target) {
const { key, salt } = this.options?.config ?? {};
if (!key || !salt) {
throw Error("Missing required params: key, salt");
}
const hexKey = _ImgProxy.hexDecode(key);
const hexSalt = _ImgProxy.hexDecode(salt);
const hmac = (0, import_crypto.createHmac)("sha256", hexKey);
hmac.update(hexSalt);
hmac.update(target);
return _ImgProxy.urlSafeBase64(hmac.digest());
}
static hexDecode(hex) {
return import_buffer.Buffer.from(hex, "hex");
}
static urlSafeBase64(string) {
return import_buffer.Buffer.from(string).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
}
get(originalImage) {
const { settings, config } = this.options;
if (!originalImage) {
throw Error("Missing required param: image");
}
const encoded_url = _ImgProxy.urlSafeBase64(originalImage);
const options = Object.values(settings).join("/");
const path = options ? `/${options}/${encoded_url}` : `/${encoded_url}`;
let url;
if (config.key && config.salt) {
url = `${config.url}/${this.sign(path)}${path}`;
} else {
url = `${config.url}/insecure${path}`;
}
if (this.options.config.autoreset) {
this.resetOptions();
}
return url;
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ImgProxy
});