my-uniapp-tools
Version:
一个功能强大、性能优化的 uni-app 开发工具库,提供剪贴板、本地存储、导航、系统信息等常用功能
2 lines (1 loc) • 23.8 kB
JavaScript
;class e extends Error{code;module;timestamp;constructor(e,t,n){super(t),this.name="UniAppToolsError",this.code=e,this.module=n,this.timestamp=Date.now()}}class t{static instance;errorCallbacks=[];static getInstance(){return t.instance||(t.instance=new t),t.instance}onError(e){this.errorCallbacks.push(e)}handleError(t,n){const s={code:t instanceof e?t.code:"UNKNOWN_ERROR",message:t.message,module:t instanceof e?t.module:n,timestamp:t instanceof e?t.timestamp:Date.now(),stack:t.stack};this.errorCallbacks.forEach(e=>{try{e(s)}catch(e){}})}createModuleErrorHandler(t){return(n,s,a)=>{const r=new e(n,s,t);return a&&(r.stack=a.stack),this.handleError(r,t),r}}}async function n(e,n,s="ASYNC_ERROR"){try{return await e()}catch(e){return t.getInstance().createModuleErrorHandler(n)(s,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function s(e,n,s="SYNC_ERROR",a=null){try{return e()}catch(e){return t.getInstance().createModuleErrorHandler(n)(s,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),a}}var a=Object.freeze({__proto__:null,ErrorHandler:t,UniAppToolsError:e,safeAsync:n,safeSync:s});class r{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return r.instance||(r.instance=new r),r.instance}start(e,t,n){const s={name:e,startTime:performance.now(),module:t,metadata:n};this.metrics.set(e,s)}end(e){const t=this.metrics.get(e);return t?(t.endTime=performance.now(),t.duration=t.endTime-t.startTime,this.metrics.delete(e),this.completedMetrics.push(t),this.completedMetrics.length>this.maxStoredMetrics&&this.completedMetrics.shift(),t):null}getReport(){const e={},t={};this.completedMetrics.forEach(n=>{e[n.module]||(e[n.module]=[]),e[n.module].push(n);const s=`${n.module}.${n.name}`;t[s]||(t[s]={total:0,count:0}),t[s].total+=n.duration||0,t[s].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const s=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:s,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function o(e){return function(t,n,s){const a=s.value;s.value=function(...s){const o=r.getInstance(),i=`${t.constructor.name}.${n}`;o.start(i,e,{args:s.length});try{const e=a.apply(this,s);return e instanceof Promise?e.finally(()=>{o.end(i)}):(o.end(i),e)}catch(e){throw o.end(i),e}}}}var i=Object.freeze({__proto__:null,PerformanceMonitor:r,measurePerformance:o});const c=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function u(e){return s(()=>{if(null===e||"object"!=typeof e)return e;const t=new WeakMap;return function e(n){if(null===n||"object"!=typeof n)return n;if(t.has(n))return t.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(n instanceof Map){const s=new Map;return t.set(n,s),n.forEach((t,n)=>{s.set(e(n),e(t))}),s}if(n instanceof Set){const s=new Set;return t.set(n,s),n.forEach(t=>{s.add(e(t))}),s}if(Array.isArray(n)){const s=new Array(n.length);t.set(n,s);for(let t=0;t<n.length;t++)s[t]=e(n[t]);return s}const s=Object.create(Object.getPrototypeOf(n));t.set(n,s);const a=Object.getOwnPropertyDescriptors(n);for(const t in a){const n=a[t];void 0!==n.value&&(n.value=e(n.value)),Object.defineProperty(s,t,n)}return s}(e)},"utils","DEEP_CLONE_ERROR",e)}function l(e,t){const n=r.getInstance();n.start("mergeObjects","utils");const a=s(()=>Object.assign(e,t),"utils","MERGE_OBJECTS_ERROR",e);return n.end("mergeObjects"),a}function p(e,t,n=!1){let s,a=null;const r=function(...r){const o=n&&!a;return a&&clearTimeout(a),a=setTimeout(()=>{a=null,n||(s=e.apply(this,r))},t),o&&(s=e.apply(this,r)),s};return r.cancel=()=>{a&&(clearTimeout(a),a=null)},r}class g{static instance;navigationQueue=[];isNavigating=!1;maxQueueSize=10;static getInstance(){return g.instance||(g.instance=new g),g.instance}async processQueue(){if(!this.isNavigating&&0!==this.navigationQueue.length){for(this.isNavigating=!0;this.navigationQueue.length>0;){const e=this.navigationQueue.shift();if(e)try{await e(),await new Promise(e=>setTimeout(e,100))}catch(e){}}this.isNavigating=!1}}addToQueue(e){this.navigationQueue.length>=this.maxQueueSize&&this.navigationQueue.shift(),this.navigationQueue.push(e),this.processQueue()}async navigateTo(e){const t=r.getInstance();return t.start("navigateTo","navigation",{url:e.url}),new Promise(s=>{this.addToQueue(async()=>{const a=await n(()=>new Promise(n=>{let s=e.url;if(e.params&&Object.keys(e.params).length>0){const t=Object.entries(e.params).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");s+=(s.includes("?")?"&":"?")+t}uni.navigateTo({url:s,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>{t.end("navigateTo"),n(!0)},fail:e=>{t.end("navigateTo"),n(!1)}})}),"navigation","NAVIGATE_TO_ERROR");s(a??!1)})})}async redirectTo(e){const t=r.getInstance();return t.start("redirectTo","navigation",{url:e.url}),new Promise(s=>{this.addToQueue(async()=>{const a=await n(()=>new Promise(n=>{let s=e.url;if(e.params&&Object.keys(e.params).length>0){const t=Object.entries(e.params).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");s+=(s.includes("?")?"&":"?")+t}uni.redirectTo({url:s,success:()=>{t.end("redirectTo"),n(!0)},fail:e=>{t.end("redirectTo"),n(!1)}})}),"navigation","REDIRECT_TO_ERROR");s(a??!1)})})}async navigateBack(e="",t={}){const s=r.getInstance();s.start("navigateBack","navigation");const a={delta:1,timeout:5e3,enableDebounce:!0,debounceWait:300,...t};return new Promise(t=>{this.addToQueue(async()=>{const r=await n(()=>new Promise(t=>{if(getCurrentPages().length<=a.delta)return void t(!1);const n=setTimeout(()=>{t(!1)},a.timeout);uni.navigateBack({delta:a.delta,success:()=>{clearTimeout(n),setTimeout(()=>{try{const n=getCurrentPages();if(n.length>0){const t=n[n.length-1];t.$vm&&"function"==typeof t.$vm.init?t.$vm.init(e):t.route}s.end("navigateBack"),t(!0)}catch(e){s.end("navigateBack"),t(!0)}},100)},fail:e=>{clearTimeout(n),s.end("navigateBack"),t(!1)}})}),"navigation","NAVIGATE_BACK_ERROR");t(r??!1)})})}async switchTab(e){const t=r.getInstance();return t.start("switchTab","navigation",{url:e}),new Promise(s=>{this.addToQueue(async()=>{const a=await n(()=>new Promise(n=>{uni.switchTab({url:e,success:()=>{t.end("switchTab"),n(!0)},fail:e=>{t.end("switchTab"),n(!1)}})}),"navigation","SWITCH_TAB_ERROR");s(a??!1)})})}async reLaunch(e){const t=r.getInstance();return t.start("reLaunch","navigation",{url:e.url}),new Promise(s=>{this.addToQueue(async()=>{const a=await n(()=>new Promise(n=>{let s=e.url;if(e.params&&Object.keys(e.params).length>0){const t=Object.entries(e.params).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");s+=(s.includes("?")?"&":"?")+t}uni.reLaunch({url:s,success:()=>{t.end("reLaunch"),n(!0)},fail:e=>{t.end("reLaunch"),n(!1)}})}),"navigation","RELAUNCH_ERROR");s(a??!1)})})}getCurrentPageInfo(){return s(()=>{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}},"navigation","GET_CURRENT_PAGE_ERROR",null)}getPageStack(){return s(()=>getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}})),"navigation","GET_PAGE_STACK_ERROR",[])??[]}clearQueue(){this.navigationQueue=[],this.isNavigating=!1}}const d=g.getInstance(),m=async(e="",t={})=>await d.navigateBack(e,t),h=p(m,300),f=async e=>await d.navigateTo(e),y={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function w(e,t={}){const a=r.getInstance();a.start("copyText","clipboard",{textLength:e.length});const o={...y,...t};if(!e||"string"!=typeof e)return o.showToast&&c("复制内容不能为空",!1,"error"),a.end("copyText"),!1;if(e.length>1e4)return o.showToast&&c("复制内容过长",!1,"error"),a.end("copyText"),!1;let i=!1;return i=await n(()=>new Promise(t=>{uni.setClipboardData({data:e,success:()=>{o.showToast&&c(o.successMessage),t(!0)},fail:()=>{o.showToast&&c(o.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_NATIVE_ERROR")??!1,i=await async function(e,t){if(navigator.clipboard&&window.isSecureContext){if(await n(async()=>(await Promise.race([navigator.clipboard.writeText(e),new Promise((e,n)=>setTimeout(()=>n(new Error("Clipboard API timeout")),t.timeout))]),!0),"clipboard","CLIPBOARD_API_ERROR"))return t.showToast&&c(t.successMessage),!0}return function(e,t){return s(()=>{const n=document.createElement("textarea");Object.assign(n.style,{position:"fixed",top:"-9999px",left:"-9999px",width:"1px",height:"1px",padding:"0",border:"none",outline:"none",boxShadow:"none",background:"transparent",fontSize:"16px"}),n.value=e,n.setAttribute("readonly",""),n.setAttribute("contenteditable","true"),document.body.appendChild(n),n.focus(),n.select(),n.setSelectionRange(0,e.length);const s=document.execCommand("copy");return document.body.removeChild(n),s?(t.showToast&&c(t.successMessage),!0):(t.showToast&&c(t.failMessage),!1)},"clipboard","FALLBACK_COPY_ERROR",!1)??!1}(e,t)}(e,o),a.end("copyText"),i}class T{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return T.instance||(T.instance=new T),T.instance}set(e,t,n=this.defaultTTL){this.cache.set(e,{data:t,timestamp:Date.now(),ttl:n})}get(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>t.ttl?(this.cache.delete(e),null):t.data:null}clear(){this.cache.clear()}}const R=T.getInstance(),E=()=>{let e;return e="weixin",e="web",e="app",e="alipay",e="h5","h5"},S=()=>{try{return uni.getSystemInfoSync().statusBarHeight||0}catch(e){return 0}},x=()=>{try{const e=E();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},v=()=>{try{const e=S(),t=E();if("weixin"===t||"alipay"===t){const t=x();if(t){return t.height+e}}return e+0}catch(e){return S()+0}};class I{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return I.instance||(I.instance=new I),I.instance}compress(e){return e.replace(/(.)\1{2,}/g,(e,t)=>`${t}*${e.length}`)}decompress(e){return e.replace(/(.)\*(\d+)/g,(e,t,n)=>t.repeat(parseInt(n)))}encrypt(e){return btoa(encodeURIComponent(e))}decrypt(e){try{return decodeURIComponent(atob(e))}catch{return e}}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){const a=r.getInstance();a.start(`setStorage_${e}`,"localStorage");const o=s(()=>{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const s={value:t,timestamp:Date.now(),ttl:n.ttl,compressed:n.compress,encrypted:n.encrypt};let a=JSON.stringify(s);if(n.compress&&(a=this.compress(a)),n.encrypt&&(a=this.encrypt(a)),a.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,a),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,s),!0},"localStorage","SET_STORAGE_ERROR",!1);return a.end(`setStorage_${e}`),o??!1}get(e,t){const n=r.getInstance();n.start(`getStorage_${e}`,"localStorage");const a=s(()=>{if(!e||"string"!=typeof e)return t;if(this.cache.has(e)){const n=this.cache.get(e);return this.isExpired(n)?(this.cache.delete(e),this.remove(e),t):n.value}let n=uni.getStorageSync(e);if(!n)return t;if("string"!=typeof n)return t;let s,a=n;if(a&&a.includes("="))try{const e=this.decrypt(a);e&&(a=e)}catch{}if(a&&a.includes("*"))try{a=this.decompress(a)}catch{}try{const e=JSON.parse(a);s=e&&"object"==typeof e&&"value"in e&&"timestamp"in e?e:{value:e,timestamp:Date.now()}}catch{return a}return this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)},"localStorage","GET_STORAGE_ERROR",t);return n.end(`getStorage_${e}`),a??t}remove(e){return s(()=>!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0),"localStorage","REMOVE_STORAGE_ERROR",!1)??!1}clear(){return s(()=>(uni.clearStorageSync(),this.cache.clear(),!0),"localStorage","CLEAR_STORAGE_ERROR",!1)??!1}getInfo(){return s(()=>{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}},"localStorage","GET_STORAGE_INFO_ERROR",{keys:[],currentSize:0,limitSize:0})??{keys:[],currentSize:0,limitSize:0}}cleanExpired(){const e=r.getInstance();e.start("cleanExpiredStorage","localStorage");const t=s(()=>{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t},"localStorage","CLEAN_EXPIRED_ERROR",0);return e.end("cleanExpiredStorage"),t??0}}const O=I.getInstance();function P(e,t,n={}){return O.set(e,t,n)}function b(e,t){return O.get(e,t)}const _={name:"file",maxSize:10,allowedTypes:["jpg","jpeg","png","gif","webp"],showToast:!0,timeout:6e4,successMessage:"上传成功",failMessage:"上传失败"},C={type:"image",count:1,sizeType:["original","compressed"],sourceType:["album","camera"],extension:[],maxSize:10,showToast:!0,failMessage:"选择文件失败"};async function A(e={}){const t=r.getInstance();t.start("chooseFile","upload",{count:e.count,type:e.type});const s={...C,...e};let a=s.type;var o;("messagefile"===(o=a)?"function"==typeof uni.chooseMessageFile:"local"===o||"image"===o)||(a="image");const i=await n(()=>new Promise(e=>{const t=t=>{const n=t.errMsg||s.failMessage;s.showToast&&c(n,!1,"error"),e({success:!1,message:n,type:a})};"image"!==a&&"local"!==a?"messagefile"===a?uni.chooseMessageFile({count:s.count,type:"all",success:t=>{e({success:!0,tempFilePaths:t.tempFiles.map(e=>e.path),tempFiles:t.tempFiles,type:"messagefile"})},fail:t}):"image"===a?uni.chooseImage({count:s.count,sizeType:s.sizeType,sourceType:s.sourceType,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"image"})},fail:t}):"local"===a&&("function"==typeof uni.chooseFile?uni.chooseFile({count:s.count,extension:s.extension,success:t=>{const n=Array.isArray(t.tempFilePaths)?t.tempFilePaths:[t.tempFilePaths],s=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>({path:n[t],size:e.size}));e({success:!0,tempFilePaths:n,tempFiles:s,type:"local"})},fail:t}):e({success:!1,message:"当前平台不支持选择本地文件",type:a})):function(e,t){const n=document.createElement("input");n.type="file",n.multiple=e.count>1,"image"===e.type?n.accept="image/*":e.extension.length>0&&(n.accept=e.extension.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),n.onchange=s=>{const a=s.target.files;if(a&&a.length>0){const n=Array.from(a).map(e=>({path:URL.createObjectURL(e),size:e.size,name:e.name,type:e.type,file:e})),s=n.map(e=>({path:e.path,size:e.size}));t({success:!0,tempFilePaths:n.map(e=>e.path),tempFiles:s,type:e.type})}else t({success:!1,message:"用户取消选择",type:e.type});document.body.removeChild(n)},n.style.display="none",document.body.appendChild(n),n.click()}(s,e)}).then(e=>{if(!e.success||!e.tempFiles||!s.maxSize)return e;if(e.tempFiles.filter(e=>{var t,n;return!(t=e.size,(n=s.maxSize)&&t>1024*n*1024?{valid:!1,message:`文件大小不能超过 ${n}MB`}:{valid:!0}).valid}).length>0){const t=`部分文件大小超过 ${s.maxSize}MB 限制`;return s.showToast&&c(t,!1,"error"),{...e,success:!1,message:t}}return e}),"upload","CHOOSE_FILE_ERROR");return t.end("chooseFile"),i||{success:!1,message:"选择文件失败",type:a}}async function F(e,t,s){const a=r.getInstance();a.start("uploadFile","upload",{filePath:e});const o={..._,...t};if(!o.url){const e="上传地址不能为空";return o.showToast&&c(e,!1,"error"),a.end("uploadFile"),{success:!1,message:e}}const i=function(e,t){if(!e)return{valid:!1,message:"文件路径不能为空"};if(t.allowedTypes&&t.allowedTypes.length>0){const n=e.split(".").pop()?.toLowerCase();if(!n||!t.allowedTypes.includes(n))return{valid:!1,message:`不支持的文件类型,仅支持:${t.allowedTypes.join(", ")}`}}return{valid:!0}}(e,o);if(!i.valid)return o.showToast&&c(i.message,!1,"error"),a.end("uploadFile"),{success:!1,message:i.message};const u=await n(()=>new Promise(t=>{const n=uni.uploadFile({url:o.url,filePath:e,name:o.name,formData:o.formData,header:o.header,timeout:o.timeout,success:n=>{let s;try{s=JSON.parse(n.data)}catch{s=n.data}if(200===n.statusCode)o.showToast&&c(o.successMessage,!1,"success"),t({success:!0,data:s,tempFilePath:e,statusCode:n.statusCode});else{const e=`上传失败,状态码:${n.statusCode}`;o.showToast&&c(e,!1,"error"),t({success:!1,message:e,statusCode:n.statusCode})}},fail:n=>{const s=n.errMsg||o.failMessage;o.showToast&&c(s,!1,"error"),t({success:!1,message:s,tempFilePath:e})}});s&&n&&n.onProgressUpdate(e=>{s({progress:e.progress,totalBytesSent:e.totalBytesSent,totalBytesExpectedToSend:e.totalBytesExpectedToSend})})}),"upload","UPLOAD_FILE_ERROR");return a.end("uploadFile"),u||{success:!1,message:"上传文件失败"}}async function M(e,t={},n){const s=r.getInstance();s.start("chooseAndUploadFile","upload");const a=await A(t);if(!a.success||!a.tempFilePaths)return s.end("chooseAndUploadFile"),[{success:!1,message:a.message||"选择文件失败"}];const o=a.tempFilePaths.map(t=>F(t,e,n)),i=await Promise.all(o);return s.end("chooseAndUploadFile"),i}exports.ErrorHandler=t,exports.PerformanceMonitor=r,exports.UniAppToolsError=e,exports.VERSION="1.0.8",exports.batchGetStorage=function(e){const t=r.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=b(e)}),t.end("batchGetStorage"),n},exports.batchSetStorage=function(e,t={}){const n=r.getInstance();n.start("batchSetStorage","localStorage");let s=0;return Object.entries(e).forEach(([e,n])=>{P(e,n,t)&&s++}),n.end("batchSetStorage"),s},exports.chooseAndUploadFile=M,exports.chooseAndUploadImage=async function(e,t={},n){return M(e,{...t,type:"image"},n)},exports.chooseFile=A,exports.chooseImage=async function(e={}){const t=await A({...e,type:"image"});return{success:t.success,tempFilePaths:t.tempFilePaths,tempFiles:t.tempFiles,message:t.message}},exports.cleanExpiredStorage=function(){return O.cleanExpired()},exports.clearClipboard=async function(e={}){return await w("",e)},exports.clearNavigationQueue=()=>{d.clearQueue()},exports.clearStorageSync=function(e){return e?O.remove(e):O.clear()},exports.copyText=w,exports.debounce=p,exports.deepClone=u,exports.deepMerge=function(e,t){const n=r.getInstance();n.start("deepMerge","utils");const a=s(()=>{const n=u(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const a=n[s],r=t[s];a&&"object"==typeof a&&!Array.isArray(a)&&r&&"object"==typeof r&&!Array.isArray(r)?e(r,a):t[s]=u(a)}}(n,t),n},"utils","DEEP_MERGE_ERROR",e);return n.end("deepMerge"),a},exports.getCurrentEnv=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return{appId:"",version:"",envVersion:"",accountInfo:null}}},exports.getCurrentPageInfo=()=>d.getCurrentPageInfo(),exports.getFileInfo=async function(e){return await n(()=>new Promise((t,n)=>{uni.getFileInfo({filePath:e,digestAlgorithm:"md5",success:e=>{const n=e;t({size:n.size,digest:n.digest})},fail:n})}),"upload","GET_FILE_INFO_ERROR")},exports.getMenuButtonBoundingClientRect=x,exports.getNavHeight=v,exports.getPageStack=()=>d.getPageStack(),exports.getPlatform=E,exports.getStatusBarHeight=S,exports.getStorage=async function(e,t){return await n(()=>new Promise(n=>{n(b(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return O.getInfo()},exports.getStorageSync=b,exports.getTopNavBarHeight=()=>{try{const e=S();return{statusBarHeight:e,navHeight:v()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,logLevel:s="warn"}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return a}),n=e.getInstance();t&&n.onError(e=>{})}if(t){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return i}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},6e4)}},exports.isClipboardSupported=function(){return!(!navigator.clipboard||!window.isSecureContext)},exports.isUploadSupported=function(){return"undefined"!=typeof uni&&"function"==typeof uni.chooseImage&&"function"==typeof uni.uploadFile},exports.measurePerformance=o,exports.mergeObjects=l,exports.navigateTo=f,exports.onCheckForUpdate=()=>{try{const e=uni.getUpdateManager();e.onCheckForUpdate(function(e){e.hasUpdate}),e.onUpdateReady(function(t){uni.showModal({title:"更新提示",content:"新版本已经准备好,是否重启应用?",showCancel:!0,cancelText:"稍后",confirmText:"立即重启",success(t){t.confirm&&e.applyUpdate()}})}),e.onUpdateFailed(function(e){uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){}},exports.reLaunch=async e=>await d.reLaunch(e),exports.readClipboard=async function(e={}){const t=r.getInstance();t.start("readClipboard","clipboard");const s={...y,...e};if(navigator.clipboard&&window.isSecureContext){const e=await n(async()=>await Promise.race([navigator.clipboard.readText(),new Promise((e,t)=>setTimeout(()=>t(new Error("Read clipboard timeout")),s.timeout))]),"clipboard","READ_CLIPBOARD_ERROR");return t.end("readClipboard"),e}return s.showToast&&c("当前平台不支持读取剪贴板",!1,"error"),t.end("readClipboard"),null},exports.redirectTo=async e=>await d.redirectTo(e),exports.safeAsync=n,exports.safeNavigateTo=async(e,t=3)=>{for(let n=0;n<t;n++){if(await f(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=s,exports.setPageIcon=(e,t="image/x-icon")=>s(()=>{const n=E();if(("h5"===n||"web"===n)&&"undefined"!=typeof document){document.querySelectorAll('link[rel*="icon"]').forEach(e=>e.remove());const n=document.createElement("link");return n.rel="icon",n.type=t,n.href=e,document.head.appendChild(n),!0}return!1},"system","SET_PAGE_ICON_ERROR",!1),exports.setPageTitle=e=>s(()=>{const t=E();return("h5"===t||"web"===t)&&"undefined"!=typeof document&&(document.title=e,!0)},"system","SET_PAGE_TITLE_ERROR",!1),exports.setStorage=async function(e,t,s={}){return await n(()=>new Promise(n=>{n(P(e,t,s))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=P,exports.switchTab=async e=>await d.switchTab(e),exports.throttle=function(e,t,n={}){let s,a=null,r=0;const{leading:o=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();r||o||(r=c);const u=t-(c-r);return u<=0||u>t?(a&&(clearTimeout(a),a=null),r=c,s=e.apply(this,n)):!a&&i&&(a=setTimeout(()=>{r=o?Date.now():0,a=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{a&&(clearTimeout(a),a=null),r=0},c},exports.uploadFile=F,exports.useBack=m,exports.useBackDebounced=h,exports.useBackOrHome=async(e="",t={})=>{const n=r.getInstance();n.start("useBackOrHome","navigation");try{const s=getCurrentPages(),a=t.delta||1;if(s.length>a){const s=await d.navigateBack(e,t);return n.end("useBackOrHome"),s}const r=t.homePage||"pages/index/index",o=r.startsWith("/")?r:`/${r}`,i=await d.reLaunch({url:o,params:t.homeParams});return n.end("useBackOrHome"),i}catch(e){return n.end("useBackOrHome"),!1}},exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return l(e,u(t))}return u(t)},exports.useToast=c,exports.useWindowInfo=(e=!0)=>{const t=r.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=R.get(n);if(e)return t.end("getWindowInfo"),e}const a=s(()=>{const t=uni.getWindowInfo();return e&&R.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),a};