UNPKG

crapifyme

Version:

Ultra-fast developer productivity CLI tools - remove comments, logs, and more

120 lines 4.64 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Base64Processor = void 0; const promises_1 = __importDefault(require("fs/promises")); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const mime_types_1 = require("mime-types"); const types_1 = require("./types"); class Base64Processor { constructor(logger) { this.logger = logger; } async encodeFile(filePath, options) { const absolutePath = path_1.default.resolve(filePath); if (!fs_1.default.existsSync(absolutePath)) { throw new Error(`File not found: ${filePath}`); } const ext = path_1.default.extname(absolutePath).slice(1).toLowerCase(); if (!(0, types_1.isSupportedImageExtension)(ext)) { throw new Error(`Unsupported file format: .${ext}. Supported formats: png, jpg, jpeg, svg, gif, webp, bmp, ico, tiff, avif`); } const fileBuffer = await promises_1.default.readFile(absolutePath); const originalSize = fileBuffer.length; const mimeType = (0, mime_types_1.lookup)(absolutePath) || `image/${ext === 'svg' ? 'svg+xml' : ext}`; const rawBase64 = fileBuffer.toString('base64'); const base64Size = rawBase64.length; const dataUrl = `data:${mimeType};base64,${rawBase64}`; const cssBackgroundImage = `background-image: url("${dataUrl}");`; const overhead = ((base64Size - originalSize) / originalSize) * 100; return { dataUrl, cssBackgroundImage, rawBase64, originalSize, base64Size, mimeType, overhead }; } async decodeBase64(input, outputPath) { let base64Data; let mimeType; let detectedFormat; if (input.startsWith('data:')) { const match = input.match(/^data:([^;]+);base64,(.+)$/); if (!match) { throw new Error('Invalid data URL format'); } mimeType = match[1]; base64Data = match[2]; if (mimeType.startsWith('image/')) { detectedFormat = mimeType.split('/')[1]; if (detectedFormat === 'svg+xml') detectedFormat = 'svg'; } } else { base64Data = input; } if (!this.isValidBase64(base64Data)) { throw new Error('Invalid base64 string'); } const buffer = Buffer.from(base64Data, 'base64'); const decodedSize = buffer.length; let finalOutputPath; if (outputPath) { finalOutputPath = path_1.default.resolve(outputPath); } else { const timestamp = Date.now(); const extension = detectedFormat || 'bin'; finalOutputPath = path_1.default.resolve(`decoded_${timestamp}.${extension}`); } const outputDir = path_1.default.dirname(finalOutputPath); await promises_1.default.mkdir(outputDir, { recursive: true }); await promises_1.default.writeFile(finalOutputPath, buffer); return { outputPath: finalOutputPath, originalSize: base64Data.length, decodedSize, mimeType, detectedFormat }; } isValidBase64(str) { try { return Buffer.from(str, 'base64').toString('base64') === str; } catch { return false; } } formatSize(bytes) { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`; } validateFilePath(filePath) { const absolutePath = path_1.default.resolve(filePath); if (!fs_1.default.existsSync(absolutePath)) { throw new Error(`File not found: ${filePath}`); } const stats = fs_1.default.statSync(absolutePath); if (!stats.isFile()) { throw new Error(`Path is not a file: ${filePath}`); } const maxSize = 100 * 1024 * 1024; if (stats.size > maxSize) { throw new Error(`File too large (${this.formatSize(stats.size)}). Maximum size is ${this.formatSize(maxSize)}.`); } } } exports.Base64Processor = Base64Processor; //# sourceMappingURL=logic.js.map