my-uniapp-tools 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("@vant/area-data");class t 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 n{static instance;errorCallbacks=[];static getInstance(){return n.instance||(n.instance=new n),n.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,n){const r={code:e instanceof t?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof t?e.module:n,timestamp:e instanceof t?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){}})}createModuleErrorHandler(e){return(n,r,s)=>{const o=new t(n,r,e);return s&&(o.stack=s.stack),this.handleError(o,e),o}}}async function r(e,t,r="ASYNC_ERROR"){try{return await e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function s(e,t,r="SYNC_ERROR",s=null){try{return e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var o=Object.freeze({__proto__:null,ErrorHandler:n,UniAppToolsError:t,safeAsync:r,safeSync:s});function a(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const r={name:e,startTime:a(),module:t,metadata:n};this.metrics.set(e,r)}end(e){const t=this.metrics.get(e);return t?(t.endTime=a(),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 r=`${n.module}.${n.name}`;t[r]||(t[r]={total:0,count:0}),t[r].total+=n.duration||0,t[r].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const r=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:r,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function i(e){return function(t,n,r){const s=r.value;r.value=function(...r){const o=c.getInstance(),a=`${t.constructor.name}.${n}`;o.start(a,e,{args:r.length});try{const e=s.apply(this,r);return e instanceof Promise?e.finally(()=>{o.end(a)}):(o.end(a),e)}catch(e){throw o.end(a),e}}}}var u=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:i});class l{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return l.instance||(l.instance=new l),l.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 p=l.getInstance(),f=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=p.get(n);if(e)return t.end("getWindowInfo"),e}const r=s(()=>{const t=uni.getWindowInfo();return e&&p.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},d=()=>{const e="platform",t=p.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",p.set(e,"h5"),"h5"},m=()=>{try{const e=f();return e?.statusBarHeight||0}catch(e){return 0}},h=()=>{try{const e=d();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},g=()=>{try{const e=m(),t=d();if("weixin"===t||"alipay"===t){const t=h();if(t){return t.height+e}}return e+0}catch(e){return m()+0}};function w(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function y(e,t){return Object.assign(e,t)}function x(e,t,n=!1){let r,s=null;const o=function(...o){const a=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(r=e.apply(this,o))},t),a&&(r=e.apply(this,o)),r};return o.cancel=()=>{s&&(clearTimeout(s),s=null)},o}const S=e.areaList,E=e.useCascaderAreaData;const v=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})};function T(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function P(e){return new Promise(t=>{const n=T(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function R(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return void n(!1);const o=setTimeout(()=>{n(!1)},s);uni.navigateBack({delta:r,success:()=>{clearTimeout(o),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(o),n(!1)}})})}const C=x(R,300);async function I(e){return new Promise(t=>{const n=T(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const A={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class M{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return M.instance||(M.instance=new M),M.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const r={value:t,timestamp:Date.now(),ttl:n.ttl},s=JSON.stringify(r);if(s.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,s),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,r),!0}catch(e){throw e}}get(e,t){try{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}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const r=JSON.parse(n);let s;return s=r&&"object"==typeof r&&"value"in r&&"timestamp"in r?r:{value:r,timestamp:Date.now()},this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const b=M.getInstance();function _(e,t,n={}){return b.set(e,t,n)}function O(e,t){return b.get(e,t)}function D(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function k(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function j(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function U(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!D(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(r&&r.length>0){const t=r.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${r.join(", ")}`}}return{success:!0,files:e}}async function W(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:r}=e;return new Promise(s=>{if("undefined"==typeof document)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const o=document.createElement("input");o.type="file",o.multiple=n>1,"image"===t?o.accept="image/*":r&&r.length>0&&(o.accept=r.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),o.onchange=t=>{const n=t.target,r=n?.files;if(!r||0===r.length)return s({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(o);const a=U(Array.from(r).map((e,t)=>{const n=k(e.name),r=URL.createObjectURL(e);return{id:j(t),name:e.name,size:e.size,path:r,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);s(a),document.body.removeChild(o)},o.style.display="none",document.body.appendChild(o),o.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(r=>{const s="undefined"==typeof uni?null:uni;if(!s)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const o=e=>{r({success:!1,files:[],message:e?.errMsg||"选择文件失败"})};"image"!==t||"function"!=typeof s.chooseImage?"function"!=typeof s.chooseMessageFile?"function"!=typeof s.chooseFile?r({success:!1,files:[],message:"当前平台不支持文件选择"}):s.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:j(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:"app",raw:e}});r(U(n,e))},fail:o}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=k(e.name||e.path);return{id:j(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:"weixin",raw:e}});r(U(n,e))},fail:o}):s.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:j(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:"weixin",raw:e}});r(U(n,e))},fail:o})})}(e)}async function B(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,maxUploadFileSizeMB:c,showToast:i=!0,successMessage:u="上传成功",failMessage:l="上传失败",onProgress:p,beforeUpload:f}=t;if("function"==typeof f){if(!await Promise.resolve(f(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return i&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const d=D(e.size,c);if(!d.valid)return i&&d.message&&v(d.message,!1,"error"),Promise.resolve({file:e,success:!1,message:d.message});const m="undefined"==typeof uni?null:uni;if(!m||"function"!=typeof m.uploadFile){const t="当前环境不支持文件上传";return i&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const c=m.uploadFile({url:r,filePath:e.path,name:s,formData:o,header:a,success:r=>{let s=r.data;try{s=JSON.parse(r.data)}catch{}const o=r.statusCode;if(o>=200&&o<300)i&&1===n&&v(u,!1,"success"),t({file:e,success:!0,statusCode:o,data:s});else{const n=`上传失败,状态码:${o}`;i&&v(n,!1,"error"),t({file:e,success:!1,statusCode:o,data:s,message:n})}},fail:n=>{const r=n?.errMsg||l;i&&v(r,!1,"error"),t({file:e,success:!1,message:r})}});p&&c&&"function"==typeof c.onProgressUpdate&&c.onProgressUpdate(t=>{p(e,t.progress)})})}async function z(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await W(e);if(!r.success){const e=r.message||n;return t&&e&&v(e,!1,"error"),[{file:null,success:!1,message:e}]}const s=r.files;if(0===s.length)return[];const o=s.length;return await async function(e,t,n){const r=new Array(e.length),s=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let o=0;const a=async()=>{for(;;){const s=o;if(s>=e.length)break;o+=1;const a=e[s],c=await B(a,t,n);r[s]=c}},c=[];for(let e=0;e<s;e+=1)c.push(a());return await Promise.all(c),r}(s,e,o)}catch(e){const r=n;return t&&r&&v(r,!1,"error"),[{file:null,success:!1,message:r}]}}const N=()=>{const e=c.getInstance();e.start("isWechat","system");const t=s(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},$=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const r=s=>{const o=document.createElement("script");o.src=s,o.async=!0,o.onload=()=>{e(!0)},o.onerror=()=>{n++,n<t.length?(document.head.removeChild(o),r(t[n])):(document.head.removeChild(o),e(!1))},document.head.appendChild(o)};r(t[n]),e(!1)}),F=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!N())return!1;return!!await $()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},H=e=>{s(()=>{window.wx&&N()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},L=e=>{s(()=>{window.wx&&N()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class J{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return J.instance||(J.instance=new J),J.instance}async init(e){return this.config=e,this.isConfigured=await F(e),this.isConfigured}isReady(){return this.isConfigured&&N()}getConfig(){return this.config}setShareData(e){this.isReady()&&(H(e),L(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=c,exports.UniAppToolsError=t,exports.VERSION="2.0.0",exports.WechatSDK=J,exports.areaList=S,exports.batchGetStorage=function(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=O(e)}),t.end("batchGetStorage"),n},exports.batchSetStorage=function(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let r=0;return Object.entries(e).forEach(([e,n])=>{_(e,n,t)&&r++}),n.end("batchSetStorage"),r},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&N()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),exports.cleanExpiredStorage=function(){return b.cleanExpired()},exports.clearStorageSync=function(e){return e?b.remove(e):b.clear()},exports.configWechatJSSDK=F,exports.copyText=async function(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...A,...t};if(!e||"string"!=typeof e)return s.showToast&&v("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return s.showToast&&v("复制内容过长",!1,"error"),n.end("copyText"),!1;const o=await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{s.showToast&&v(s.successMessage),t(!0)},fail:()=>{s.showToast&&v(s.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),o},exports.debounce=x,exports.deepClone=w,exports.deepMerge=function(e,t){const n=w(e);return function e(t,n){for(const r in n)if(n.hasOwnProperty(r)){const s=n[r],o=t[r];s&&"object"==typeof s&&!Array.isArray(s)&&o&&"object"==typeof o&&!Array.isArray(o)?e(o,s):t[r]=w(s)}}(n,t),n},exports.extractUrlParts=function(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,r={};return t.searchParams.forEach((e,t)=>{r[t]=e}),{path:n,params:r}}catch(e){return{path:"",params:{}}}},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=function(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}},exports.getH5UrlParams=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(r){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}},exports.getMenuButtonBoundingClientRect=h,exports.getNavHeight=g,exports.getPageStack=function(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}},exports.getPlatform=d,exports.getStatusBarHeight=m,exports.getStorage=async function(e,t){return await r(()=>new Promise(n=>{n(O(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return b.getInfo()},exports.getStorageSync=O,exports.getTopNavBarHeight=()=>{try{const e=m();return{statusBarHeight:e,navHeight:g()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:r=null,performanceReportInterval:s=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof r?t.onError(r):t.onError(e=>{})}if(t&&s>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return u}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},s)}},exports.isWechat=N,exports.loadWechatJSSDK=$,exports.measurePerformance=i,exports.mergeObjects=y,exports.navigateTo=P,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=I,exports.redirectTo=async function(e){return new Promise(t=>{const n=T(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.safeAsync=r,exports.safeNavigateTo=async function(e,t=3){for(let n=0;n<t;n++){if(await P(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=s,exports.selectAndUpload=z,exports.selectAndUploadImage=async function(e){return z({...e,type:"image"})},exports.setPageIcon=(e,t="image/x-icon")=>s(()=>{const n=d();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=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),exports.setStorage=async function(e,t,n={}){return await r(()=>new Promise(r=>{r(_(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=_,exports.shareToFriend=L,exports.shareToTimeline=H,exports.switchTab=async function(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.throttle=function(e,t,n={}){let r,s=null,o=0;const{leading:a=!0,trailing:c=!0}=n,i=function(...n){const i=Date.now();o||a||(o=i);const u=t-(i-o);return u<=0||u>t?(s&&(clearTimeout(s),s=null),o=i,r=e.apply(this,n)):!s&&c&&(s=setTimeout(()=>{o=a?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return i.cancel=()=>{s&&(clearTimeout(s),s=null),o=0},i},exports.useBack=R,exports.useBackDebounced=C,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await R(e,t);const s=t.homePage||"pages/index/index",o=s.startsWith("/")?s:`/${s}`;return await I({url:o,params:t.homeParams})},exports.useCascaderAreaData=E,exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return y(e,w(t))}return w(t)},exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=v,exports.useTryCatch=function(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}},exports.useWindowInfo=f,exports.weChatOfficialAccountPayment=(e,t,n)=>{const r=c.getInstance();return r.start("weChatOfficialAccountPayment","payment"),new Promise(o=>{s(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function s(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){r.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),o(!0)):(n?.(e),o(!1))})}catch(e){r.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),o(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",s,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",s),e.attachEvent("onWeixinJSBridgeReady",s))}else s();return!0},"payment","WECHAT_PAY_ERROR",!1)||(r.end("weChatOfficialAccountPayment"),o(!1))})};
|
|
1
|
+
"use strict";var e=require("@vant/area-data");class t 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 n{static instance;errorCallbacks=[];static getInstance(){return n.instance||(n.instance=new n),n.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,n){const r={code:e instanceof t?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof t?e.module:n,timestamp:e instanceof t?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){}})}createModuleErrorHandler(e){return(n,r,s)=>{const o=new t(n,r,e);return s&&(o.stack=s.stack),this.handleError(o,e),o}}}async function r(e,t,r="ASYNC_ERROR"){try{return await e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function s(e,t,r="SYNC_ERROR",s=null){try{return e()}catch(e){return n.getInstance().createModuleErrorHandler(t)(r,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var o=Object.freeze({__proto__:null,ErrorHandler:n,UniAppToolsError:t,safeAsync:r,safeSync:s});function a(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const r={name:e,startTime:a(),module:t,metadata:n};this.metrics.set(e,r)}end(e){const t=this.metrics.get(e);return t?(t.endTime=a(),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 r=`${n.module}.${n.name}`;t[r]||(t[r]={total:0,count:0}),t[r].total+=n.duration||0,t[r].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const r=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:r,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function i(e){return function(t,n,r){const s=r.value;r.value=function(...r){const o=c.getInstance(),a=`${t.constructor.name}.${n}`;o.start(a,e,{args:r.length});try{const e=s.apply(this,r);return e instanceof Promise?e.finally(()=>{o.end(a)}):(o.end(a),e)}catch(e){throw o.end(a),e}}}}var u=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:i});class l{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return l.instance||(l.instance=new l),l.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 f=l.getInstance(),p=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=f.get(n);if(e)return t.end("getWindowInfo"),e}const r=s(()=>{const t=uni.getWindowInfo();return e&&f.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},d=()=>{const e="platform",t=f.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",f.set(e,"h5"),"h5"},m=()=>{try{const e=p();return e?.statusBarHeight||0}catch(e){return 0}},h=()=>{try{const e=d();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},g=()=>{try{const e=m(),t=d();if("weixin"===t||"alipay"===t){const t=h();if(t){return t.height+e}}return e+0}catch(e){return m()+0}};function w(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function y(e,t){return Object.assign(e,t)}function x(e,t,n=!1){let r,s=null;const o=function(...o){const a=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(r=e.apply(this,o))},t),a&&(r=e.apply(this,o)),r};return o.cancel=()=>{s&&(clearTimeout(s),s=null)},o}const S=e.areaList,E=e.useCascaderAreaData;const v=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})};function T(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function P(e){return new Promise(t=>{const n=T(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function C(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return void n(!1);const o=setTimeout(()=>{n(!1)},s);uni.navigateBack({delta:r,success:()=>{clearTimeout(o),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(o),n(!1)}})})}const R=x(C,300);async function I(e){return new Promise(t=>{const n=T(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const M={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class A{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return A.instance||(A.instance=new A),A.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const r={value:t,timestamp:Date.now(),ttl:n.ttl},s=JSON.stringify(r);if(s.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,s),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,r),!0}catch(e){throw e}}get(e,t){try{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}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const r=JSON.parse(n);let s;return s=r&&"object"==typeof r&&"value"in r&&"timestamp"in r?r:{value:r,timestamp:Date.now()},this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const b=A.getInstance();function O(e,t,n={}){return b.set(e,t,n)}function _(e,t){return b.get(e,t)}function D(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function k(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function j(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function U(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!D(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(r&&r.length>0){const t=r.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${r.join(", ")}`}}return{success:!0,files:e}}async function W(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:r}=e;return new Promise(s=>{if("undefined"==typeof document)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const o=document.createElement("input");o.type="file",o.multiple=n>1,"image"===t?o.accept="image/*":r&&r.length>0&&(o.accept=r.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),o.onchange=t=>{const n=t.target,r=n?.files;if(!r||0===r.length)return s({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(o);const a=U(Array.from(r).map((e,t)=>{const n=k(e.name),r=URL.createObjectURL(e);return{id:j(t),name:e.name,size:e.size,path:r,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);s(a),document.body.removeChild(o)},o.style.display="none",document.body.appendChild(o),o.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(r=>{const s="undefined"==typeof uni?null:uni;if(!s)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const o=e=>{r({success:!1,files:[],message:e?.errMsg||"选择文件失败"})};"image"!==t||"function"!=typeof s.chooseImage?"function"!=typeof s.chooseMessageFile?"function"!=typeof s.chooseFile?r({success:!1,files:[],message:"当前平台不支持文件选择"}):s.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:j(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:"app",raw:e}});r(U(n,e))},fail:o}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=k(e.name||e.path);return{id:j(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:"weixin",raw:e}});r(U(n,e))},fail:o}):s.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=k(e.path);return{id:j(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:"weixin",raw:e}});r(U(n,e))},fail:o})})}(e)}async function B(e,t,n){const{url:r,maxUploadFileSizeMB:s,showToast:o=!0,beforeUpload:a}=t;if("function"==typeof a){if(!await Promise.resolve(a(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return o&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const c=D(e.size,s);return c.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:c=!0,successMessage:i="上传成功",failMessage:u="上传失败",onProgress:l}=t;return new Promise(t=>{const f=e.raw;if(!(f&&f instanceof File)){const n="H5 环境缺少原生文件对象";return c&&v(n,!1,"error"),void t({file:e,success:!1,message:n})}const p=new XMLHttpRequest,d=new FormData;d.append(s,f,e.name),o&&Object.keys(o).forEach(e=>{d.append(e,String(o[e]))}),l&&p.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),p.addEventListener("load",()=>{const r=p.status,s=r>=200&&r<300;let o=p.responseText;try{o=JSON.parse(p.responseText)}catch{}if(s)c&&1===n&&v(i,!1,"success"),t({file:e,success:!0,statusCode:r,data:o});else{const n=`上传失败,状态码:${r}`;c&&v(n,!1,"error"),t({file:e,success:!1,statusCode:r,data:o,message:n})}}),p.addEventListener("error",()=>{const n=u;c&&v(n,!1,"error"),t({file:e,success:!1,message:n})}),p.addEventListener("abort",()=>{t({file:e,success:!1,message:"上传已取消"})}),p.open("POST",r),a&&Object.keys(a).forEach(e=>{p.setRequestHeader(e,a[e])}),p.send(d)})}(e,t,n):function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:c=!0,successMessage:i="上传成功",failMessage:u="上传失败",onProgress:l}=t,f="undefined"==typeof uni?null:uni;if(!f||"function"!=typeof f.uploadFile){const t="当前环境不支持文件上传";return c&&v(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const p=f.uploadFile({url:r,filePath:e.path,name:s,formData:o,header:a,success:r=>{let s=r.data;try{s=JSON.parse(r.data)}catch{}const o=r.statusCode;if(o>=200&&o<300)c&&1===n&&v(i,!1,"success"),t({file:e,success:!0,statusCode:o,data:s});else{const n=`上传失败,状态码:${o}`;c&&v(n,!1,"error"),t({file:e,success:!1,statusCode:o,data:s,message:n})}},fail:n=>{const r=n?.errMsg||u;c&&v(r,!1,"error"),t({file:e,success:!1,message:r})}});l&&p&&"function"==typeof p.onProgressUpdate&&p.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(o&&c.message&&v(c.message,!1,"error"),Promise.resolve({file:e,success:!1,message:c.message}))}async function F(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await W(e);if(!r.success){const e=r.message||n;return t&&e&&v(e,!1,"error"),[{file:null,success:!1,message:e}]}const s=r.files;if(0===s.length)return[];const o=s.length;return await async function(e,t,n){const r=new Array(e.length),s=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let o=0;const a=async()=>{for(;;){const s=o;if(s>=e.length)break;o+=1;const a=e[s],c=await B(a,t,n);r[s]=c}},c=[];for(let e=0;e<s;e+=1)c.push(a());return await Promise.all(c),r}(s,e,o)}catch(e){const r=n;return t&&r&&v(r,!1,"error"),[{file:null,success:!1,message:r}]}}const H=()=>{const e=c.getInstance();e.start("isWechat","system");const t=s(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},L=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const r=s=>{const o=document.createElement("script");o.src=s,o.async=!0,o.onload=()=>{e(!0)},o.onerror=()=>{n++,n<t.length?(document.head.removeChild(o),r(t[n])):(document.head.removeChild(o),e(!1))},document.head.appendChild(o)};r(t[n]),e(!1)}),N=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!H())return!1;return!!await L()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},$=e=>{s(()=>{window.wx&&H()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},z=e=>{s(()=>{window.wx&&H()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class J{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return J.instance||(J.instance=new J),J.instance}async init(e){return this.config=e,this.isConfigured=await N(e),this.isConfigured}isReady(){return this.isConfigured&&H()}getConfig(){return this.config}setShareData(e){this.isReady()&&($(e),z(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=c,exports.UniAppToolsError=t,exports.VERSION="2.0.0",exports.WechatSDK=J,exports.areaList=S,exports.batchGetStorage=function(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=_(e)}),t.end("batchGetStorage"),n},exports.batchSetStorage=function(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let r=0;return Object.entries(e).forEach(([e,n])=>{O(e,n,t)&&r++}),n.end("batchSetStorage"),r},exports.checkWechatJSAPI=e=>new Promise(t=>{window.wx&&H()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),exports.cleanExpiredStorage=function(){return b.cleanExpired()},exports.clearStorageSync=function(e){return e?b.remove(e):b.clear()},exports.configWechatJSSDK=N,exports.copyText=async function(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...M,...t};if(!e||"string"!=typeof e)return s.showToast&&v("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return s.showToast&&v("复制内容过长",!1,"error"),n.end("copyText"),!1;const o=await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{s.showToast&&v(s.successMessage),t(!0)},fail:()=>{s.showToast&&v(s.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),o},exports.debounce=x,exports.deepClone=w,exports.deepMerge=function(e,t){const n=w(e);return function e(t,n){for(const r in n)if(n.hasOwnProperty(r)){const s=n[r],o=t[r];s&&"object"==typeof s&&!Array.isArray(s)&&o&&"object"==typeof o&&!Array.isArray(o)?e(o,s):t[r]=w(s)}}(n,t),n},exports.extractUrlParts=function(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,r={};return t.searchParams.forEach((e,t)=>{r[t]=e}),{path:n,params:r}}catch(e){return{path:"",params:{}}}},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=function(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}},exports.getH5UrlParams=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(r){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}},exports.getMenuButtonBoundingClientRect=h,exports.getNavHeight=g,exports.getPageStack=function(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}},exports.getPlatform=d,exports.getStatusBarHeight=m,exports.getStorage=async function(e,t){return await r(()=>new Promise(n=>{n(_(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return b.getInfo()},exports.getStorageSync=_,exports.getTopNavBarHeight=()=>{try{const e=m();return{statusBarHeight:e,navHeight:g()}}catch(e){return{statusBarHeight:0,navHeight:44}}},exports.initUniAppTools=async function(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:r=null,performanceReportInterval:s=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof r?t.onError(r):t.onError(e=>{})}if(t&&s>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return u}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},s)}},exports.isWechat=H,exports.loadWechatJSSDK=L,exports.measurePerformance=i,exports.mergeObjects=y,exports.navigateTo=P,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=I,exports.redirectTo=async function(e){return new Promise(t=>{const n=T(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.safeAsync=r,exports.safeNavigateTo=async function(e,t=3){for(let n=0;n<t;n++){if(await P(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=s,exports.selectAndUpload=F,exports.selectAndUploadImage=async function(e){return F({...e,type:"image"})},exports.setPageIcon=(e,t="image/x-icon")=>s(()=>{const n=d();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=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),exports.setStorage=async function(e,t,n={}){return await r(()=>new Promise(r=>{r(O(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=O,exports.shareToFriend=z,exports.shareToTimeline=$,exports.switchTab=async function(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})},exports.throttle=function(e,t,n={}){let r,s=null,o=0;const{leading:a=!0,trailing:c=!0}=n,i=function(...n){const i=Date.now();o||a||(o=i);const u=t-(i-o);return u<=0||u>t?(s&&(clearTimeout(s),s=null),o=i,r=e.apply(this,n)):!s&&c&&(s=setTimeout(()=>{o=a?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return i.cancel=()=>{s&&(clearTimeout(s),s=null),o=0},i},exports.useBack=C,exports.useBackDebounced=R,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await C(e,t);const s=t.homePage||"pages/index/index",o=s.startsWith("/")?s:`/${s}`;return await I({url:o,params:t.homeParams})},exports.useCascaderAreaData=E,exports.useDeepCopyByObj=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return y(e,w(t))}return w(t)},exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=v,exports.useTryCatch=function(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}},exports.useWindowInfo=p,exports.weChatOfficialAccountPayment=(e,t,n)=>{const r=c.getInstance();return r.start("weChatOfficialAccountPayment","payment"),new Promise(o=>{s(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function s(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){r.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),o(!0)):(n?.(e),o(!1))})}catch(e){r.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),o(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",s,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",s),e.attachEvent("onWeixinJSBridgeReady",s))}else s();return!0},"payment","WECHAT_PAY_ERROR",!1)||(r.end("weChatOfficialAccountPayment"),o(!1))})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{areaList as e,useCascaderAreaData as t}from"@vant/area-data";class n 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 r{static instance;errorCallbacks=[];static getInstance(){return r.instance||(r.instance=new r),r.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,t){const r={code:e instanceof n?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof n?e.module:t,timestamp:e instanceof n?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){}})}createModuleErrorHandler(e){return(t,r,s)=>{const a=new n(t,r,e);return s&&(a.stack=s.stack),this.handleError(a,e),a}}}async function s(e,t,n="ASYNC_ERROR"){try{return await e()}catch(e){return r.getInstance().createModuleErrorHandler(t)(n,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function a(e,t,n="SYNC_ERROR",s=null){try{return e()}catch(e){return r.getInstance().createModuleErrorHandler(t)(n,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var o=Object.freeze({__proto__:null,ErrorHandler:r,UniAppToolsError:n,safeAsync:s,safeSync:a});function i(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const r={name:e,startTime:i(),module:t,metadata:n};this.metrics.set(e,r)}end(e){const t=this.metrics.get(e);return t?(t.endTime=i(),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 r=`${n.module}.${n.name}`;t[r]||(t[r]={total:0,count:0}),t[r].total+=n.duration||0,t[r].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const r=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:r,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function u(e){return function(t,n,r){const s=r.value;r.value=function(...r){const a=c.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:r.length});try{const e=s.apply(this,r);return e instanceof Promise?e.finally(()=>{a.end(o)}):(a.end(o),e)}catch(e){throw a.end(o),e}}}}var l=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:u});class f{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return f.instance||(f.instance=new f),f.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 m=f.getInstance(),d=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=m.get(n);if(e)return t.end("getWindowInfo"),e}const r=a(()=>{const t=uni.getWindowInfo();return e&&m.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},h=()=>{const e="platform",t=m.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",m.set(e,"h5"),"h5"},p=()=>{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}}},g=()=>{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){}},w=()=>{try{const e=d();return e?.statusBarHeight||0}catch(e){return 0}},y=()=>{try{const e=h();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},S=()=>{try{const e=w(),t=h();if("weixin"===t||"alipay"===t){const t=y();if(t){return t.height+e}}return e+0}catch(e){return w()+0}},E=()=>{try{const e=w();return{statusBarHeight:e,navHeight:S()}}catch(e){return{statusBarHeight:0,navHeight:44}}},v=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),x=(e,t="image/x-icon")=>a(()=>{const n=h();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);function R(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function T(e,t){return Object.assign(e,t)}function P(e,t){const n=R(e);return function e(t,n){for(const r in n)if(n.hasOwnProperty(r)){const s=n[r],a=t[r];s&&"object"==typeof s&&!Array.isArray(s)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,s):t[r]=R(s)}}(n,t),n}function C(e,t,n=!1){let r,s=null;const a=function(...a){const o=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(r=e.apply(this,a))},t),o&&(r=e.apply(this,a)),r};return a.cancel=()=>{s&&(clearTimeout(s),s=null)},a}function I(e,t,n={}){let r,s=null,a=0;const{leading:o=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();a||o||(a=c);const u=t-(c-a);return u<=0||u>t?(s&&(clearTimeout(s),s=null),a=c,r=e.apply(this,n)):!s&&i&&(s=setTimeout(()=>{a=o?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return c.cancel=()=>{s&&(clearTimeout(s),s=null),a=0},c}function M(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return T(e,R(t))}return R(t)}const _=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(r){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}};function A(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,r={};return t.searchParams.forEach((e,t)=>{r[t]=e}),{path:n,params:r}}catch(e){return{path:"",params:{}}}}function b(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}}const O=e,k=t;function D(){return t()}const j=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})};function z(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function $(e){return new Promise(t=>{const n=z(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function W(e){return new Promise(t=>{const n=z(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function F(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return void n(!1);const a=setTimeout(()=>{n(!1)},s);uni.navigateBack({delta:r,success:()=>{clearTimeout(a),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(a),n(!1)}})})}async function U(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await F(e,t);const s=t.homePage||"pages/index/index",a=s.startsWith("/")?s:`/${s}`;return await B({url:a,params:t.homeParams})}const N=C(F,300);async function L(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})}async function B(e){return new Promise(t=>{const n=z(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function H(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}}function J(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}}async function q(e,t=3){for(let n=0;n<t;n++){if(await $(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1}const G={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function Y(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const r={...G,...t};if(!e||"string"!=typeof e)return r.showToast&&j("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return r.showToast&&j("复制内容过长",!1,"error"),n.end("copyText"),!1;const a=await s(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{r.showToast&&j(r.successMessage),t(!0)},fail:()=>{r.showToast&&j(r.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),a}class K{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return K.instance||(K.instance=new K),K.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const r={value:t,timestamp:Date.now(),ttl:n.ttl},s=JSON.stringify(r);if(s.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,s),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,r),!0}catch(e){throw e}}get(e,t){try{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}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const r=JSON.parse(n);let s;return s=r&&"object"==typeof r&&"value"in r&&"timestamp"in r?r:{value:r,timestamp:Date.now()},this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const V=K.getInstance();function X(e,t,n={}){return V.set(e,t,n)}function Q(e,t){return V.get(e,t)}function Z(e){return e?V.remove(e):V.clear()}async function ee(e,t,n={}){return await s(()=>new Promise(r=>{r(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function te(e,t){return await s(()=>new Promise(n=>{n(Q(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ne(){return V.getInfo()}function re(){return V.cleanExpired()}function se(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let r=0;return Object.entries(e).forEach(([e,n])=>{X(e,n,t)&&r++}),n.end("batchSetStorage"),r}function ae(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=Q(e)}),t.end("batchGetStorage"),n}function oe(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function ie(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function ce(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function ue(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!oe(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(r&&r.length>0){const t=r.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${r.join(", ")}`}}return{success:!0,files:e}}async function le(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:r}=e;return new Promise(s=>{if("undefined"==typeof document)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const a=document.createElement("input");a.type="file",a.multiple=n>1,"image"===t?a.accept="image/*":r&&r.length>0&&(a.accept=r.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),a.onchange=t=>{const n=t.target,r=n?.files;if(!r||0===r.length)return s({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(a);const o=ue(Array.from(r).map((e,t)=>{const n=ie(e.name),r=URL.createObjectURL(e);return{id:ce(t),name:e.name,size:e.size,path:r,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);s(o),document.body.removeChild(a)},a.style.display="none",document.body.appendChild(a),a.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(r=>{const s="undefined"==typeof uni?null:uni;if(!s)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const a=e=>{r({success:!1,files:[],message:e?.errMsg||"选择文件失败"})};"image"!==t||"function"!=typeof s.chooseImage?"function"!=typeof s.chooseMessageFile?"function"!=typeof s.chooseFile?r({success:!1,files:[],message:"当前平台不支持文件选择"}):s.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=ie(e.path);return{id:ce(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:"app",raw:e}});r(ue(n,e))},fail:a}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=ie(e.name||e.path);return{id:ce(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:"weixin",raw:e}});r(ue(n,e))},fail:a}):s.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=ie(e.path);return{id:ce(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:"weixin",raw:e}});r(ue(n,e))},fail:a})})}(e)}async function fe(e,t,n){const{url:r,fieldName:s="file",formData:a,headers:o,maxUploadFileSizeMB:i,showToast:c=!0,successMessage:u="上传成功",failMessage:l="上传失败",onProgress:f,beforeUpload:m}=t;if("function"==typeof m){if(!await Promise.resolve(m(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return c&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const d=oe(e.size,i);if(!d.valid)return c&&d.message&&j(d.message,!1,"error"),Promise.resolve({file:e,success:!1,message:d.message});const h="undefined"==typeof uni?null:uni;if(!h||"function"!=typeof h.uploadFile){const t="当前环境不支持文件上传";return c&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const i=h.uploadFile({url:r,filePath:e.path,name:s,formData:a,header:o,success:r=>{let s=r.data;try{s=JSON.parse(r.data)}catch{}const a=r.statusCode;if(a>=200&&a<300)c&&1===n&&j(u,!1,"success"),t({file:e,success:!0,statusCode:a,data:s});else{const n=`上传失败,状态码:${a}`;c&&j(n,!1,"error"),t({file:e,success:!1,statusCode:a,data:s,message:n})}},fail:n=>{const r=n?.errMsg||l;c&&j(r,!1,"error"),t({file:e,success:!1,message:r})}});f&&i&&"function"==typeof i.onProgressUpdate&&i.onProgressUpdate(t=>{f(e,t.progress)})})}async function me(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await le(e);if(!r.success){const e=r.message||n;return t&&e&&j(e,!1,"error"),[{file:null,success:!1,message:e}]}const s=r.files;if(0===s.length)return[];const a=s.length;return await async function(e,t,n){const r=new Array(e.length),s=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let a=0;const o=async()=>{for(;;){const s=a;if(s>=e.length)break;a+=1;const o=e[s],i=await fe(o,t,n);r[s]=i}},i=[];for(let e=0;e<s;e+=1)i.push(o());return await Promise.all(i),r}(s,e,a)}catch(e){const r=n;return t&&r&&j(r,!1,"error"),[{file:null,success:!1,message:r}]}}async function de(e){return me({...e,type:"image"})}const he=(e,t,n)=>{const r=c.getInstance();return r.start("weChatOfficialAccountPayment","payment"),new Promise(s=>{a(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function a(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){r.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),s(!0)):(n?.(e),s(!1))})}catch(e){r.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),s(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",a,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",a),e.attachEvent("onWeixinJSBridgeReady",a))}else a();return!0},"payment","WECHAT_PAY_ERROR",!1)||(r.end("weChatOfficialAccountPayment"),s(!1))})},pe=()=>{const e=c.getInstance();e.start("isWechat","system");const t=a(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},ge=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const r=s=>{const a=document.createElement("script");a.src=s,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),r(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};r(t[n]),e(!1)}),we=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!pe())return!1;return!!await ge()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},ye=e=>new Promise(t=>{window.wx&&pe()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),Se=e=>{a(()=>{window.wx&&pe()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},Ee=e=>{a(()=>{window.wx&&pe()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class ve{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return ve.instance||(ve.instance=new ve),ve.instance}async init(e){return this.config=e,this.isConfigured=await we(e),this.isConfigured}isReady(){return this.isConfigured&&pe()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Se(e),Ee(e))}}const xe="2.0.0";async function Re(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:r=null,performanceReportInterval:s=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof r?t.onError(r):t.onError(e=>{})}if(t&&s>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return l}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},s)}}export{r as ErrorHandler,c as PerformanceMonitor,n as UniAppToolsError,xe as VERSION,ve as WechatSDK,O as areaList,ae as batchGetStorage,se as batchSetStorage,ye as checkWechatJSAPI,re as cleanExpiredStorage,Z as clearStorageSync,we as configWechatJSSDK,Y as copyText,C as debounce,R as deepClone,P as deepMerge,A as extractUrlParts,p as getCurrentEnv,H as getCurrentPageInfo,_ as getH5UrlParams,y as getMenuButtonBoundingClientRect,S as getNavHeight,J as getPageStack,h as getPlatform,w as getStatusBarHeight,te as getStorage,ne as getStorageInfo,Q as getStorageSync,E as getTopNavBarHeight,Re as initUniAppTools,pe as isWechat,ge as loadWechatJSSDK,u as measurePerformance,T as mergeObjects,$ as navigateTo,g as onCheckForUpdate,B as reLaunch,W as redirectTo,s as safeAsync,q as safeNavigateTo,a as safeSync,me as selectAndUpload,de as selectAndUploadImage,x as setPageIcon,v as setPageTitle,ee as setStorage,X as setStorageSync,Ee as shareToFriend,Se as shareToTimeline,L as switchTab,I as throttle,F as useBack,N as useBackDebounced,U as useBackOrHome,k as useCascaderAreaData,M as useDeepCopyByObj,D as useRegions,j as useToast,b as useTryCatch,d as useWindowInfo,he as weChatOfficialAccountPayment};
|
|
1
|
+
import{areaList as e,useCascaderAreaData as t}from"@vant/area-data";class n 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 r{static instance;errorCallbacks=[];static getInstance(){return r.instance||(r.instance=new r),r.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,t){const r={code:e instanceof n?e.code:"UNKNOWN_ERROR",message:e.message,module:e instanceof n?e.module:t,timestamp:e instanceof n?e.timestamp:Date.now(),stack:e.stack};this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){}})}createModuleErrorHandler(e){return(t,r,s)=>{const a=new n(t,r,e);return s&&(a.stack=s.stack),this.handleError(a,e),a}}}async function s(e,t,n="ASYNC_ERROR"){try{return await e()}catch(e){return r.getInstance().createModuleErrorHandler(t)(n,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function a(e,t,n="SYNC_ERROR",s=null){try{return e()}catch(e){return r.getInstance().createModuleErrorHandler(t)(n,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),s}}var o=Object.freeze({__proto__:null,ErrorHandler:r,UniAppToolsError:n,safeAsync:s,safeSync:a});function i(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}class c{static instance;metrics=new Map;completedMetrics=[];maxStoredMetrics=100;static getInstance(){return c.instance||(c.instance=new c),c.instance}start(e,t,n){const r={name:e,startTime:i(),module:t,metadata:n};this.metrics.set(e,r)}end(e){const t=this.metrics.get(e);return t?(t.endTime=i(),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 r=`${n.module}.${n.name}`;t[r]||(t[r]={total:0,count:0}),t[r].total+=n.duration||0,t[r].count+=1});const n={};Object.entries(t).forEach(([e,t])=>{n[e]=t.total/t.count});const r=[...this.completedMetrics].sort((e,t)=>(t.duration||0)-(e.duration||0)).slice(0,10);return{byModule:e,slowest:r,average:n}}clear(){this.metrics.clear(),this.completedMetrics=[]}}function u(e){return function(t,n,r){const s=r.value;r.value=function(...r){const a=c.getInstance(),o=`${t.constructor.name}.${n}`;a.start(o,e,{args:r.length});try{const e=s.apply(this,r);return e instanceof Promise?e.finally(()=>{a.end(o)}):(a.end(o),e)}catch(e){throw a.end(o),e}}}}var l=Object.freeze({__proto__:null,PerformanceMonitor:c,measurePerformance:u});class f{static instance;cache=new Map;defaultTTL=3e4;static getInstance(){return f.instance||(f.instance=new f),f.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 d=f.getInstance(),m=(e=!0)=>{const t=c.getInstance();t.start("getWindowInfo","system");const n="windowInfo";if(e){const e=d.get(n);if(e)return t.end("getWindowInfo"),e}const r=a(()=>{const t=uni.getWindowInfo();return e&&d.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),r},h=()=>{const e="platform",t=d.get(e);if(t)return t;let n="unknown";return n="weixin",n="web",n="app",n="alipay",n="h5",d.set(e,"h5"),"h5"},p=()=>{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}}},g=()=>{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){}},w=()=>{try{const e=m();return e?.statusBarHeight||0}catch(e){return 0}},y=()=>{try{const e=h();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},S=()=>{try{const e=w(),t=h();if("weixin"===t||"alipay"===t){const t=y();if(t){return t.height+e}}return e+0}catch(e){return w()+0}},E=()=>{try{const e=w();return{statusBarHeight:e,navHeight:S()}}catch(e){return{statusBarHeight:0,navHeight:44}}},v=e=>e&&"string"==typeof e?new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{t(!1)}})}catch(e){t(!1)}}):Promise.resolve(!1),x=(e,t="image/x-icon")=>a(()=>{const n=h();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);function T(e){if(null===e||"object"!=typeof e)return e;try{if("undefined"!=typeof structuredClone)try{return structuredClone(e)}catch(e){}return JSON.parse(JSON.stringify(e))}catch(e){throw new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function R(e,t){return Object.assign(e,t)}function P(e,t){const n=T(e);return function e(t,n){for(const r in n)if(n.hasOwnProperty(r)){const s=n[r],a=t[r];s&&"object"==typeof s&&!Array.isArray(s)&&a&&"object"==typeof a&&!Array.isArray(a)?e(a,s):t[r]=T(s)}}(n,t),n}function C(e,t,n=!1){let r,s=null;const a=function(...a){const o=n&&!s;return s&&clearTimeout(s),s=setTimeout(()=>{s=null,n||(r=e.apply(this,a))},t),o&&(r=e.apply(this,a)),r};return a.cancel=()=>{s&&(clearTimeout(s),s=null)},a}function M(e,t,n={}){let r,s=null,a=0;const{leading:o=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();a||o||(a=c);const u=t-(c-a);return u<=0||u>t?(s&&(clearTimeout(s),s=null),a=c,r=e.apply(this,n)):!s&&i&&(s=setTimeout(()=>{a=o?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return c.cancel=()=>{s&&(clearTimeout(s),s=null),a=0},c}function I(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){return R(e,T(t))}return T(t)}const _=e=>{try{if("undefined"==typeof window||!window.location)throw new Error("不在 H5 浏览器环境中");const t=new URLSearchParams(window.location.search),n={};return t.forEach((e,t)=>{try{n[t]=decodeURIComponent(e)}catch(r){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}};function b(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,r={};return t.searchParams.forEach((e,t)=>{r[t]=e}),{path:n,params:r}}catch(e){return{path:"",params:{}}}}function A(e,t={}){return async(...n)=>{try{return{data:await e(...n),error:null}}catch(e){return t.onError?.(e),{data:null,error:e}}finally{t.onFinally?.()}}}const O=e,k=t;function D(){return t()}const j=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})};function $(e,t){if(!t||0===Object.keys(t).length)return e;const n=Object.entries(t).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");return e+(e.includes("?")?"&":"?")+n}async function z(e){return new Promise(t=>{const n=$(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{t(!1)}})})}async function F(e){return new Promise(t=>{const n=$(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function L(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return void n(!1);const a=setTimeout(()=>{n(!1)},s);uni.navigateBack({delta:r,success:()=>{clearTimeout(a),setTimeout(()=>{try{const t=getCurrentPages();if(t.length>0){const n=t[t.length-1];n.$vm&&"function"==typeof n.$vm.init&&n.$vm.init(e)}n(!0)}catch(e){n(!0)}},100)},fail:e=>{clearTimeout(a),n(!1)}})})}async function N(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await L(e,t);const s=t.homePage||"pages/index/index",a=s.startsWith("/")?s:`/${s}`;return await H({url:a,params:t.homeParams})}const W=C(L,300);async function U(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:e=>{t(!1)}})})}async function H(e){return new Promise(t=>{const n=$(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function B(){try{const e=getCurrentPages();if(0===e.length)return null;const t=e[e.length-1];return{route:t.route||"",options:t.options||{}}}catch(e){return null}}function J(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}}async function q(e,t=3){for(let n=0;n<t;n++){if(await z(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1}const G={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function Y(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const r={...G,...t};if(!e||"string"!=typeof e)return r.showToast&&j("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return r.showToast&&j("复制内容过长",!1,"error"),n.end("copyText"),!1;const a=await s(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{r.showToast&&j(r.successMessage),t(!0)},fail:()=>{r.showToast&&j(r.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),a}class K{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return K.instance||(K.instance=new K),K.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,n={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const r={value:t,timestamp:Date.now(),ttl:n.ttl},s=JSON.stringify(r);if(s.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,s),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,r),!0}catch(e){throw e}}get(e,t){try{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}const n=uni.getStorageSync(e);if(!n||"string"!=typeof n)return t;const r=JSON.parse(n);let s;return s=r&&"object"==typeof r&&"value"in r&&"timestamp"in r?r:{value:r,timestamp:Date.now()},this.isExpired(s)?(this.remove(e),t):(this.cache.set(e,s),s.value)}catch(e){return t}}remove(e){try{return!(!e||"string"!=typeof e)&&(uni.removeStorageSync(e),this.cache.delete(e),!0)}catch(e){return!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return{keys:[],currentSize:0,limitSize:0}}}cleanExpired(){try{const e=this.getInfo();let t=0;return e.keys.forEach(e=>{void 0===this.get(e)&&t++}),t}catch(e){return 0}}}const V=K.getInstance();function X(e,t,n={}){return V.set(e,t,n)}function Q(e,t){return V.get(e,t)}function Z(e){return e?V.remove(e):V.clear()}async function ee(e,t,n={}){return await s(()=>new Promise(r=>{r(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function te(e,t){return await s(()=>new Promise(n=>{n(Q(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ne(){return V.getInfo()}function re(){return V.cleanExpired()}function se(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let r=0;return Object.entries(e).forEach(([e,n])=>{X(e,n,t)&&r++}),n.end("batchSetStorage"),r}function ae(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=Q(e)}),t.end("batchGetStorage"),n}function oe(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function ie(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function ce(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function ue(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!oe(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(r&&r.length>0){const t=r.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${r.join(", ")}`}}return{success:!0,files:e}}async function le(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:r}=e;return new Promise(s=>{if("undefined"==typeof document)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const a=document.createElement("input");a.type="file",a.multiple=n>1,"image"===t?a.accept="image/*":r&&r.length>0&&(a.accept=r.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),a.onchange=t=>{const n=t.target,r=n?.files;if(!r||0===r.length)return s({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(a);const o=ue(Array.from(r).map((e,t)=>{const n=ie(e.name),r=URL.createObjectURL(e);return{id:ce(t),name:e.name,size:e.size,path:r,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);s(o),document.body.removeChild(a)},a.style.display="none",document.body.appendChild(a),a.click()})}(e):function(e){const{type:t="image",count:n=1}=e;return new Promise(r=>{const s="undefined"==typeof uni?null:uni;if(!s)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const a=e=>{r({success:!1,files:[],message:e?.errMsg||"选择文件失败"})};"image"!==t||"function"!=typeof s.chooseImage?"function"!=typeof s.chooseMessageFile?"function"!=typeof s.chooseFile?r({success:!1,files:[],message:"当前平台不支持文件选择"}):s.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=ie(e.path);return{id:ce(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:"app",raw:e}});r(ue(n,e))},fail:a}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=ie(e.name||e.path);return{id:ce(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:"weixin",raw:e}});r(ue(n,e))},fail:a}):s.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=ie(e.path);return{id:ce(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:"weixin",raw:e}});r(ue(n,e))},fail:a})})}(e)}async function fe(e,t,n){const{url:r,maxUploadFileSizeMB:s,showToast:a=!0,beforeUpload:o}=t;if("function"==typeof o){if(!await Promise.resolve(o(e)))return{file:e,success:!1,message:"已取消上传"}}if(!r){const t="上传地址不能为空";return a&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const i=oe(e.size,s);return i.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:r,fieldName:s="file",formData:a,headers:o,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l}=t;return new Promise(t=>{const f=e.raw;if(!(f&&f instanceof File)){const n="H5 环境缺少原生文件对象";return i&&j(n,!1,"error"),void t({file:e,success:!1,message:n})}const d=new XMLHttpRequest,m=new FormData;m.append(s,f,e.name),a&&Object.keys(a).forEach(e=>{m.append(e,String(a[e]))}),l&&d.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),d.addEventListener("load",()=>{const r=d.status,s=r>=200&&r<300;let a=d.responseText;try{a=JSON.parse(d.responseText)}catch{}if(s)i&&1===n&&j(c,!1,"success"),t({file:e,success:!0,statusCode:r,data:a});else{const n=`上传失败,状态码:${r}`;i&&j(n,!1,"error"),t({file:e,success:!1,statusCode:r,data:a,message:n})}}),d.addEventListener("error",()=>{const n=u;i&&j(n,!1,"error"),t({file:e,success:!1,message:n})}),d.addEventListener("abort",()=>{t({file:e,success:!1,message:"上传已取消"})}),d.open("POST",r),o&&Object.keys(o).forEach(e=>{d.setRequestHeader(e,o[e])}),d.send(m)})}(e,t,n):function(e,t,n){const{url:r,fieldName:s="file",formData:a,headers:o,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l}=t,f="undefined"==typeof uni?null:uni;if(!f||"function"!=typeof f.uploadFile){const t="当前环境不支持文件上传";return i&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{const d=f.uploadFile({url:r,filePath:e.path,name:s,formData:a,header:o,success:r=>{let s=r.data;try{s=JSON.parse(r.data)}catch{}const a=r.statusCode;if(a>=200&&a<300)i&&1===n&&j(c,!1,"success"),t({file:e,success:!0,statusCode:a,data:s});else{const n=`上传失败,状态码:${a}`;i&&j(n,!1,"error"),t({file:e,success:!1,statusCode:a,data:s,message:n})}},fail:n=>{const r=n?.errMsg||u;i&&j(r,!1,"error"),t({file:e,success:!1,message:r})}});l&&d&&"function"==typeof d.onProgressUpdate&&d.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(a&&i.message&&j(i.message,!1,"error"),Promise.resolve({file:e,success:!1,message:i.message}))}async function de(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await le(e);if(!r.success){const e=r.message||n;return t&&e&&j(e,!1,"error"),[{file:null,success:!1,message:e}]}const s=r.files;if(0===s.length)return[];const a=s.length;return await async function(e,t,n){const r=new Array(e.length),s=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let a=0;const o=async()=>{for(;;){const s=a;if(s>=e.length)break;a+=1;const o=e[s],i=await fe(o,t,n);r[s]=i}},i=[];for(let e=0;e<s;e+=1)i.push(o());return await Promise.all(i),r}(s,e,a)}catch(e){const r=n;return t&&r&&j(r,!1,"error"),[{file:null,success:!1,message:r}]}}async function me(e){return de({...e,type:"image"})}const he=(e,t,n)=>{const r=c.getInstance();return r.start("weChatOfficialAccountPayment","payment"),new Promise(s=>{a(()=>{if("undefined"==typeof window||!window.navigator)throw new Error("不在浏览器环境中,无法调用微信支付");if(!(e&&e.appId&&e.timeStamp&&e.nonceStr&&e.package&&e.paySign))throw new Error("微信支付配置参数不完整");function a(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){r.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),s(!0)):(n?.(e),s(!1))})}catch(e){r.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),s(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",a,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",a),e.attachEvent("onWeixinJSBridgeReady",a))}else a();return!0},"payment","WECHAT_PAY_ERROR",!1)||(r.end("weChatOfficialAccountPayment"),s(!1))})},pe=()=>{const e=c.getInstance();e.start("isWechat","system");const t=a(()=>{if("undefined"!=typeof navigator&&navigator.userAgent){return navigator.userAgent.toLowerCase().includes("micromessenger")}return!1},"system","IS_WECHAT_ERROR",!1);return e.end("isWechat"),t||!1},ge=()=>new Promise(e=>{if("undefined"!=typeof window&&window.wx)return void e(!0);const t=["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];let n=0;const r=s=>{const a=document.createElement("script");a.src=s,a.async=!0,a.onload=()=>{e(!0)},a.onerror=()=>{n++,n<t.length?(document.head.removeChild(a),r(t[n])):(document.head.removeChild(a),e(!1))},document.head.appendChild(a)};r(t[n]),e(!1)}),we=async e=>{const t=c.getInstance();t.start("configWechatJSSDK","wechat");try{if(!pe())return!1;return!!await ge()&&new Promise(t=>{window.wx?(window.wx.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),window.wx.ready(()=>{t(!0)}),window.wx.error(e=>{t(!1)})):t(!1),t(!1)})}catch(e){return!1}finally{t.end("configWechatJSSDK")}},ye=e=>new Promise(t=>{window.wx&&pe()?window.wx.checkJsApi({jsApiList:e,success:e=>{t(e.checkResult||{})}}):t({}),t({})}),Se=e=>{a(()=>{window.wx&&pe()&&(window.wx.updateTimelineShareData?window.wx.updateTimelineShareData(e):window.wx.onMenuShareTimeline&&window.wx.onMenuShareTimeline(e))},"wechat","SHARE_TIMELINE_ERROR")},Ee=e=>{a(()=>{window.wx&&pe()&&(window.wx.updateAppMessageShareData?window.wx.updateAppMessageShareData(e):window.wx.onMenuShareAppMessage&&window.wx.onMenuShareAppMessage(e))},"wechat","SHARE_FRIEND_ERROR")};class ve{static instance;isConfigured=!1;config=null;constructor(){}static getInstance(){return ve.instance||(ve.instance=new ve),ve.instance}async init(e){return this.config=e,this.isConfigured=await we(e),this.isConfigured}isReady(){return this.isConfigured&&pe()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Se(e),Ee(e))}}const xe="2.0.0";async function Te(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:r=null,performanceReportInterval:s=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return o}),t=e.getInstance();"function"==typeof r?t.onError(r):t.onError(e=>{})}if(t&&s>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return l}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},s)}}export{r as ErrorHandler,c as PerformanceMonitor,n as UniAppToolsError,xe as VERSION,ve as WechatSDK,O as areaList,ae as batchGetStorage,se as batchSetStorage,ye as checkWechatJSAPI,re as cleanExpiredStorage,Z as clearStorageSync,we as configWechatJSSDK,Y as copyText,C as debounce,T as deepClone,P as deepMerge,b as extractUrlParts,p as getCurrentEnv,B as getCurrentPageInfo,_ as getH5UrlParams,y as getMenuButtonBoundingClientRect,S as getNavHeight,J as getPageStack,h as getPlatform,w as getStatusBarHeight,te as getStorage,ne as getStorageInfo,Q as getStorageSync,E as getTopNavBarHeight,Te as initUniAppTools,pe as isWechat,ge as loadWechatJSSDK,u as measurePerformance,R as mergeObjects,z as navigateTo,g as onCheckForUpdate,H as reLaunch,F as redirectTo,s as safeAsync,q as safeNavigateTo,a as safeSync,de as selectAndUpload,me as selectAndUploadImage,x as setPageIcon,v as setPageTitle,ee as setStorage,X as setStorageSync,Ee as shareToFriend,Se as shareToTimeline,U as switchTab,M as throttle,L as useBack,W as useBackDebounced,N as useBackOrHome,k as useCascaderAreaData,I as useDeepCopyByObj,D as useRegions,j as useToast,A as useTryCatch,m as useWindowInfo,he as weChatOfficialAccountPayment};
|