UNPKG

anitimejs

Version:

Thư viện xử lý chuỗi số và thời gian trong JavaScript/Typescript

250 lines (249 loc) 8.99 kB
"use strict"; // regex.ts Object.defineProperty(exports, "__esModule", { value: true }); exports.RegexHelper = exports.RegexHelperClass = void 0; /** * Class chính xử lý các hàm regex và mã hóa */ class RegexHelperClass { /** * Thực hiện validation theo loại * @param type Loại validation * @param value Giá trị cần kiểm tra * @param options Tùy chọn (cho password) * @returns true nếu hợp lệ, false nếu không */ validate(type, value, options) { switch (type) { case "email": return this.validateEmail(value); case "password": const passwordOptions = options || {}; return this.validatePassword(value, { minLength: passwordOptions.minLength || 8, requireUppercase: passwordOptions.requireUppercase !== false, requireLowercase: passwordOptions.requireLowercase !== false, requireNumbers: passwordOptions.requireNumbers !== false, requireSpecial: passwordOptions.requireSpecial !== false, }); case "phone": const country = typeof options === "string" ? options : "VN"; return this.validatePhone(value, country); case "url": return this.validateUrl(value); default: return false; } } /** * Thực hiện ẩn thông tin theo loại * @param type Loại ẩn thông tin * @param value Giá trị cần ẩn * @param options Tùy chọn bổ sung * @returns Chuỗi đã được ẩn thông tin */ mask(type, value, options) { switch (type) { case "email": return this.maskEmail(value); case "phone": return this.maskPhone(value, options || 2); case "card": return this.maskCard(value, options || 4); default: return value; } } /** * Xử lý chuỗi theo loại * @param type Loại xử lý * @param value Chuỗi cần xử lý * @returns Kết quả xử lý */ process(type, value) { switch (type) { case "stripHtml": return this.stripHtml(value); case "extractUrls": return this.extractUrls(value); case "parseUrl": return this.parseUrl(value); default: return value; } } /** * Thực hiện mã hóa/băm theo loại * @param type Loại mã hóa * @param value Chuỗi cần mã hóa * @param key Khóa mã hóa (cho encrypt/decrypt) * @returns Kết quả mã hóa */ crypto(type, value, key) { switch (type) { case "hash": return this.simpleHash(value); case "encrypt": if (!key) throw new Error("Key is required for encryption"); return this.simpleEncrypt(value, key); case "decrypt": if (!key) throw new Error("Key is required for decryption"); return this.simpleDecrypt(value, key); default: return value; } } /** * Các hàm private bên dưới */ validateEmail(email) { const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; return regex.test(email); } validatePassword(password, options) { if (password.length < options.minLength) return false; if (options.requireUppercase && !/[A-Z]/.test(password)) return false; if (options.requireLowercase && !/[a-z]/.test(password)) return false; if (options.requireNumbers && !/[0-9]/.test(password)) return false; if (options.requireSpecial && !/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) return false; return true; } validatePhone(phone, country = "VN") { // Loại bỏ các ký tự không phải số const digits = phone.replace(/\D/g, ""); switch (country) { case "VN": // Số điện thoại Việt Nam: 10 chữ số, bắt đầu bằng 0 hoặc +84 return /^(0|84|\+84)(\d{9})$/.test(phone); case "US": // Số điện thoại Mỹ: 10 chữ số, có thể bắt đầu bằng +1 return /^(\+?1)?[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$/.test(phone); case "INT": // Số điện thoại quốc tế: ít nhất 8 chữ số return digits.length >= 8; default: return false; } } validateUrl(url) { try { new URL(url); return true; } catch (_a) { return false; } } stripHtml(html) { return html.replace(/<[^>]*>/g, ""); } extractUrls(text) { const urlRegex = /(https?:\/\/[^\s]+)/g; return text.match(urlRegex) || []; } parseUrl(url) { try { const parsedUrl = new URL(url); const params = {}; // Phân tích query parameters parsedUrl.searchParams.forEach((value, key) => { params[key] = value; }); return { protocol: parsedUrl.protocol, host: parsedUrl.host, hostname: parsedUrl.hostname, port: parsedUrl.port, pathname: parsedUrl.pathname, search: parsedUrl.search, hash: parsedUrl.hash, params, }; } catch (error) { throw new Error(`Invalid URL: ${url}`); } } maskEmail(email) { if (!email || typeof email !== "string") return ""; const [localPart, domain] = email.split("@"); if (!domain) return email; // Không phải email hợp lệ const [domainName, extension] = domain.split("."); if (!extension) return email; // Không phải email hợp lệ // Giữ ký tự đầu tiên của local part, còn lại thay bằng * const maskedLocalPart = localPart.charAt(0) + "*".repeat(localPart.length - 1); // Thay thế domain name bằng *** const maskedDomain = "*".repeat(3); return `${maskedLocalPart}@${maskedDomain}.${extension}`; } maskPhone(phone, visibleDigits = 2) { if (!phone || typeof phone !== "string") return ""; // Loại bỏ các ký tự không phải số const digits = phone.replace(/\D/g, ""); if (digits.length <= visibleDigits * 2) return phone; const prefix = digits.slice(0, visibleDigits); const suffix = digits.slice(-visibleDigits); const masked = "*".repeat(digits.length - visibleDigits * 2); return `${prefix}${masked}${suffix}`; } maskCard(cardNumber, visibleDigits = 4) { if (!cardNumber || typeof cardNumber !== "string") return ""; // Loại bỏ các ký tự không phải số const digits = cardNumber.replace(/\D/g, ""); if (digits.length <= visibleDigits * 2) return cardNumber; const prefix = digits.slice(0, visibleDigits); const suffix = digits.slice(-visibleDigits); const masked = "*".repeat(digits.length - visibleDigits * 2); return `${prefix}${masked}${suffix}`; } simpleHash(input) { let hash = 0; if (!input.length) return hash.toString(16); for (let i = 0; i < input.length; i++) { const char = input.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; // Convert to 32bit integer } return Math.abs(hash).toString(16); } simpleEncrypt(input, key) { const result = []; for (let i = 0; i < input.length; i++) { const charCode = input.charCodeAt(i) ^ key.charCodeAt(i % key.length); result.push(String.fromCharCode(charCode)); } return btoa(result.join("")); } simpleDecrypt(encrypted, key) { try { const encryptedText = atob(encrypted); const result = []; for (let i = 0; i < encryptedText.length; i++) { const charCode = encryptedText.charCodeAt(i) ^ key.charCodeAt(i % key.length); result.push(String.fromCharCode(charCode)); } return result.join(""); } catch (e) { return ""; } } } exports.RegexHelperClass = RegexHelperClass; exports.RegexHelper = new RegexHelperClass();