js-use-core
Version:
JavaScript Comprehensive tool library, including full screen, copy and paste functions
2 lines (1 loc) • 26.1 kB
JavaScript
"use strict";class EventEmitter{constructor(){this.events=new Map,this.maxListeners=10}on(e,t,r){if("function"!=typeof t)throw new Error("Listener must be a function");const i={listener:t,once:r?.once||!1,priority:r?.priority||0};this.events.has(e)||this.events.set(e,[]);const s=this.events.get(e);s.length,this.maxListeners;let o=!1;for(let e=0;e<s.length;e++)if(i.priority>(s[e].priority||0)){s.splice(e,0,i),o=!0;break}return o||s.push(i),this}once(e,t,r){return this.on(e,t,{once:!0,priority:r})}off(e,t){if(!this.events.has(e))return this;const r=this.events.get(e);if(t){const i=r.findIndex(e=>e.listener===t);-1!==i&&(r.splice(i,1),0===r.length&&this.events.delete(e))}else this.events.delete(e);return this}emit(e,...t){if(!this.events.has(e))return!1;const r=this.events.get(e).slice(),i=[];for(const e of r)try{e.listener.apply(this,t),e.once&&i.push(e)}catch(e){}if(i.length>0){const t=this.events.get(e);if(t){for(const e of i){const r=t.indexOf(e);-1!==r&&t.splice(r,1)}0===t.length&&this.events.delete(e)}}return!0}listenerCount(e){return this.events.get(e)?.length||0}listeners(e){return this.events.get(e)?.map(e=>e.listener)||[]}eventNames(){return Array.from(this.events.keys())}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}setMaxListeners(e){if(e<0||!Number.isInteger(e))throw new Error("Max listeners must be a non-negative integer");return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}prependListener(e,t){return this.on(e,t,{priority:Number.MAX_SAFE_INTEGER})}prependOnceListener(e,t){return this.once(e,t,Number.MAX_SAFE_INTEGER)}}var e,t,r,i,s,o,n,a,l,c,h;!function(e){e.USER_ERROR="USER_ERROR",e.SYSTEM_ERROR="SYSTEM_ERROR",e.NETWORK_ERROR="NETWORK_ERROR",e.PERMISSION_ERROR="PERMISSION_ERROR",e.CONFIG_ERROR="CONFIG_ERROR",e.VALIDATION_ERROR="VALIDATION_ERROR",e.TIMEOUT_ERROR="TIMEOUT_ERROR",e.UNSUPPORTED_ERROR="UNSUPPORTED_ERROR",e.INTERNAL_ERROR="INTERNAL_ERROR",e.EXTERNAL_ERROR="EXTERNAL_ERROR",e.UNKNOWN_ERROR="UNKNOWN_ERROR"}(e||(e={})),function(e){e.LOW="low",e.MEDIUM="medium",e.HIGH="high",e.CRITICAL="critical"}(t||(t={})),function(e){e.USER_ERROR="USER_ERROR",e.SYSTEM_ERROR="SYSTEM_ERROR",e.NETWORK_ERROR="NETWORK_ERROR",e.PERMISSION_ERROR="PERMISSION_ERROR",e.CONFIG_ERROR="CONFIG_ERROR",e.TIMEOUT_ERROR="TIMEOUT_ERROR",e.VALIDATION_ERROR="VALIDATION_ERROR",e.INTERNAL_ERROR="INTERNAL_ERROR",e.UNKNOWN_ERROR="UNKNOWN_ERROR"}(r||(r={})),function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(i||(i={}));class Logger{constructor(e="Core",t){this.level=i.INFO,this.logs=[],this.maxLogs=1e3,this.enableConsole=!0,this.module=e,t&&(this.level=t.level??i.INFO,this.maxLogs=t.maxLogs??1e3,this.enableConsole=t.enableConsole??!0)}setLevel(e){this.level=e}getLevel(){return this.level}debug(e,t){this.log(i.DEBUG,e,t)}info(e,t){this.log(i.INFO,e,t)}warn(e,t){this.log(i.WARN,e,t)}error(e,t){this.log(i.ERROR,e,t)}log(e,t,r){if(e<this.level)return;const i={level:e,message:t,timestamp:Date.now(),module:this.module,data:r};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift(),this.enableConsole&&this.outputToConsole(i)}outputToConsole(e){new Date(e.timestamp).toISOString(),i[e.level],e.module,e.message,void 0!==e.data&&e.data;switch(e.level){case i.DEBUG:case i.INFO:case i.WARN:case i.ERROR:}}getLogs(){return[...this.logs]}getLogsByLevel(e){return this.logs.filter(t=>t.level===e)}getLogsByTimeRange(e,t){return this.logs.filter(r=>r.timestamp>=e&&r.timestamp<=t)}clear(){this.logs=[]}setMaxLogs(e){if(e<0)throw new Error("Max logs must be non-negative");this.maxLogs=e,this.logs.length>e&&(this.logs=this.logs.slice(-e))}setConsoleOutput(e){this.enableConsole=e}exportLogs(){return JSON.stringify(this.logs,null,2)}importLogs(e){try{const t=JSON.parse(e);Array.isArray(t)&&(this.logs=t.filter(e=>e&&"number"==typeof e.level&&"string"==typeof e.message&&"number"==typeof e.timestamp))}catch(e){this.error("Failed to import logs",e)}}createChild(e){return new Logger(`${this.module}.${e}`,{level:this.level,maxLogs:this.maxLogs,enableConsole:this.enableConsole})}}class u extends Error{constructor(e,t,r){super(t),this.name="CustomError",this.type=e,this.code=r?.code,this.context=r?.context,this.recoverable=r?.recoverable??!1,r?.cause&&(this.cause=r.cause),Error.captureStackTrace&&Error.captureStackTrace(this,u)}}class ErrorHandler{constructor(e){this.errorSolutions=new Map,this.logger=e||new Logger("ErrorHandler"),this.initializeErrorSolutions()}handleError(e,t){const r=this.classifyError(e),i={module:"Unknown",method:"Unknown",timestamp:Date.now(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"Node.js",...t},s={type:r,severity:this.getErrorSeverity(r),message:e.message,userMessage:this.getUserFriendlyMessage(e,r),originalError:e,context:i,code:this.getErrorCode(e)||this.generateErrorCode(r),recoverable:this.isRecoverableError(e),solutions:this.getErrorSolutions(e),id:this.generateErrorId(),processedAt:Date.now(),relatedErrors:[]};return this.logger.error(`[${r}] ${s.message}`,{error:e.message,stack:e.stack,context:i,recoverable:s.recoverable}),s}createError(e,t,r){const i={module:"Unknown",method:"Unknown",timestamp:Date.now(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"Node.js",...r?.context};return new u(e,t,{code:r?.code,context:i,recoverable:r?.recoverable,cause:r?.cause})}isRecoverableError(t){if(t instanceof u)return t.recoverable;switch(this.classifyError(t)){case e.NETWORK_ERROR:case e.TIMEOUT_ERROR:return!0;case e.PERMISSION_ERROR:case e.SYSTEM_ERROR:return!1;case e.USER_ERROR:case e.CONFIG_ERROR:return!0;default:return!1}}getErrorSolution(e){const t=this.getErrorCode(e);if(t&&this.errorSolutions.has(t))return this.errorSolutions.get(t);const r=this.classifyError(e);return this.getDefaultSolution(r)}getErrorSolutions(e){const t=this.getErrorSolution(e);return t?[{description:t,steps:[t],automatic:!1,priority:1}]:[]}getErrorSeverity(r){switch(r){case e.USER_ERROR:case e.CONFIG_ERROR:return t.LOW;case e.NETWORK_ERROR:case e.TIMEOUT_ERROR:return t.MEDIUM;case e.PERMISSION_ERROR:case e.VALIDATION_ERROR:return t.HIGH;case e.SYSTEM_ERROR:case e.INTERNAL_ERROR:return t.CRITICAL;default:return t.MEDIUM}}generateErrorCode(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).substr(2,5)}`.toUpperCase()}generateErrorId(){return`error_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}addErrorSolution(e,t){this.errorSolutions.set(e,t)}addErrorSolutions(e){for(const[t,r]of Object.entries(e))this.errorSolutions.set(t,r)}classifyError(t){if(t instanceof u)return t.type;const r=(t.message||"").toLowerCase(),i=(t.name||"").toLowerCase();return r.includes("network")||r.includes("fetch")||r.includes("xhr")||i.includes("networkerror")?e.NETWORK_ERROR:r.includes("timeout")||r.includes("timed out")||i.includes("timeouterror")?e.TIMEOUT_ERROR:r.includes("permission")||r.includes("denied")||r.includes("unauthorized")||r.includes("forbidden")||i.includes("notallowederror")?e.PERMISSION_ERROR:r.includes("not supported")||r.includes("not available")||r.includes("not implemented")||i.includes("notsupportederror")?e.SYSTEM_ERROR:r.includes("invalid")||r.includes("configuration")||r.includes("config")||i.includes("configerror")?e.CONFIG_ERROR:t instanceof TypeError||t instanceof RangeError||r.includes("invalid argument")||r.includes("invalid parameter")?e.USER_ERROR:e.UNKNOWN_ERROR}getUserFriendlyMessage(t,r){switch(r){case e.NETWORK_ERROR:return"网络连接失败,请检查网络连接后重试";case e.TIMEOUT_ERROR:return"操作超时,请稍后重试";case e.PERMISSION_ERROR:return"权限不足,请检查浏览器权限设置";case e.SYSTEM_ERROR:return"当前浏览器不支持此功能,请使用其他浏览器或升级浏览器版本";case e.CONFIG_ERROR:return"配置参数错误,请检查配置";case e.USER_ERROR:return"输入参数错误,请检查输入参数";default:return t.message||"发生未知错误"}}getErrorCode(e){if(e instanceof u)return e.code;const t=e;return t.code||t.errno||void 0}getDefaultSolution(t){switch(t){case e.NETWORK_ERROR:return"请检查网络连接,确保网络正常后重试";case e.TIMEOUT_ERROR:return"请稍后重试,或增加超时时间设置";case e.PERMISSION_ERROR:return"请在浏览器设置中允许相关权限,或使用HTTPS协议";case e.SYSTEM_ERROR:return"请使用支持此功能的现代浏览器,或升级浏览器版本";case e.CONFIG_ERROR:return"请检查配置参数是否正确,参考文档进行配置";case e.USER_ERROR:return"请检查输入参数的类型和格式是否正确";default:return null}}initializeErrorSolutions(){this.errorSolutions.set("ENOTFOUND","域名解析失败,请检查网络连接"),this.errorSolutions.set("ECONNREFUSED","连接被拒绝,请检查服务器状态"),this.errorSolutions.set("ETIMEDOUT","连接超时,请检查网络连接或稍后重试"),this.errorSolutions.set("CERT_UNTRUSTED","SSL证书不受信任,请检查证书配置"),this.errorSolutions.set("MIXED_CONTENT","混合内容错误,请使用HTTPS协议")}}class Cache{constructor(e){this.cache=new Map,this.config={maxSize:e?.maxSize??100,defaultTTL:e?.defaultTTL??3e5,enableLRU:e?.enableLRU??!0,cleanupInterval:e?.cleanupInterval??6e4},this.startCleanup()}set(e,t,r){const i=Date.now(),s={value:t,expireAt:i+(r??this.config.defaultTTL),createdAt:i,accessCount:0,lastAccessed:i};this.cache.size>=this.config.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,s)}get(e){const t=this.cache.get(e);if(!t)return;const r=Date.now();if(!(r>t.expireAt))return t.accessCount++,t.lastAccessed=r,t.value;this.cache.delete(e)}has(e){const t=this.cache.get(e);return!!t&&(!(Date.now()>t.expireAt)||(this.cache.delete(e),!1))}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}keys(){return Array.from(this.cache.keys())}getInfo(e){const t=this.cache.get(e);if(t){if(!(Date.now()>t.expireAt))return{...t};this.cache.delete(e)}}touch(e,t){const r=this.cache.get(e);if(!r)return!1;const i=Date.now();if(i>r.expireAt)return this.cache.delete(e),!1;const s=t??this.config.defaultTTL;return r.expireAt=i+s,r.lastAccessed=i,!0}async getOrSet(e,t,r){const i=this.get(e);if(void 0!==i)return i;const s=await t();return this.set(e,s,r),s}mset(e,t){for(const[r,i]of e)this.set(r,i,t)}mget(e){return e.map(e=>this.get(e))}mdel(e){let t=0;for(const r of e)this.delete(r)&&t++;return t}getStats(){let e=0,t=0;const r=Date.now();for(const[i,s]of this.cache.entries())e+=s.accessCount,r>s.expireAt&&t++;return{size:this.cache.size,maxSize:this.config.maxSize,hitRate:e>0?(e-t)/e:0,totalAccess:e,expiredCount:t}}cleanup(){const e=Date.now();let t=0;for(const[r,i]of this.cache.entries())e>i.expireAt&&(this.cache.delete(r),t++);return t}evictLRU(){if(!this.config.enableLRU||0===this.cache.size)return;let e=null,t=1/0;for(const[r,i]of this.cache.entries())i.lastAccessed<t&&(t=i.lastAccessed,e=r);e&&this.cache.delete(e)}startCleanup(){this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=setInterval(()=>{this.cleanup()},this.config.cleanupInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}updateConfig(e){if(this.config={...this.config,...e},void 0!==e.cleanupInterval&&this.startCleanup(),void 0!==e.maxSize&&this.cache.size>e.maxSize)for(;this.cache.size>e.maxSize;)this.evictLRU()}destroy(){this.stopCleanup(),this.clear()}}class BaseManager{constructor(e,t="BaseManager"){this.initialized=!1,this.destroyed=!1,this.options=this.mergeDefaultOptions(e),this.logger=new Logger(t,{level:this.options.debug?0:1,enableConsole:this.options.debug}),this.eventEmitter=new EventEmitter,this.errorHandler=new ErrorHandler(this.logger),this.options.cache&&(this.cache=new Cache),this.setupErrorHandling()}on(e,t,r){return this.eventEmitter.on(e,t,r),this}off(e,t){return this.eventEmitter.off(e,t),this}emit(e,...t){return this.eventEmitter.emit(e,...t)}once(e,t,r){return this.eventEmitter.once(e,t,r),this}listenerCount(e){return this.eventEmitter.listenerCount(e)}eventNames(){return this.eventEmitter.eventNames()}handleError(e,t){const r={module:this.constructor.name,method:t},i=this.errorHandler.handleError(e,r);return this.emit("error",i),i}validateInput(e,t){try{if(t.type){const r=typeof e;if(r!==t.type)throw this.errorHandler.createError("USER_ERROR",`Expected ${t.type}, got ${r}`,{context:{method:"validateInput"}})}if(t.required&&null==e)throw this.errorHandler.createError("USER_ERROR","Required parameter is missing",{context:{method:"validateInput"}});if(t.isArray&&!Array.isArray(e))throw this.errorHandler.createError("USER_ERROR","Expected array",{context:{method:"validateInput"}});if(t.properties&&"object"==typeof e&&null!==e)for(const[r,i]of Object.entries(t.properties))if(!this.validateInput(e[r],i))return!1;return!0}catch(e){return this.handleError(e,"validateInput"),!1}}async safeExecute(e,t,r){const i=r??this.options.retries??0;let s=null;for(let r=0;r<=i;r++)try{const i=new Promise((e,r)=>{setTimeout(()=>{r(this.errorHandler.createError("TIMEOUT_ERROR",`Operation timed out after ${this.options.timeout}ms`,{context:{method:t}}))},this.options.timeout)}),s=await Promise.race([e(),i]);return r>0&&this.logger.info(`Operation succeeded after ${r} retries`,{context:t}),s}catch(e){if(s=e,r===i||!this.errorHandler.isRecoverableError(s))throw this.handleError(s,t);const o=Math.min(1e3*Math.pow(2,r),5e3);this.logger.warn(`Operation failed, retrying in ${o}ms (attempt ${r+1}/${i+1})`,{context:t,error:s.message}),await new Promise(e=>setTimeout(e,o))}throw this.handleError(s,t)}getCached(e){return this.cache?.get(e)}setCached(e,t,r){this.cache?.set(e,t,r)}async getOrSetCached(e,t,r){return this.cache?this.cache.getOrSet(e,t,r):t()}ensureInitialized(){if(!this.initialized)throw this.errorHandler.createError("SYSTEM_ERROR","Manager not initialized. Call initialize() first.",{context:{method:"ensureInitialized"}})}ensureNotDestroyed(){if(this.destroyed)throw this.errorHandler.createError("SYSTEM_ERROR","Manager has been destroyed and cannot be used.",{context:{method:"ensureNotDestroyed"}})}getStatus(){return{initialized:this.initialized,destroyed:this.destroyed,eventListeners:this.eventNames().reduce((e,t)=>e+this.listenerCount(t),0),cacheSize:this.cache?.size()}}updateOptions(e){this.options={...this.options,...e},void 0!==e.debug&&(this.logger.setLevel(e.debug?0:1),this.logger.setConsoleOutput(e.debug)),this.emit("optionsUpdated",this.options)}mergeDefaultOptions(e){return{...this.getDefaultOptions(),...e}}setupErrorHandling(){"undefined"!=typeof window?window.addEventListener("unhandledrejection",e=>{this.handleError(new Error(e.reason),"unhandledrejection")}):"undefined"!=typeof process&&process.on("unhandledRejection",e=>{this.handleError(new Error(String(e)),"unhandledRejection")})}baseDestroy(){this.destroyed||(this.emit("beforeDestroy"),this.eventEmitter.removeAllListeners(),this.cache?.destroy(),this.logger.clear(),this.destroyed=!0,this.initialized=!1,this.emit("destroyed"))}}function d(e){if(!e||"string"!=typeof e)return!1;if(0===e.indexOf("data:"))return-1!==e.indexOf("base64");try{return btoa(atob(e))===e}catch(e){return!1}}function R(e){return e instanceof Blob}function E(e){return e instanceof File}function p(e){if(!e)return"";const t=e.split(".");return t.length>1&&t.pop()?.toLowerCase()||""}function f(e){return{"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","audio/mpeg":"mp3","audio/mp3":"mp3","audio/wav":"wav","audio/ogg":"ogg","video/mp4":"mp4","video/webm":"webm","video/ogg":"ogv","application/pdf":"pdf","text/plain":"txt","text/html":"html","text/css":"css","text/javascript":"js","application/json":"json"}[e]||""}function g(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",mp4:"video/mp4",webm:"video/webm",ogv:"video/ogg",pdf:"application/pdf",txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json"}[e.toLowerCase()]||"application/octet-stream"}function m(e){let t="",r="";"string"==typeof e?(r=p(e),t=g(r)):(t=e.type||"",r=e.name?p(e.name):f(t));const i=t.startsWith("image/"),o=t.startsWith("audio/"),n=t.startsWith("video/"),a=t.startsWith("application/")||t.startsWith("text/");let l;return l=i?s.IMAGE:o?s.AUDIO:n?s.VIDEO:a?s.DOCUMENT:t.includes("zip")||t.includes("rar")||t.includes("tar")?s.ARCHIVE:t.includes("javascript")||t.includes("json")||"js"===r||"ts"===r?s.CODE:s.OTHER,{isImage:i,isAudio:o,isVideo:n,isDocument:a,type:l,mimeType:t,extension:r,isSupported:!0}}function O(e=""){return`file_${(new Date).getTime()}_${Math.floor(1e4*Math.random())}${e?"."+e:""}`}function w(e){const t=e.match(/^data:([\w\/+]+);base64,/);return t&&t.length>1?t[1]:""}!function(e){e.IMAGE="image",e.AUDIO="audio",e.VIDEO="video",e.DOCUMENT="document",e.ARCHIVE="archive",e.CODE="code",e.OTHER="other"}(s||(s={})),function(e){e.DESKTOP="desktop",e.MOBILE="mobile",e.TABLET="tablet",e.TV="tv",e.WEARABLE="wearable",e.UNKNOWN="unknown"}(o||(o={})),function(e){e.WINDOWS="windows",e.MACOS="macos",e.LINUX="linux",e.ANDROID="android",e.IOS="ios",e.UNKNOWN="unknown"}(n||(n={})),function(e){e.CHROME="chrome",e.FIREFOX="firefox",e.SAFARI="safari",e.EDGE="edge",e.IE="ie",e.OPERA="opera",e.UNKNOWN="unknown"}(a||(a={})),function(e){e.NORMAL="normal",e.ITALIC="italic",e.OBLIQUE="oblique"}(l||(l={})),function(e){e[e.THIN=100]="THIN",e[e.EXTRA_LIGHT=200]="EXTRA_LIGHT",e[e.LIGHT=300]="LIGHT",e[e.NORMAL=400]="NORMAL",e[e.MEDIUM=500]="MEDIUM",e[e.SEMI_BOLD=600]="SEMI_BOLD",e[e.BOLD=700]="BOLD",e[e.EXTRA_BOLD=800]="EXTRA_BOLD",e[e.BLACK=900]="BLACK"}(c||(c={})),function(e){e.TEXT="text/plain",e.HTML="text/html",e.RTF="text/rtf",e.IMAGE="image/png",e.JSON="application/json"}(h||(h={}));class T extends BaseManager{constructor(){super(...arguments),this.CHUNK_SIZE=512}getDefaultOptions(){return{debug:!1,timeout:3e4,retries:2,cache:!0,cacheTTL:3e5,maxFileSize:10485760,allowedTypes:[],enableTypeValidation:!0,enableSizeValidation:!0,defaultReadAs:"dataURL"}}async initialize(){if(!this.initialized)try{this.checkBrowserSupport(),this.initialized=!0,this.emit("initialized"),this.logger.info("FileManager initialized successfully")}catch(e){throw this.handleError(e,"initialize")}}destroy(){this.baseDestroy(),this.logger.info("FileManager destroyed")}async urlToBase64(e){if(this.ensureInitialized(),this.ensureNotDestroyed(),!this.validateInput(e,{type:"string",required:!0}))throw this.handleError(new Error("Invalid URL parameter"),"urlToBase64");const t=Date.now(),r=`url_to_base64_${e}`;try{const i=this.getCached(r);if(i)return{result:i,duration:Date.now()-t,fromCache:!0};const s=await this.safeExecute(async()=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const r=await t.blob();return await this.blobToBase64(r)},"urlToBase64");return this.setCached(r,s.result,3e5),{result:s.result,duration:Date.now()-t,fromCache:!1}}catch(e){throw this.handleError(e,"urlToBase64")}}async blobToBase64(e){if(this.ensureInitialized(),this.ensureNotDestroyed(),!R(e))throw this.handleError(new Error("Parameter must be a Blob object"),"blobToBase64");if(this.options.enableSizeValidation&&e.size>this.options.maxFileSize)throw this.handleError(new Error(`File size ${e.size} exceeds maximum allowed size ${this.options.maxFileSize}`),"blobToBase64");const t=Date.now();try{return{result:await this.safeExecute(()=>new Promise((t,r)=>{const i=new FileReader;i.onload=()=>{"string"==typeof i.result?t(i.result):r(new Error("FileReader result is not a string"))},i.onerror=()=>r(new Error("Failed to read Blob as Base64")),i.readAsDataURL(e)}),"blobToBase64"),originalInfo:this.extractFileInfo(e),duration:Date.now()-t,fromCache:!1}}catch(e){throw this.handleError(e,"blobToBase64")}}async fileToBase64(e){if(this.ensureInitialized(),this.ensureNotDestroyed(),!E(e))throw this.handleError(new Error("Parameter must be a File object"),"fileToBase64");if(this.options.enableTypeValidation&&!this.isAllowedFileType(e))throw this.handleError(new Error(`File type ${e.type} is not allowed`),"fileToBase64");const t=await this.blobToBase64(e);return t.originalInfo=this.extractFileInfo(e),t}base64ToBlob(e){if(this.ensureInitialized(),this.ensureNotDestroyed(),!this.validateInput(e,{type:"string",required:!0}))throw this.handleError(new Error("Invalid Base64 parameter"),"base64ToBlob");if(!d(e))throw this.handleError(new Error("Invalid Base64 format"),"base64ToBlob");const t=Date.now();try{let r="application/octet-stream",i=e;if(e.startsWith("data:")){r=w(e)||r;const t=e.split(",");if(2!==t.length)throw new Error("Invalid DataURL format");i=t[1]}const s=atob(i),o=[];for(let e=0;e<s.length;e+=this.CHUNK_SIZE){const t=s.slice(e,e+this.CHUNK_SIZE),r=new Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);o.push(new Uint8Array(r))}const n=new Blob(o,{type:r});return{result:n,convertedInfo:this.extractFileInfo(n),duration:Date.now()-t,fromCache:!1}}catch(e){throw this.handleError(e,"base64ToBlob")}}base64ToFile(e,t){this.ensureInitialized(),this.ensureNotDestroyed();const r=this.base64ToBlob(e),i=r.result,s=Date.now();try{let e,o=i.type||"application/octet-stream",n=f(o);e=t?!t.includes(".")&&n?`${t}.${n}`:t:O(n);const a=new File([i],e,{type:o});return{result:a,originalInfo:r.convertedInfo,convertedInfo:this.extractFileInfo(a),duration:r.duration+(Date.now()-s),fromCache:!1}}catch(e){throw this.handleError(e,"base64ToFile")}}fileToBlob(e){if(this.ensureInitialized(),this.ensureNotDestroyed(),!E(e))throw this.handleError(new Error("Parameter must be a File object"),"fileToBlob");const t=Date.now();try{const r=new Blob([e],{type:e.type});return{result:r,originalInfo:this.extractFileInfo(e),convertedInfo:this.extractFileInfo(r),duration:Date.now()-t,fromCache:!1}}catch(e){throw this.handleError(e,"fileToBlob")}}blobToFile(e,t){if(this.ensureInitialized(),this.ensureNotDestroyed(),!R(e))throw this.handleError(new Error("Parameter must be a Blob object"),"blobToFile");const r=Date.now();try{let i,s=e.type||"application/octet-stream",o=f(s);i=t?!t.includes(".")&&o?`${t}.${o}`:t:O(o);const n=new File([e],i,{type:s});return{result:n,originalInfo:this.extractFileInfo(e),convertedInfo:this.extractFileInfo(n),duration:Date.now()-r,fromCache:!1}}catch(e){throw this.handleError(e,"blobToFile")}}async readFile(e,t){if(this.ensureInitialized(),this.ensureNotDestroyed(),!E(e))throw this.handleError(new Error("Parameter must be a File object"),"readFile");const r={readAs:this.options.defaultReadAs,...t},i=Date.now();try{return{result:await this.safeExecute(()=>new Promise((t,i)=>{const s=new FileReader;switch(r.enableProgress&&r.onProgress&&(s.onprogress=e=>{if(e.lengthComputable){const t=e.loaded/e.total*100;r.onProgress(t)}}),s.onload=()=>t(s.result),s.onerror=()=>i(new Error(`Failed to read file as ${r.readAs}`)),r.readAs){case"text":s.readAsText(e,r.encoding);break;case"dataURL":default:s.readAsDataURL(e);break;case"arrayBuffer":s.readAsArrayBuffer(e);break;case"binaryString":s.readAsBinaryString(e)}}),"readFile"),fileInfo:this.extractFileInfo(e),duration:Date.now()-i,success:!0}}catch(t){return{result:null,fileInfo:this.extractFileInfo(e),duration:Date.now()-i,success:!1,error:t.message}}}checkFileType(e){this.ensureInitialized(),this.ensureNotDestroyed();try{return m(e)}catch(e){throw this.handleError(e,"checkFileType")}}validateFile(e){this.ensureInitialized(),this.ensureNotDestroyed();const t=[];try{return E(e)?(this.options.enableSizeValidation&&e.size>this.options.maxFileSize&&t.push(`File size ${e.size} exceeds maximum allowed size ${this.options.maxFileSize}`),this.options.enableTypeValidation&&!this.isAllowedFileType(e)&&t.push(`File type ${e.type} is not allowed`),e.name&&""!==e.name.trim()||t.push("File name is required"),{valid:0===t.length,errors:t}):(t.push("Invalid file object"),{valid:!1,errors:t})}catch(e){throw this.handleError(e,"validateFile")}}checkBrowserSupport(){const e=[{name:"FileReader",api:"undefined"!=typeof FileReader},{name:"Blob",api:"undefined"!=typeof Blob},{name:"File",api:"undefined"!=typeof File},{name:"atob",api:"undefined"!=typeof atob},{name:"btoa",api:"undefined"!=typeof btoa}].filter(e=>!e.api);if(e.length>0)throw new Error(`Unsupported browser APIs: ${e.map(e=>e.name).join(", ")}`)}isAllowedFileType(e){return 0===this.options.allowedTypes.length||this.options.allowedTypes.some(t=>{if(t.includes("/"))return e.type===t||e.type.startsWith(t.replace("*",""));return p(e.name)===t.toLowerCase()})}extractFileInfo(e){const t=E(e),r=m(t?e:"unknown");return{name:t?e.name:"blob",size:e.size,type:r.type,mimeType:e.type||"application/octet-stream",extension:r.extension,lastModified:t?e.lastModified:Date.now()}}}const I=new T;exports.FileManager=T,exports.base64ToBlob=function(e){return I.getStatus().initialized||I.initialize().catch(()=>{}),I.base64ToBlob(e).result},exports.base64ToFile=function(e,t){return I.getStatus().initialized||I.initialize().catch(()=>{}),I.base64ToFile(e,t).result},exports.blobToBase64=async function(e){return I.getStatus().initialized||await I.initialize(),(await I.blobToBase64(e)).result},exports.blobToFile=function(e,t){return I.getStatus().initialized||I.initialize().catch(()=>{}),I.blobToFile(e,t).result},exports.checkFileType=m,exports.delay=function(e){return new Promise(t=>setTimeout(t,e))},exports.fileToBase64=async function(e){return I.getStatus().initialized||await I.initialize(),(await I.fileToBase64(e)).result},exports.fileToBlob=function(e){return I.getStatus().initialized||I.initialize().catch(()=>{}),I.fileToBlob(e).result},exports.generateRandomFileName=O,exports.getBase64FromDataURL=function(e){return e.split(",")[1]||""},exports.getExtensionFromMimeType=f,exports.getFileExtension=p,exports.getMimeTypeFromDataURL=w,exports.getMimeTypeFromExtension=g,exports.isBase64=d,exports.isBlob=R,exports.isFile=E,exports.urlToBase64=async function(e){return I.getStatus().initialized||await I.initialize(),(await I.urlToBase64(e)).result};