UNPKG

@blocklet/images

Version:

support functions for blocklet image validation

54 lines (53 loc) 2.78 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateLogo = void 0; const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const image_size_1 = __importDefault(require("image-size")); const image_type_1 = __importDefault(require("image-type")); const is_svg_1 = __importDefault(require("is-svg")); const ASPECT_RATIO = 1 / 1; const ASPECT_RATIO_THRESHOLD = 0.01; const validateLogo = (logoName, options) => { const { extractedFilepath, maxSize = 1024, minWidth = 256 } = options; const logoType = options.logoType || ['png', 'jpg', 'webp', 'svg']; const logoPath = path_1.default.join(extractedFilepath, logoName); const preLogoMessage = `The logo(${logoName})`; const errorMessages = []; if (!logoName) { errorMessages.push('The logo field is required in blocklet.yml.'); return errorMessages; } if (!fs_1.default.existsSync(logoPath)) { errorMessages.push(`${preLogoMessage} file not found.`); return errorMessages; } const logoStats = fs_1.default.statSync(logoPath); if (maxSize && logoStats.size > maxSize * 1024) { errorMessages.push(`${preLogoMessage} size exceeds ${maxSize} KB, but got ${(logoStats.size / 1024).toFixed(2)} KB.`); } const isSvgFile = (0, is_svg_1.default)(fs_1.default.readFileSync(logoPath)); if (!isSvgFile) { const imgType = (0, image_type_1.default)(fs_1.default.readFileSync(logoPath)); if (!imgType || !logoType.includes(imgType.ext)) { errorMessages.push(`${preLogoMessage} format is not supported, expected: [${logoType}].`); } const logoExt = path_1.default.extname(logoPath); if (`.${imgType?.ext}` !== logoExt && logoExt !== '.jpeg') { errorMessages.push(`${preLogoMessage} extension is not match the real file extension [.${imgType?.ext}].`); } const logoMeta = (0, image_size_1.default)(logoPath); const aspectRatio = logoMeta.width / logoMeta.height; if (logoMeta.width < minWidth || logoMeta.height < minWidth) { errorMessages.push(`${preLogoMessage} minimum size must be ${minWidth}x${minWidth}, but got ${logoMeta.width}x${logoMeta.height}.`); } if (Math.abs(aspectRatio - ASPECT_RATIO) > ASPECT_RATIO_THRESHOLD) { errorMessages.push(`${preLogoMessage} aspect ratio must be approximately 1:1, but got 1:${parseFloat((logoMeta.height / logoMeta.width).toFixed(2))} (${logoMeta.width}x${logoMeta.height}).`); } } return errorMessages; }; exports.validateLogo = validateLogo;