my-uniapp-tools 3.0.2 → 4.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 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},m=()=>{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"},d=()=>{try{const e=p();return e?.statusBarHeight||0}catch(e){return 0}},h=()=>{try{const e=m();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},g=()=>{try{const e=d(),t=m();if("weixin"===t||"alipay"===t){const t=h();if(t){return t.height+e}}return e+0}catch(e){return d()+0}};function y(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 w(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 x=e.areaList,S=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 E(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 P(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=w(P,300);async function M(e){return new Promise(t=>{const n=T(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}const R={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};class b{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return b.instance||(b.instance=new b),b.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 I=b.getInstance();function O(e,t,n={}){return I.set(e,t,n)}function A(e,t){return I.get(e,t)}function k(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function _(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function U(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function j(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n){if(e.some(e=>!U(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 L(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=j(Array.from(r).map((e,t)=>{const n=k(e.name),r=URL.createObjectURL(e);return{id:_(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=>{const t=function(e){const t=(e||"").trim();if(!t)return"选择文件失败";const n=t.toLowerCase();return n.includes("fail cancel")||n.includes("cancel")?"用户取消选择":/[\u4e00-\u9fff]/.test(t)?t:"选择文件失败"}(e?.errMsg);r({success:!1,files:[],message:t})},a=function(){let e="unknown";return e="h5",e="weixin",e="alipay",e="app","app"}();"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:_(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(j(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:_(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(j(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:_(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:a,raw:e}});r(j(n,e))},fail:o})})}(e)}async function D(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=U(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,uploadTimeoutMs:f,autoRevokeObjectURL:p=!1}=t;return new Promise(t=>{const m=e.raw;if(!(m&&m instanceof File)){const n="H5 环境缺少原生文件对象";return c&&v(n,!1,"none"),void t({file:e,success:!1,message:n})}const d=p&&"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&"string"==typeof e.path&&e.path.startsWith("blob:"),h=()=>{if(d)try{URL.revokeObjectURL(e.path)}catch{}},g=new XMLHttpRequest,y=new FormData;y.append(s,m,e.name),o&&Object.keys(o).forEach(e=>{y.append(e,String(o[e]))}),l&&g.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),g.addEventListener("load",()=>{const r=g.status,s=r>=200&&r<300;let o=g.responseText;try{o=JSON.parse(g.responseText)}catch{}if(s)c&&1===n&&v(i,!1,"none"),h(),t({file:e,success:!0,statusCode:r,data:o});else{const n=`上传失败,状态码:${r}`;c&&v(n,!1,"none"),h(),t({file:e,success:!1,statusCode:r,data:o,message:n})}}),g.addEventListener("error",()=>{const n=u;c&&v(n,!1,"none"),h(),t({file:e,success:!1,message:n})}),g.addEventListener("timeout",()=>{const n=f?`上传超时(${f}ms)`:"上传超时";c&&v(n,!1,"none"),h(),t({file:e,success:!1,message:n})}),g.addEventListener("abort",()=>{h(),t({file:e,success:!1,message:"上传已取消"})}),g.open("POST",r),"number"==typeof f&&f>0&&(g.timeout=f),a&&Object.keys(a).forEach(e=>{g.setRequestHeader(e,a[e])}),g.send(y)})}(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,uploadTimeoutMs:f}=t,p="undefined"==typeof uni?null:uni;if(!p||"function"!=typeof p.uploadFile){const t="当前环境不支持文件上传";return c&&v(t,!1,"none"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{let m=!1,d=null;const h=e=>{m||(m=!0,d&&(clearTimeout(d),d=null),t(e))};let g=null;"number"==typeof f&&f>0&&(d=setTimeout(()=>{try{g&&"function"==typeof g.abort&&g.abort()}catch{}const t=`上传超时(${f}ms)`;c&&v(t,!1,"none"),h({file:e,success:!1,message:t})},f)),g=p.uploadFile({url:r,filePath:e.path,name:s,formData:o,header:a,success:t=>{let r=t.data;try{r=JSON.parse(t.data)}catch{}const s=t.statusCode;if(s>=200&&s<300)c&&1===n&&v(i,!1,"none"),h({file:e,success:!0,statusCode:s,data:r});else{const t=`上传失败,状态码:${s}`;c&&v(t,!1,"none"),h({file:e,success:!1,statusCode:s,data:r,message:t})}},fail:t=>{const n=t?.errMsg||u;c&&v(n,!1,"none"),h({file:e,success:!1,message:n})}}),l&&g&&"function"==typeof g.onProgressUpdate&&g.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 N(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await L(e);if(!r.success){const e=r.message||n;return t&&e&&v(e,!1,"none"),[{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 D(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,"none"),[{file:null,success:!1,message:r}]}}const $=()=>!("undefined"==typeof navigator||!navigator.userAgent)&&navigator.userAgent.toLowerCase().includes("micromessenger"),B=()=>"undefined"!=typeof window&&"undefined"!=typeof document,F=()=>B()&&$()&&window.wx||null;let z=!1,W=null;const H=(e={})=>{const{timeoutMs:t=1e4}=e;if(z||B()&&window.wx)return z=!0,Promise.resolve(!0);if(!B())return Promise.resolve(!1);if(W)return W;const n=e.cdnUrls&&e.cdnUrls.length>0?e.cdnUrls:["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];return W=new Promise(e=>{let r=!1,s=null,o=null,a=0;const c=t=>{r||(r=!0,s&&(clearTimeout(s),s=null),o&&o.parentNode&&o.parentNode.removeChild(o),t&&(z=!0),W=null,e(t))},i=()=>{if(a>=n.length)return void c(!1);if(!document.head)return void c(!1);const e=n[a];a+=1;const t=document.createElement("script");o=t,t.src=e,t.async=!0,t.onload=()=>c(!0),t.onerror=()=>{t.parentNode&&t.parentNode.removeChild(t),o=null,i()},document.head.appendChild(t)};s=setTimeout(()=>{c(!1)},t),i()}),W};let J=null;const q=async(e,t={})=>{const{timeoutMs:n=1e4}=t;if(!$())return!1;if(J)return J;if(!await H({timeoutMs:n}))return!1;if(!B())return!1;const r=window.wx;return!!r&&(J=new Promise(t=>{let s=!1,o=null;const a=e=>{s||(s=!0,o&&(clearTimeout(o),o=null),J=null,t(e))};o=setTimeout(()=>a(!1),n);try{r.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),r.ready(()=>{a(!0)}),r.error(e=>{a(!1)})}catch(e){a(!1)}}),J)},G=e=>{const t=F();t&&(t.updateTimelineShareData?t.updateTimelineShareData(e):t.onMenuShareTimeline&&t.onMenuShareTimeline(e))},Y=e=>{const t=F();t&&(t.updateAppMessageShareData?t.updateAppMessageShareData(e):t.onMenuShareAppMessage&&t.onMenuShareAppMessage(e))};class K{static instance;isConfigured=!1;config=null;initPromise=null;constructor(){}static getInstance(){return K.instance||(K.instance=new K),K.instance}async init(e){return this.initPromise||(this.config=e,this.initPromise=q(e).then(e=>(this.isConfigured=e,e)).finally(()=>{this.initPromise=null})),this.initPromise}isReady(){return this.isConfigured&&$()}getConfig(){return this.config}setShareData(e){this.isReady()&&(G(e),Y(e))}}exports.ErrorHandler=n,exports.PerformanceMonitor=c,exports.UniAppToolsError=t,exports.VERSION="2.0.0",exports.WechatSDK=K,exports.areaList=x,exports.batchGetStorage=function(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=A(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,t={})=>{const{timeoutMs:n=8e3}=t;return new Promise(t=>{const r=F();if(!r||"function"!=typeof r.checkJsApi)return void t({});let s=!1;const o=e=>{s||(s=!0,t(e))},a=setTimeout(()=>o({}),n);try{r.checkJsApi({jsApiList:e,success:e=>{clearTimeout(a),o(e?.checkResult||{})}})}catch(e){clearTimeout(a),o({})}})},exports.cleanExpiredStorage=function(){return I.cleanExpired()},exports.clearStorageSync=function(e){return e?I.remove(e):I.clear()},exports.configWechatJSSDK=q,exports.copyText=async function(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...R,...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=w,exports.deepClone=y,exports.deepMerge=function(e,t){const n=y(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]=y(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=m,exports.getStatusBarHeight=d,exports.getStorage=async function(e,t){return await r(()=>new Promise(n=>{n(A(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return I.getInfo()},exports.getStorageSync=A,exports.getTopNavBarHeight=()=>{try{const e=d();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=$,exports.loadWechatJSSDK=H,exports.measurePerformance=i,exports.mergeObjects=function(e,t){if(!t||0===Object.keys(t).length)return e;const n={...e};for(const r of Object.keys(e))Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n},exports.navigateTo=E,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=M,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 E(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1},exports.safeSync=s,exports.selectAndUpload=N,exports.selectAndUploadImage=async function(e){return N({...e,type:"image"})},exports.setPageIcon=(e,t="image/x-icon")=>s(()=>{const n=m();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=Y,exports.shareToTimeline=G,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=P,exports.useBackDebounced=C,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await P(e,t);const s=t.homePage||"pages/index/index",o=s.startsWith("/")?s:`/${s}`;return await M({url:o,params:t.homeParams})},exports.useCascaderAreaData=S,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
+ "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};console.error(`[${r.module}] ${r.code}: ${r.message}`,r),this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){console.error("Error in error callback:",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}}const o=n.getInstance();let a=null,i=null,c=null;const u=e=>"weixin"===e||"alipay"===e;let l=!1;const f=()=>{if(a)return a;let e="unknown";return e="weixin",e="web",e="app",e="alipay",e="h5",a="h5","h5"},p=(e=!0)=>e&&c?c:s(()=>{const t=uni.getWindowInfo();return e&&(c=t),t},"system","GET_WINDOW_INFO_ERROR",null),m=()=>{if(null!==i)return i;try{const e=p();return i=e?.statusBarHeight||0,i}catch(e){return o.handleError(new t("GET_STATUS_BAR_HEIGHT_ERROR",`获取状态栏高度失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),0}},g=()=>{try{const e=f();return u(e)?uni.getMenuButtonBoundingClientRect():null}catch(e){return o.handleError(new t("GET_MENU_BUTTON_ERROR",`获取菜单按钮边界信息失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),null}},d=()=>{try{const e=f();if(u(e)){const e=g();return e?.height||44}return 44}catch(e){return o.handleError(new t("GET_NAVIGATION_BAR_HEIGHT_ERROR",`获取导航栏高度失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),44}},h=()=>{const e=f(),t=m(),n=d();return{platform:e,statusBarHeight:t,navigationBarHeight:n,totalTopHeight:t+n}},y=n.getInstance();function E(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 y.handleError(new t("DEEP_CLONE_ERROR",`深拷贝失败: ${e instanceof Error?e.message:String(e)}`,"utils"),"utils"),new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function w(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,R=e.useCascaderAreaData,T=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})},x=n.getInstance();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}function A(e,n){x.handleError(new t(e,n,"navigation"),"navigation")}async function v(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=>{A("NAVIGATE_TO_FAILED",`页面跳转失败: ${n}`),t(!1)}})})}async function C(e){return new Promise(t=>{const n=_(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{A("RELAUNCH_FAILED",`重新启动失败: ${n}`),t(!1)}})})}async function P(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return console.warn(`[navigation] 无法返回${r}页,当前页面栈深度不足`),void n(!1);const o=setTimeout(()=>{console.warn("[navigation] 导航返回超时"),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){A("PAGE_CALLBACK_ERROR",`页面回调执行失败: ${e instanceof Error?e.message:String(e)}`),n(!0)}},100)},fail:e=>{clearTimeout(o),A("NAVIGATE_BACK_FAILED","导航返回失败"),n(!1)}})})}const O=w(P,300),I={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3},$=n.getInstance();class b{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return b.instance||(b.instance=new b),b.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,n,r={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const t={value:n,timestamp:Date.now(),ttl:r.ttl},s=JSON.stringify(t);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,t),!0}catch(e){throw $.handleError(new t("SET_STORAGE_ERROR",`设置存储失败: ${e instanceof Error?e.message:String(e)}`,"localStorage"),"localStorage"),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(n){return console.warn(`[localStorage] 获取存储失败 [${e}]:`,n),t}}remove(e){try{return!(!e||"string"!=typeof e||(uni.removeStorageSync(e),this.cache.delete(e),0))}catch(n){return $.handleError(new t("REMOVE_STORAGE_ERROR",`删除存储失败: ${e}`,"localStorage"),"localStorage"),!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return $.handleError(new t("CLEAR_STORAGE_ERROR","清空存储失败","localStorage"),"localStorage"),!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return $.handleError(new t("GET_STORAGE_INFO_ERROR",`获取存储信息失败: ${e instanceof Error?e.message:String(e)}`,"localStorage"),"localStorage"),{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 $.handleError(new t("CLEAN_EXPIRED_ERROR",`清理过期数据失败: ${e instanceof Error?e.message:String(e)}`,"localStorage"),"localStorage"),0}}}const D=b.getInstance();function U(e,t,n={}){return D.set(e,t,n)}function L(e,t){return D.get(e,t)}function M(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function N(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function k(e,t){return t&&e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function H(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n&&e.some(e=>!k(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 F(e,t,n){const{url:r,maxUploadFileSizeMB:s,showToast:o=!0,beforeUpload:a}=t;if("function"==typeof a&&!await Promise.resolve(a(e)))return{file:e,success:!1,message:"已取消上传"};if(!r){const t="上传地址不能为空";return o&&T(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const i=k(e.size,s);return i.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f,autoRevokeObjectURL:p=!1}=t;return new Promise(t=>{const m=e.raw;if(!(m&&m instanceof File)){const n="H5 环境缺少原生文件对象";return i&&T(n,!1,"none"),void t({file:e,success:!1,message:n})}const g=p&&"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&"string"==typeof e.path&&e.path.startsWith("blob:"),d=()=>{if(g)try{URL.revokeObjectURL(e.path)}catch{}},h=new XMLHttpRequest,y=new FormData;y.append(s,m,e.name),o&&Object.keys(o).forEach(e=>{y.append(e,String(o[e]))}),l&&h.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),h.addEventListener("load",()=>{const r=h.status,s=r>=200&&r<300;let o=h.responseText;try{o=JSON.parse(h.responseText)}catch{}if(s)i&&1===n&&T(c,!1,"none"),d(),t({file:e,success:!0,statusCode:r,data:o});else{const n=`上传失败,状态码:${r}`;i&&T(n,!1,"none"),d(),t({file:e,success:!1,statusCode:r,data:o,message:n})}}),h.addEventListener("error",()=>{const n=u;i&&T(n,!1,"none"),d(),t({file:e,success:!1,message:n})}),h.addEventListener("timeout",()=>{const n=f?`上传超时(${f}ms)`:"上传超时";i&&T(n,!1,"none"),d(),t({file:e,success:!1,message:n})}),h.addEventListener("abort",()=>{d(),t({file:e,success:!1,message:"上传已取消"})}),h.open("POST",r),"number"==typeof f&&f>0&&(h.timeout=f),a&&Object.keys(a).forEach(e=>{h.setRequestHeader(e,a[e])}),h.send(y)})}(e,t,n):function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f}=t,p="undefined"==typeof uni?null:uni;if(!p||"function"!=typeof p.uploadFile){const t="当前环境不支持文件上传";return i&&T(t,!1,"none"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{let m=!1,g=null;const d=e=>{m||(m=!0,g&&(clearTimeout(g),g=null),t(e))};let h=null;"number"==typeof f&&f>0&&(g=setTimeout(()=>{try{h&&"function"==typeof h.abort&&h.abort()}catch{}const t=`上传超时(${f}ms)`;i&&T(t,!1,"none"),d({file:e,success:!1,message:t})},f)),h=p.uploadFile({url:r,filePath:e.path,name:s,formData:o,header:a,success:t=>{let r=t.data;try{r=JSON.parse(t.data)}catch{}const s=t.statusCode;if(s>=200&&s<300)i&&1===n&&T(c,!1,"none"),d({file:e,success:!0,statusCode:s,data:r});else{const t=`上传失败,状态码:${s}`;i&&T(t,!1,"none"),d({file:e,success:!1,statusCode:s,data:r,message:t})}},fail:t=>{const n=t?.errMsg||u;i&&T(n,!1,"none"),d({file:e,success:!1,message:n})}}),l&&h&&"function"==typeof h.onProgressUpdate&&h.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(o&&i.message&&T(i.message,!1,"error"),Promise.resolve({file:e,success:!1,message:i.message}))}async function B(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await async function(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=H(Array.from(r).map((e,t)=>{const n=M(e.name),r=URL.createObjectURL(e);return{id:N(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=>{const t=function(e){const t=(e||"").trim();if(!t)return"选择文件失败";const n=t.toLowerCase();return n.includes("fail cancel")||n.includes("cancel")?"用户取消选择":/[\u4e00-\u9fff]/.test(t)?t:"选择文件失败"}(e?.errMsg);r({success:!1,files:[],message:t})},a=function(){let e="unknown";return e="h5",e="weixin",e="alipay",e="app","app"}();"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=M(e.path);return{id:N(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(H(n,e))},fail:o}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=M(e.name||e.path);return{id:N(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(H(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=M(e.path);return{id:N(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:a,raw:e}});r(H(n,e))},fail:o})})}(e)}(e);if(!r.success){const e=r.message||n;return t&&e&&T(e,!1,"none"),[{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],i=await F(a,t,n);r[s]=i}},i=[];for(let e=0;e<s;e+=1)i.push(a());return await Promise.all(i),r}(s,e,o)}catch(e){const r=n;return t&&r&&T(r,!1,"none"),[{file:null,success:!1,message:r}]}}const j=n.getInstance(),G=n.getInstance(),W=()=>!("undefined"==typeof navigator||!navigator.userAgent)&&navigator.userAgent.toLowerCase().includes("micromessenger"),J=()=>"undefined"!=typeof window&&"undefined"!=typeof document,z=()=>J()&&W()&&window.wx||null;let K=!1,q=null;const V=(e={})=>{const{timeoutMs:t=1e4}=e;if(K||J()&&window.wx)return K=!0,Promise.resolve(!0);if(!J())return Promise.resolve(!1);if(q)return q;const n=e.cdnUrls&&e.cdnUrls.length>0?e.cdnUrls:["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];return q=new Promise(e=>{let r=!1,s=null,o=null,a=0;const i=t=>{r||(r=!0,s&&(clearTimeout(s),s=null),o&&o.parentNode&&o.parentNode.removeChild(o),t&&(K=!0),q=null,e(t))},c=()=>{if(a>=n.length)return void i(!1);if(!document.head)return void i(!1);const e=n[a];a+=1;const t=document.createElement("script");o=t,t.src=e,t.async=!0,t.onload=()=>i(!0),t.onerror=()=>{t.parentNode&&t.parentNode.removeChild(t),o=null,c()},document.head.appendChild(t)};s=setTimeout(()=>{i(!1)},t),c()}),q};let Y=null;const X=async(e,n={})=>{const{timeoutMs:r=1e4}=n;if(!W())return console.warn("当前不在微信环境中"),!1;if(Y)return Y;if(!await V({timeoutMs:r}))return G.handleError(new t("WECHAT_JSSDK_LOAD_FAILED","微信 JS-SDK 加载失败","weixin"),"weixin"),!1;if(!J())return!1;const s=window.wx;return!!s&&(Y=new Promise(n=>{let o=!1,a=null;const i=e=>{o||(o=!0,a&&(clearTimeout(a),a=null),Y=null,n(e))};a=setTimeout(()=>i(!1),r);try{s.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),s.ready(()=>{console.log("微信 JS-SDK 初始化完成"),i(!0)}),s.error(e=>{G.handleError(new t("WECHAT_JSSDK_CONFIG_ERROR",`微信 JS-SDK 配置错误: ${JSON.stringify(e)}`,"weixin"),"weixin"),i(!1)})}catch(e){G.handleError(new t("WECHAT_JSSDK_CONFIG_EXCEPTION",`微信 JS-SDK 配置异常: ${e instanceof Error?e.message:String(e)}`,"weixin"),"weixin"),i(!1)}}),Y)},Q=e=>{const t=z();t&&(t.updateTimelineShareData?t.updateTimelineShareData(e):t.onMenuShareTimeline&&t.onMenuShareTimeline(e))},Z=e=>{const t=z();t&&(t.updateAppMessageShareData?t.updateAppMessageShareData(e):t.onMenuShareAppMessage&&t.onMenuShareAppMessage(e))};class ee{static instance;isConfigured=!1;config=null;initPromise=null;constructor(){}static getInstance(){return ee.instance||(ee.instance=new ee),ee.instance}async init(e){return this.initPromise||(this.config=e,this.initPromise=X(e).then(e=>(this.isConfigured=e,e)).finally(()=>{this.initPromise=null})),this.initPromise}isReady(){return this.isConfigured&&W()}getConfig(){return this.config}setShareData(e){this.isReady()?(Q(e),Z(e)):console.warn("微信 SDK 未就绪")}}const te="4.0.0",ne={info:0,warn:1,error:2};exports.ErrorHandler=n,exports.UniAppToolsError=t,exports.VERSION=te,exports.WechatSDK=ee,exports.areaList=S,exports.batchGetStorage=function(e){const t={};return e.forEach(e=>{t[e]=L(e)}),t},exports.batchSetStorage=function(e,t={}){let n=0;return Object.entries(e).forEach(([e,r])=>{U(e,r,t)&&n++}),n},exports.buildUrl=_,exports.checkWechatJSAPI=(e,n={})=>{const{timeoutMs:r=8e3}=n;return new Promise(n=>{const s=z();if(!s||"function"!=typeof s.checkJsApi)return void n({});let o=!1;const a=e=>{o||(o=!0,n(e))},i=setTimeout(()=>a({}),r);try{s.checkJsApi({jsApiList:e,success:e=>{clearTimeout(i),a(e?.checkResult||{})}})}catch(e){clearTimeout(i),G.handleError(new t("CHECK_WECHAT_JSAPI_ERROR",`检查微信 JS-SDK API 异常: ${e instanceof Error?e.message:String(e)}`,"weixin"),"weixin"),a({})}})},exports.cleanExpiredStorage=function(){return D.cleanExpired()},exports.clearStorageSync=function(e){return e?D.remove(e):D.clear()},exports.clearSystemCache=()=>{c=null},exports.configWechatJSSDK=X,exports.copyText=async function(e,t={}){const n={...I,...t};return e&&"string"==typeof e?e.length>1e4?(n.showToast&&T("复制内容过长",!1,"error"),!1):await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{n.showToast&&T(n.successMessage),t(!0)},fail:()=>{n.showToast&&T(n.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1:(n.showToast&&T("复制内容不能为空",!1,"error"),!1)},exports.debounce=w,exports.deepClone=E,exports.deepMerge=function(e,t){const n=E(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]=E(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(n){return y.handleError(new t("EXTRACT_URL_PARTS_ERROR",`无效的URL: ${e}`,"utils"),"utils"),{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 o.handleError(new t("GET_ACCOUNT_INFO_ERROR",`获取小程序账户信息失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),{appId:"",version:"",envVersion:"",accountInfo:{}}}},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 A("GET_CURRENT_PAGE_ERROR",`获取当前页面信息失败: ${e instanceof Error?e.message:String(e)}`),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}}),console.log("🔗 H5 URL参数解析:",{fullUrl:window.location.href,searchParams:window.location.search,parsedParams:n,paramName:e}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(n){return y.handleError(new t("GET_H5_URL_PARAMS_ERROR",`获取H5 URL参数失败: ${n instanceof Error?n.message:String(n)}`,"utils"),"utils"),e?null:{}}},exports.getMenuButtonBoundingClientRect=g,exports.getNavHeight=()=>h().totalTopHeight,exports.getNavigationBarHeight=d,exports.getPageStack=function(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return A("GET_PAGE_STACK_ERROR",`获取页面栈信息失败: ${e instanceof Error?e.message:String(e)}`),[]}},exports.getPlatform=f,exports.getStatusBarHeight=m,exports.getStorage=async function(e,t){return await r(()=>new Promise(n=>{n(L(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t},exports.getStorageInfo=function(){return D.getInfo()},exports.getStorageSync=L,exports.getTopBarMetrics=h,exports.getTopNavBarHeight=()=>{const e=h();return{statusBarHeight:e.statusBarHeight,navHeight:e.totalTopHeight}},exports.initUniAppTools=function(e={}){const{enableErrorHandler:t=!0,onError:r=null,showInitMessage:s=!1,silent:o=!1,logLevel:a="warn"}=e,i=ne[a]||ne.warn;if(t){const e=n.getInstance();"function"==typeof r?e.onError(r):e.onError(e=>{((...e)=>{!o&&i<=ne.error&&console.error(...e)})(`[UniAppTools] ${e.module} - ${e.code}: ${e.message}`,e)})}if(((...e)=>{!o&&i<=ne.info&&console.log(...e)})(`[UniAppTools] v${te} 初始化完成`),s&&"undefined"!=typeof uni)try{uni.showToast({title:`工具库v${te}已就绪`,icon:"none",duration:2e3})}catch(e){}},exports.isWechat=W,exports.loadWechatJSSDK=V,exports.mergeObjects=function(e,t){if(!t||0===Object.keys(t).length)return e;const n={...e};for(const r of Object.keys(e))Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n},exports.navigateTo=v,exports.onCheckForUpdate=()=>{if(!l)try{const e=uni.getUpdateManager();l=!0,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){o.handleError(new t("UPDATE_DOWNLOAD_FAILED","新版本下载失败","system"),"system"),uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){o.handleError(new t("CHECK_UPDATE_ERROR",`版本更新检查失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system")}},exports.reLaunch=C,exports.redirectTo=async function(e){return new Promise(t=>{const n=_(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{A("REDIRECT_TO_FAILED",`页面重定向失败: ${n}`),t(!1)}})})},exports.safeAsync=r,exports.safeNavigateTo=async function(e,t=3){for(let n=0;n<t;n++){if(await v(e))return!0;n<t-1&&(await new Promise(e=>setTimeout(e,1e3*(n+1))),console.log(`[navigation] 第${n+2}次尝试跳转...`))}return!1},exports.safeSync=s,exports.selectAndUpload=B,exports.selectAndUploadImage=async function(e){return B({...e,type:"image"})},exports.setPageIcon=(e,t="image/x-icon")=>s(()=>{const n=f();if("h5"===n||"web"===n){if("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}}else console.warn("setPageIcon 仅在H5/Web平台有效");return!1},"system","SET_PAGE_ICON_ERROR",!1),exports.setPageTitle=e=>"string"!=typeof e?(console.warn("setPageTitle: title必须是字符串"),Promise.resolve(!1)):""===e.trim()?(console.warn("setPageTitle: title不能为空"),Promise.resolve(!1)):new Promise(n=>{try{uni.setNavigationBarTitle({title:e,success:()=>{n(!0)},fail:e=>{console.warn("设置页面标题失败:",e),n(!1)}})}catch(e){o.handleError(new t("SET_PAGE_TITLE_ERROR",`setPageTitle执行异常: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),n(!1)}}),exports.setStorage=async function(e,t,n={}){return await r(()=>new Promise(r=>{r(U(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1},exports.setStorageSync=U,exports.shareToFriend=Z,exports.shareToTimeline=Q,exports.switchTab=async function(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:n=>{A("SWITCH_TAB_FAILED",`Tab切换失败: ${e}`),t(!1)}})})},exports.throttle=function(e,t,n={}){let r,s=null,o=0;const{leading:a=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();o||a||(o=c);const u=t-(c-o);return u<=0||u>t?(s&&(clearTimeout(s),s=null),o=c,r=e.apply(this,n)):!s&&i&&(s=setTimeout(()=>{o=a?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return c.cancel=()=>{s&&(clearTimeout(s),s=null),o=0},c},exports.useBack=P,exports.useBackDebounced=O,exports.useBackOrHome=async function(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await P(e,t);const s=t.homePage||"pages/index/index",o=s.startsWith("/")?s:`/${s}`;return console.info(`[navigation] 页面栈深度不足,重定向到首页: ${o}`),await C({url:o,params:t.homeParams})},exports.useCascaderAreaData=R,exports.useRegions=function(){return e.useCascaderAreaData()},exports.useToast=T,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,n,r)=>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){console.log("🚀 ~ 微信支付结果:",e),"get_brand_wcpay_request:ok"===e.err_msg?(console.log("✅ 微信支付成功"),n?.(e),o(!0)):(console.warn("❌ 微信支付失败或取消:",e.err_msg),r?.(e),o(!1))})}catch(e){j.handleError(new t("WECHAT_PAY_INVOKE_ERROR",`调用微信支付接口失败: ${e instanceof Error?e.message:String(e)}`,"payment"),"payment");const n={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};r?.(n),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)||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 s{static instance;errorCallbacks=[];static getInstance(){return s.instance||(s.instance=new s),s.instance}onError(e){this.errorCallbacks.push(e)}handleError(e,t){const s={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(s)}catch(e){}})}createModuleErrorHandler(e){return(t,s,r)=>{const o=new n(t,s,e);return r&&(o.stack=r.stack),this.handleError(o,e),o}}}async function r(e,t,n="ASYNC_ERROR"){try{return await e()}catch(e){return s.getInstance().createModuleErrorHandler(t)(n,`异步操作失败: ${e instanceof Error?e.message:String(e)}`,e),null}}function o(e,t,n="SYNC_ERROR",r=null){try{return e()}catch(e){return s.getInstance().createModuleErrorHandler(t)(n,`同步操作失败: ${e instanceof Error?e.message:String(e)}`,e),r}}var a=Object.freeze({__proto__:null,ErrorHandler:s,UniAppToolsError:n,safeAsync:r,safeSync:o});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 s={name:e,startTime:i(),module:t,metadata:n};this.metrics.set(e,s)}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 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 u(e){return function(t,n,s){const r=s.value;s.value=function(...s){const o=c.getInstance(),a=`${t.constructor.name}.${n}`;o.start(a,e,{args:s.length});try{const e=r.apply(this,s);return e instanceof Promise?e.finally(()=>{o.end(a)}):(o.end(a),e)}catch(e){throw o.end(a),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 s=o(()=>{const t=uni.getWindowInfo();return e&&m.set(n,t),t},"system","GET_WINDOW_INFO_ERROR",null);return t.end("getWindowInfo"),s},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){}},y=()=>{try{const e=d();return e?.statusBarHeight||0}catch(e){return 0}},w=()=>{try{const e=h();return"weixin"===e||"alipay"===e?uni.getMenuButtonBoundingClientRect():null}catch(e){return null}},v=()=>{try{const e=y(),t=h();if("weixin"===t||"alipay"===t){const t=w();if(t){return t.height+e}}return e+0}catch(e){return y()+0}},S=()=>{try{const e=y();return{statusBarHeight:e,navHeight:v()}}catch(e){return{statusBarHeight:0,navHeight:44}}},E=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),T=(e,t="image/x-icon")=>o(()=>{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 P(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 M(e,t){const n=P(e);return function e(t,n){for(const s in n)if(n.hasOwnProperty(s)){const r=n[s],o=t[s];r&&"object"==typeof r&&!Array.isArray(r)&&o&&"object"==typeof o&&!Array.isArray(o)?e(o,r):t[s]=P(r)}}(n,t),n}function R(e,t){if(!t||0===Object.keys(t).length)return e;const n={...e};for(const s of Object.keys(e))Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s]);return n}function C(e,t,n=!1){let s,r=null;const o=function(...o){const a=n&&!r;return r&&clearTimeout(r),r=setTimeout(()=>{r=null,n||(s=e.apply(this,o))},t),a&&(s=e.apply(this,o)),s};return o.cancel=()=>{r&&(clearTimeout(r),r=null)},o}function b(e,t,n={}){let s,r=null,o=0;const{leading:a=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();o||a||(o=c);const u=t-(c-o);return u<=0||u>t?(r&&(clearTimeout(r),r=null),o=c,s=e.apply(this,n)):!r&&i&&(r=setTimeout(()=>{o=a?Date.now():0,r=null,s=e.apply(this,n)},u)),s};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=0},c}function x(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 I=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(s){n[t]=e}}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return e?null:{}}};function O(e){try{const t=new URL(e,"http://localhost"),n=t.pathname,s={};return t.searchParams.forEach((e,t)=>{s[t]=e}),{path:n,params:s}}catch(e){return{path:"",params:{}}}}const _=e,A=t;function k(){return t()}const j=(e="",t=!1,n="none",s=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:s})};function L(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 U(e){return new Promise(t=>{const n=L(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 $(e){return new Promise(t=>{const n=L(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}async function D(e="",t={}){return new Promise(n=>{const s=t.delta||1,r=t.timeout||5e3;if(getCurrentPages().length<=s)return void n(!1);const o=setTimeout(()=>{n(!1)},r);uni.navigateBack({delta:s,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)}})})}async function z(e="",t={}){const n=getCurrentPages(),s=t.delta||1;if(n.length>s)return await D(e,t);const r=t.homePage||"pages/index/index",o=r.startsWith("/")?r:`/${r}`;return await B({url:o,params:t.homeParams})}const N=C(D,300);async function F(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=L(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{t(!1)}})})}function W(){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 H(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return[]}}async function J(e,t=3){for(let n=0;n<t;n++){if(await U(e))return!0;n<t-1&&await new Promise(e=>setTimeout(e,1e3*(n+1)))}return!1}const q={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function G(e,t={}){const n=c.getInstance();n.start("copyText","clipboard",{textLength:e.length});const s={...q,...t};if(!e||"string"!=typeof e)return s.showToast&&j("复制内容不能为空",!1,"error"),n.end("copyText"),!1;if(e.length>1e4)return s.showToast&&j("复制内容过长",!1,"error"),n.end("copyText"),!1;const o=await r(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{s.showToast&&j(s.successMessage),t(!0)},fail:()=>{s.showToast&&j(s.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1;return n.end("copyText"),o}class Y{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return Y.instance||(Y.instance=new Y),Y.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 s={value:t,timestamp:Date.now(),ttl:n.ttl},r=JSON.stringify(s);if(r.length>1048576)throw new Error("存储数据过大");if(uni.setStorageSync(e,r),this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}return this.cache.set(e,s),!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 s=JSON.parse(n);let r;return r=s&&"object"==typeof s&&"value"in s&&"timestamp"in s?s:{value:s,timestamp:Date.now()},this.isExpired(r)?(this.remove(e),t):(this.cache.set(e,r),r.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=Y.getInstance();function X(e,t,n={}){return V.set(e,t,n)}function K(e,t){return V.get(e,t)}function Q(e){return e?V.remove(e):V.clear()}async function Z(e,t,n={}){return await r(()=>new Promise(s=>{s(X(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function ee(e,t){return await r(()=>new Promise(n=>{n(K(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function te(){return V.getInfo()}function ne(){return V.cleanExpired()}function se(e,t={}){const n=c.getInstance();n.start("batchSetStorage","localStorage");let s=0;return Object.entries(e).forEach(([e,n])=>{X(e,n,t)&&s++}),n.end("batchSetStorage"),s}function re(e){const t=c.getInstance();t.start("batchGetStorage","localStorage");const n={};return e.forEach(e=>{n[e]=K(e)}),t.end("batchGetStorage"),n}function oe(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function ae(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function ie(e,t){if(!t)return{valid:!0};return e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function ce(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:s}=t;if(n){if(e.some(e=>!ie(e.size,n).valid))return{success:!1,files:e,message:`部分文件大小超过 ${n}MB 限制`}}if(s&&s.length>0){const t=s.map(e=>e.toLowerCase());if(e.some(e=>!e.ext||!t.includes(e.ext)))return{success:!1,files:e,message:`存在不支持的文件类型,仅支持:${s.join(", ")}`}}return{success:!0,files:e}}async function ue(e){return"undefined"!=typeof document&&"undefined"!=typeof window?function(e){const{type:t="image",count:n=1,extensions:s}=e;return new Promise(r=>{if("undefined"==typeof document)return void r({success:!1,files:[],message:"当前环境不支持文件选择"});const o=document.createElement("input");o.type="file",o.multiple=n>1,"image"===t?o.accept="image/*":s&&s.length>0&&(o.accept=s.map(e=>e.startsWith(".")?e:`.${e}`).join(",")),o.onchange=t=>{const n=t.target,s=n?.files;if(!s||0===s.length)return r({success:!1,files:[],message:"用户取消选择"}),void document.body.removeChild(o);const a=ce(Array.from(s).map((e,t)=>{const n=oe(e.name),s=URL.createObjectURL(e);return{id:ae(t),name:e.name,size:e.size,path:s,mimeType:e.type,ext:n,source:"file",platform:"h5",raw:e}}),e);r(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(s=>{const r="undefined"==typeof uni?null:uni;if(!r)return void s({success:!1,files:[],message:"当前环境不支持文件选择"});const o=e=>{const t=function(e){const t=(e||"").trim();if(!t)return"选择文件失败";const n=t.toLowerCase();return n.includes("fail cancel")||n.includes("cancel")?"用户取消选择":/[\u4e00-\u9fff]/.test(t)?t:"选择文件失败"}(e?.errMsg);s({success:!1,files:[],message:t})},a=function(){let e="unknown";return e="h5",e="weixin",e="alipay",e="app","app"}();"image"!==t||"function"!=typeof r.chooseImage?"function"!=typeof r.chooseMessageFile?"function"!=typeof r.chooseFile?s({success:!1,files:[],message:"当前平台不支持文件选择"}):r.chooseFile({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=oe(e.path);return{id:ae(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});s(ce(n,e))},fail:o}):r.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=oe(e.name||e.path);return{id:ae(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});s(ce(n,e))},fail:o}):r.chooseImage({count:n,success:t=>{const n=(Array.isArray(t.tempFiles)?t.tempFiles:[t.tempFiles]).map((e,t)=>{const n=oe(e.path);return{id:ae(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:a,raw:e}});s(ce(n,e))},fail:o})})}(e)}async function le(e,t,n){const{url:s,maxUploadFileSizeMB:r,showToast:o=!0,beforeUpload:a}=t;if("function"==typeof a){if(!await Promise.resolve(a(e)))return{file:e,success:!1,message:"已取消上传"}}if(!s){const t="上传地址不能为空";return o&&j(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const i=ie(e.size,r);return i.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:s,fieldName:r="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f,autoRevokeObjectURL:m=!1}=t;return new Promise(t=>{const d=e.raw;if(!(d&&d instanceof File)){const n="H5 环境缺少原生文件对象";return i&&j(n,!1,"none"),void t({file:e,success:!1,message:n})}const h=m&&"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&"string"==typeof e.path&&e.path.startsWith("blob:"),p=()=>{if(h)try{URL.revokeObjectURL(e.path)}catch{}},g=new XMLHttpRequest,y=new FormData;y.append(r,d,e.name),o&&Object.keys(o).forEach(e=>{y.append(e,String(o[e]))}),l&&g.upload.addEventListener("progress",t=>{if(t.lengthComputable){const n=Math.round(t.loaded/t.total*100);l(e,n)}}),g.addEventListener("load",()=>{const s=g.status,r=s>=200&&s<300;let o=g.responseText;try{o=JSON.parse(g.responseText)}catch{}if(r)i&&1===n&&j(c,!1,"none"),p(),t({file:e,success:!0,statusCode:s,data:o});else{const n=`上传失败,状态码:${s}`;i&&j(n,!1,"none"),p(),t({file:e,success:!1,statusCode:s,data:o,message:n})}}),g.addEventListener("error",()=>{const n=u;i&&j(n,!1,"none"),p(),t({file:e,success:!1,message:n})}),g.addEventListener("timeout",()=>{const n=f?`上传超时(${f}ms)`:"上传超时";i&&j(n,!1,"none"),p(),t({file:e,success:!1,message:n})}),g.addEventListener("abort",()=>{p(),t({file:e,success:!1,message:"上传已取消"})}),g.open("POST",s),"number"==typeof f&&f>0&&(g.timeout=f),a&&Object.keys(a).forEach(e=>{g.setRequestHeader(e,a[e])}),g.send(y)})}(e,t,n):function(e,t,n){const{url:s,fieldName:r="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f}=t,m="undefined"==typeof uni?null:uni;if(!m||"function"!=typeof m.uploadFile){const t="当前环境不支持文件上传";return i&&j(t,!1,"none"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{let d=!1,h=null;const p=e=>{d||(d=!0,h&&(clearTimeout(h),h=null),t(e))};let g=null;"number"==typeof f&&f>0&&(h=setTimeout(()=>{try{g&&"function"==typeof g.abort&&g.abort()}catch{}const t=`上传超时(${f}ms)`;i&&j(t,!1,"none"),p({file:e,success:!1,message:t})},f)),g=m.uploadFile({url:s,filePath:e.path,name:r,formData:o,header:a,success:t=>{let s=t.data;try{s=JSON.parse(t.data)}catch{}const r=t.statusCode;if(r>=200&&r<300)i&&1===n&&j(c,!1,"none"),p({file:e,success:!0,statusCode:r,data:s});else{const t=`上传失败,状态码:${r}`;i&&j(t,!1,"none"),p({file:e,success:!1,statusCode:r,data:s,message:t})}},fail:t=>{const n=t?.errMsg||u;i&&j(n,!1,"none"),p({file:e,success:!1,message:n})}}),l&&g&&"function"==typeof g.onProgressUpdate&&g.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(o&&i.message&&j(i.message,!1,"error"),Promise.resolve({file:e,success:!1,message:i.message}))}async function fe(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const s=await ue(e);if(!s.success){const e=s.message||n;return t&&e&&j(e,!1,"none"),[{file:null,success:!1,message:e}]}const r=s.files;if(0===r.length)return[];const o=r.length;return await async function(e,t,n){const s=new Array(e.length),r=t.concurrency&&t.concurrency>0?Math.min(t.concurrency,e.length):e.length;let o=0;const a=async()=>{for(;;){const r=o;if(r>=e.length)break;o+=1;const a=e[r],i=await le(a,t,n);s[r]=i}},i=[];for(let e=0;e<r;e+=1)i.push(a());return await Promise.all(i),s}(r,e,o)}catch(e){const s=n;return t&&s&&j(s,!1,"none"),[{file:null,success:!1,message:s}]}}async function me(e){return fe({...e,type:"image"})}const de=(e,t,n)=>{const s=c.getInstance();return s.start("weChatOfficialAccountPayment","payment"),new Promise(r=>{o(()=>{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 o(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){s.end("weChatOfficialAccountPayment"),"get_brand_wcpay_request:ok"===e.err_msg?(t?.(e),r(!0)):(n?.(e),r(!1))})}catch(e){s.end("weChatOfficialAccountPayment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};n?.(t),r(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",o,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",o),e.attachEvent("onWeixinJSBridgeReady",o))}else o();return!0},"payment","WECHAT_PAY_ERROR",!1)||(s.end("weChatOfficialAccountPayment"),r(!1))})},he=()=>!("undefined"==typeof navigator||!navigator.userAgent)&&navigator.userAgent.toLowerCase().includes("micromessenger"),pe=()=>"undefined"!=typeof window&&"undefined"!=typeof document,ge=()=>pe()&&he()&&window.wx||null;let ye=!1,we=null;const ve=(e={})=>{const{timeoutMs:t=1e4}=e;if(ye||pe()&&window.wx)return ye=!0,Promise.resolve(!0);if(!pe())return Promise.resolve(!1);if(we)return we;const n=e.cdnUrls&&e.cdnUrls.length>0?e.cdnUrls:["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];return we=new Promise(e=>{let s=!1,r=null,o=null,a=0;const i=t=>{s||(s=!0,r&&(clearTimeout(r),r=null),o&&o.parentNode&&o.parentNode.removeChild(o),t&&(ye=!0),we=null,e(t))},c=()=>{if(a>=n.length)return void i(!1);if(!document.head)return void i(!1);const e=n[a];a+=1;const t=document.createElement("script");o=t,t.src=e,t.async=!0,t.onload=()=>i(!0),t.onerror=()=>{t.parentNode&&t.parentNode.removeChild(t),o=null,c()},document.head.appendChild(t)};r=setTimeout(()=>{i(!1)},t),c()}),we};let Se=null;const Ee=async(e,t={})=>{const{timeoutMs:n=1e4}=t;if(!he())return!1;if(Se)return Se;if(!await ve({timeoutMs:n}))return!1;if(!pe())return!1;const s=window.wx;return!!s&&(Se=new Promise(t=>{let r=!1,o=null;const a=e=>{r||(r=!0,o&&(clearTimeout(o),o=null),Se=null,t(e))};o=setTimeout(()=>a(!1),n);try{s.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),s.ready(()=>{a(!0)}),s.error(e=>{a(!1)})}catch(e){a(!1)}}),Se)},Te=(e,t={})=>{const{timeoutMs:n=8e3}=t;return new Promise(t=>{const s=ge();if(!s||"function"!=typeof s.checkJsApi)return void t({});let r=!1;const o=e=>{r||(r=!0,t(e))},a=setTimeout(()=>o({}),n);try{s.checkJsApi({jsApiList:e,success:e=>{clearTimeout(a),o(e?.checkResult||{})}})}catch(e){clearTimeout(a),o({})}})},Pe=e=>{const t=ge();t&&(t.updateTimelineShareData?t.updateTimelineShareData(e):t.onMenuShareTimeline&&t.onMenuShareTimeline(e))},Me=e=>{const t=ge();t&&(t.updateAppMessageShareData?t.updateAppMessageShareData(e):t.onMenuShareAppMessage&&t.onMenuShareAppMessage(e))};class Re{static instance;isConfigured=!1;config=null;initPromise=null;constructor(){}static getInstance(){return Re.instance||(Re.instance=new Re),Re.instance}async init(e){return this.initPromise||(this.config=e,this.initPromise=Ee(e).then(e=>(this.isConfigured=e,e)).finally(()=>{this.initPromise=null})),this.initPromise}isReady(){return this.isConfigured&&he()}getConfig(){return this.config}setShareData(e){this.isReady()&&(Pe(e),Me(e))}}const Ce="2.0.0";async function be(e={}){const{enablePerformanceMonitor:t=!1,enableErrorHandler:n=!0,onError:s=null,performanceReportInterval:r=0}=e;if(n){const{ErrorHandler:e}=await Promise.resolve().then(function(){return a}),t=e.getInstance();"function"==typeof s?t.onError(s):t.onError(e=>{})}if(t&&r>0){const{PerformanceMonitor:e}=await Promise.resolve().then(function(){return l}),t=e.getInstance();setInterval(()=>{t.getReport().slowest.length},r)}}export{s as ErrorHandler,c as PerformanceMonitor,n as UniAppToolsError,Ce as VERSION,Re as WechatSDK,_ as areaList,re as batchGetStorage,se as batchSetStorage,Te as checkWechatJSAPI,ne as cleanExpiredStorage,Q as clearStorageSync,Ee as configWechatJSSDK,G as copyText,C as debounce,P as deepClone,M as deepMerge,O as extractUrlParts,p as getCurrentEnv,W as getCurrentPageInfo,I as getH5UrlParams,w as getMenuButtonBoundingClientRect,v as getNavHeight,H as getPageStack,h as getPlatform,y as getStatusBarHeight,ee as getStorage,te as getStorageInfo,K as getStorageSync,S as getTopNavBarHeight,be as initUniAppTools,he as isWechat,ve as loadWechatJSSDK,u as measurePerformance,R as mergeObjects,U as navigateTo,g as onCheckForUpdate,B as reLaunch,$ as redirectTo,r as safeAsync,J as safeNavigateTo,o as safeSync,fe as selectAndUpload,me as selectAndUploadImage,T as setPageIcon,E as setPageTitle,Z as setStorage,X as setStorageSync,Me as shareToFriend,Pe as shareToTimeline,F as switchTab,b as throttle,D as useBack,N as useBackDebounced,z as useBackOrHome,A as useCascaderAreaData,k as useRegions,j as useToast,x as useTryCatch,d as useWindowInfo,de 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};console.error(`[${r.module}] ${r.code}: ${r.message}`,r),this.errorCallbacks.forEach(e=>{try{e(r)}catch(e){console.error("Error in error callback:",e)}})}createModuleErrorHandler(e){return(t,r,s)=>{const o=new n(t,r,e);return s&&(o.stack=s.stack),this.handleError(o,e),o}}}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 o(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}}const a=r.getInstance();let i=null,c=null,u=null;const l=()=>{u=null},f=e=>"weixin"===e||"alipay"===e;let m=!1;const g=()=>{if(i)return i;let e="unknown";return e="weixin",e="web",e="app",e="alipay",e="h5",i="h5","h5"},d=(e=!0)=>e&&u?u:o(()=>{const t=uni.getWindowInfo();return e&&(u=t),t},"system","GET_WINDOW_INFO_ERROR",null),h=()=>{try{const e=uni.getAccountInfoSync();return{appId:e.miniProgram?.appId||"",version:e.miniProgram?.version||"",envVersion:e.miniProgram?.envVersion||"",accountInfo:e}}catch(e){return a.handleError(new n("GET_ACCOUNT_INFO_ERROR",`获取小程序账户信息失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),{appId:"",version:"",envVersion:"",accountInfo:{}}}},p=()=>{if(!m)try{const e=uni.getUpdateManager();m=!0,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){a.handleError(new n("UPDATE_DOWNLOAD_FAILED","新版本下载失败","system"),"system"),uni.showModal({title:"更新失败",content:"新版本下载失败,请检查网络连接或稍后重试",showCancel:!1,confirmText:"知道了"})})}catch(e){a.handleError(new n("CHECK_UPDATE_ERROR",`版本更新检查失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system")}},y=()=>{if(null!==c)return c;try{const e=d();return c=e?.statusBarHeight||0,c}catch(e){return a.handleError(new n("GET_STATUS_BAR_HEIGHT_ERROR",`获取状态栏高度失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),0}},w=()=>{try{const e=g();return f(e)?uni.getMenuButtonBoundingClientRect():null}catch(e){return a.handleError(new n("GET_MENU_BUTTON_ERROR",`获取菜单按钮边界信息失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),null}},E=()=>{try{const e=g();if(f(e)){const e=w();return e?.height||44}return 44}catch(e){return a.handleError(new n("GET_NAVIGATION_BAR_HEIGHT_ERROR",`获取导航栏高度失败: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),44}},R=()=>{const e=g(),t=y(),n=E();return{platform:e,statusBarHeight:t,navigationBarHeight:n,totalTopHeight:t+n}},S=()=>{const e=R();return{statusBarHeight:e.statusBarHeight,navHeight:e.totalTopHeight}},T=()=>R().totalTopHeight,_=e=>"string"!=typeof e?(console.warn("setPageTitle: title必须是字符串"),Promise.resolve(!1)):""===e.trim()?(console.warn("setPageTitle: title不能为空"),Promise.resolve(!1)):new Promise(t=>{try{uni.setNavigationBarTitle({title:e,success:()=>{t(!0)},fail:e=>{console.warn("设置页面标题失败:",e),t(!1)}})}catch(e){a.handleError(new n("SET_PAGE_TITLE_ERROR",`setPageTitle执行异常: ${e instanceof Error?e.message:String(e)}`,"system"),"system"),t(!1)}}),A=(e,t="image/x-icon")=>o(()=>{const n=g();if("h5"===n||"web"===n){if("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}}else console.warn("setPageIcon 仅在H5/Web平台有效");return!1},"system","SET_PAGE_ICON_ERROR",!1),v=r.getInstance();function O(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 v.handleError(new n("DEEP_CLONE_ERROR",`深拷贝失败: ${e instanceof Error?e.message:String(e)}`,"utils"),"utils"),new Error(`深拷贝失败: ${e instanceof Error?e.message:String(e)}`)}}function P(e,t){const n=O(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]=O(s)}}(n,t),n}function C(e,t){if(!t||0===Object.keys(t).length)return e;const n={...e};for(const r of Object.keys(e))Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function I(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}function $(e,t,n={}){let r,s=null,o=0;const{leading:a=!0,trailing:i=!0}=n,c=function(...n){const c=Date.now();o||a||(o=c);const u=t-(c-o);return u<=0||u>t?(s&&(clearTimeout(s),s=null),o=c,r=e.apply(this,n)):!s&&i&&(s=setTimeout(()=>{o=a?Date.now():0,s=null,r=e.apply(this,n)},u)),r};return c.cancel=()=>{s&&(clearTimeout(s),s=null),o=0},c}function x(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 L=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}}),console.log("🔗 H5 URL参数解析:",{fullUrl:window.location.href,searchParams:window.location.search,parsedParams:n,paramName:e}),e?n.hasOwnProperty(e)?n[e]:null:n}catch(t){return v.handleError(new n("GET_H5_URL_PARAMS_ERROR",`获取H5 URL参数失败: ${t instanceof Error?t.message:String(t)}`,"utils"),"utils"),e?null:{}}};function M(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(t){return v.handleError(new n("EXTRACT_URL_PARTS_ERROR",`无效的URL: ${e}`,"utils"),"utils"),{path:"",params:{}}}}const b=e,D=t;function U(){return t()}const N=(e="",t=!1,n="none",r=2e3)=>{uni.showToast({title:e,icon:n,mask:t,duration:r})},k=r.getInstance();function H(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}function F(e,t){k.handleError(new n(e,t,"navigation"),"navigation")}async function j(e){return new Promise(t=>{const n=H(e.url,e.params);uni.navigateTo({url:n,animationType:e.animationType,animationDuration:e.animationDuration,events:e.events,success:()=>t(!0),fail:e=>{F("NAVIGATE_TO_FAILED",`页面跳转失败: ${n}`),t(!1)}})})}async function G(e){return new Promise(t=>{const n=H(e.url,e.params);uni.redirectTo({url:n,success:()=>t(!0),fail:e=>{F("REDIRECT_TO_FAILED",`页面重定向失败: ${n}`),t(!1)}})})}async function B(e){return new Promise(t=>{const n=H(e.url,e.params);uni.reLaunch({url:n,success:()=>t(!0),fail:e=>{F("RELAUNCH_FAILED",`重新启动失败: ${n}`),t(!1)}})})}async function J(e){return new Promise(t=>{uni.switchTab({url:e,success:()=>t(!0),fail:n=>{F("SWITCH_TAB_FAILED",`Tab切换失败: ${e}`),t(!1)}})})}async function W(e="",t={}){return new Promise(n=>{const r=t.delta||1,s=t.timeout||5e3;if(getCurrentPages().length<=r)return console.warn(`[navigation] 无法返回${r}页,当前页面栈深度不足`),void n(!1);const o=setTimeout(()=>{console.warn("[navigation] 导航返回超时"),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){F("PAGE_CALLBACK_ERROR",`页面回调执行失败: ${e instanceof Error?e.message:String(e)}`),n(!0)}},100)},fail:e=>{clearTimeout(o),F("NAVIGATE_BACK_FAILED","导航返回失败"),n(!1)}})})}async function z(e,t=3){for(let n=0;n<t;n++){if(await j(e))return!0;n<t-1&&(await new Promise(e=>setTimeout(e,1e3*(n+1))),console.log(`[navigation] 第${n+2}次尝试跳转...`))}return!1}async function K(e="",t={}){const n=getCurrentPages(),r=t.delta||1;if(n.length>r)return await W(e,t);const s=t.homePage||"pages/index/index",o=s.startsWith("/")?s:`/${s}`;return console.info(`[navigation] 页面栈深度不足,重定向到首页: ${o}`),await B({url:o,params:t.homeParams})}const q=I(W,300);function V(){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 F("GET_CURRENT_PAGE_ERROR",`获取当前页面信息失败: ${e instanceof Error?e.message:String(e)}`),null}}function Y(){try{return getCurrentPages().map(e=>({route:e.route||"",options:e.options||{}}))}catch(e){return F("GET_PAGE_STACK_ERROR",`获取页面栈信息失败: ${e instanceof Error?e.message:String(e)}`),[]}}const X={showToast:!0,successMessage:"复制成功",failMessage:"复制失败",timeout:5e3};async function Q(e,t={}){const n={...X,...t};return e&&"string"==typeof e?e.length>1e4?(n.showToast&&N("复制内容过长",!1,"error"),!1):await s(()=>new Promise(t=>{uni.setClipboardData({data:e,showToast:!1,success:()=>{n.showToast&&N(n.successMessage),t(!0)},fail:()=>{n.showToast&&N(n.failMessage),t(!1)}})}),"clipboard","COPY_TEXT_ERROR")??!1:(n.showToast&&N("复制内容不能为空",!1,"error"),!1)}const Z=r.getInstance();class ee{static instance;cache=new Map;maxCacheSize=100;static getInstance(){return ee.instance||(ee.instance=new ee),ee.instance}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}set(e,t,r={}){try{if(!e||"string"!=typeof e)throw new Error("存储键不能为空");const n={value:t,timestamp:Date.now(),ttl:r.ttl},s=JSON.stringify(n);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,n),!0}catch(e){throw Z.handleError(new n("SET_STORAGE_ERROR",`设置存储失败: ${e instanceof Error?e.message:String(e)}`,"localStorage"),"localStorage"),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(n){return console.warn(`[localStorage] 获取存储失败 [${e}]:`,n),t}}remove(e){try{return!(!e||"string"!=typeof e||(uni.removeStorageSync(e),this.cache.delete(e),0))}catch(t){return Z.handleError(new n("REMOVE_STORAGE_ERROR",`删除存储失败: ${e}`,"localStorage"),"localStorage"),!1}}clear(){try{return uni.clearStorageSync(),this.cache.clear(),!0}catch(e){return Z.handleError(new n("CLEAR_STORAGE_ERROR","清空存储失败","localStorage"),"localStorage"),!1}}getInfo(){try{const e=uni.getStorageInfoSync();return{keys:e.keys||[],currentSize:e.currentSize||0,limitSize:e.limitSize||0}}catch(e){return Z.handleError(new n("GET_STORAGE_INFO_ERROR",`获取存储信息失败: ${e instanceof Error?e.message:String(e)}`,"localStorage"),"localStorage"),{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 Z.handleError(new n("CLEAN_EXPIRED_ERROR",`清理过期数据失败: ${e instanceof Error?e.message:String(e)}`,"localStorage"),"localStorage"),0}}}const te=ee.getInstance();function ne(e,t,n={}){return te.set(e,t,n)}function re(e,t){return te.get(e,t)}function se(e){return e?te.remove(e):te.clear()}async function oe(e,t,n={}){return await s(()=>new Promise(r=>{r(ne(e,t,n))}),"localStorage","SET_STORAGE_ASYNC_ERROR")??!1}async function ae(e,t){return await s(()=>new Promise(n=>{n(re(e,t))}),"localStorage","GET_STORAGE_ASYNC_ERROR")??t}function ie(){return te.getInfo()}function ce(){return te.cleanExpired()}function ue(e,t={}){let n=0;return Object.entries(e).forEach(([e,r])=>{ne(e,r,t)&&n++}),n}function le(e){const t={};return e.forEach(e=>{t[e]=re(e)}),t}function fe(e){const t=e.lastIndexOf(".");if(-1!==t&&t!==e.length-1)return e.slice(t+1).toLowerCase()}function me(e){return`${Date.now()}_${e}_${Math.random().toString(16).slice(2)}`}function ge(e,t){return t&&e>1024*t*1024?{valid:!1,message:`文件大小不能超过 ${t}MB`}:{valid:!0}}function de(e,t){if(0===e.length)return{success:!1,files:e,message:"未选择任何文件"};const{maxSelectFileSizeMB:n,extensions:r}=t;if(n&&e.some(e=>!ge(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 he(e,t,n){const{url:r,maxUploadFileSizeMB:s,showToast:o=!0,beforeUpload:a}=t;if("function"==typeof a&&!await Promise.resolve(a(e)))return{file:e,success:!1,message:"已取消上传"};if(!r){const t="上传地址不能为空";return o&&N(t,!1,"error"),Promise.resolve({file:e,success:!1,message:t})}const i=ge(e.size,s);return i.valid?"h5"===e.platform&&e.raw instanceof File?function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f,autoRevokeObjectURL:m=!1}=t;return new Promise(t=>{const g=e.raw;if(!(g&&g instanceof File)){const n="H5 环境缺少原生文件对象";return i&&N(n,!1,"none"),void t({file:e,success:!1,message:n})}const d=m&&"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&"string"==typeof e.path&&e.path.startsWith("blob:"),h=()=>{if(d)try{URL.revokeObjectURL(e.path)}catch{}},p=new XMLHttpRequest,y=new FormData;y.append(s,g,e.name),o&&Object.keys(o).forEach(e=>{y.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)i&&1===n&&N(c,!1,"none"),h(),t({file:e,success:!0,statusCode:r,data:o});else{const n=`上传失败,状态码:${r}`;i&&N(n,!1,"none"),h(),t({file:e,success:!1,statusCode:r,data:o,message:n})}}),p.addEventListener("error",()=>{const n=u;i&&N(n,!1,"none"),h(),t({file:e,success:!1,message:n})}),p.addEventListener("timeout",()=>{const n=f?`上传超时(${f}ms)`:"上传超时";i&&N(n,!1,"none"),h(),t({file:e,success:!1,message:n})}),p.addEventListener("abort",()=>{h(),t({file:e,success:!1,message:"上传已取消"})}),p.open("POST",r),"number"==typeof f&&f>0&&(p.timeout=f),a&&Object.keys(a).forEach(e=>{p.setRequestHeader(e,a[e])}),p.send(y)})}(e,t,n):function(e,t,n){const{url:r,fieldName:s="file",formData:o,headers:a,showToast:i=!0,successMessage:c="上传成功",failMessage:u="上传失败",onProgress:l,uploadTimeoutMs:f}=t,m="undefined"==typeof uni?null:uni;if(!m||"function"!=typeof m.uploadFile){const t="当前环境不支持文件上传";return i&&N(t,!1,"none"),Promise.resolve({file:e,success:!1,message:t})}return new Promise(t=>{let g=!1,d=null;const h=e=>{g||(g=!0,d&&(clearTimeout(d),d=null),t(e))};let p=null;"number"==typeof f&&f>0&&(d=setTimeout(()=>{try{p&&"function"==typeof p.abort&&p.abort()}catch{}const t=`上传超时(${f}ms)`;i&&N(t,!1,"none"),h({file:e,success:!1,message:t})},f)),p=m.uploadFile({url:r,filePath:e.path,name:s,formData:o,header:a,success:t=>{let r=t.data;try{r=JSON.parse(t.data)}catch{}const s=t.statusCode;if(s>=200&&s<300)i&&1===n&&N(c,!1,"none"),h({file:e,success:!0,statusCode:s,data:r});else{const t=`上传失败,状态码:${s}`;i&&N(t,!1,"none"),h({file:e,success:!1,statusCode:s,data:r,message:t})}},fail:t=>{const n=t?.errMsg||u;i&&N(n,!1,"none"),h({file:e,success:!1,message:n})}}),l&&p&&"function"==typeof p.onProgressUpdate&&p.onProgressUpdate(t=>{l(e,t.progress)})})}(e,t,n):(o&&i.message&&N(i.message,!1,"error"),Promise.resolve({file:e,success:!1,message:i.message}))}async function pe(e){const{showToast:t=!0,failMessage:n="选择文件失败"}=e;try{const r=await async function(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=de(Array.from(r).map((e,t)=>{const n=fe(e.name),r=URL.createObjectURL(e);return{id:me(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=>{const t=function(e){const t=(e||"").trim();if(!t)return"选择文件失败";const n=t.toLowerCase();return n.includes("fail cancel")||n.includes("cancel")?"用户取消选择":/[\u4e00-\u9fff]/.test(t)?t:"选择文件失败"}(e?.errMsg);r({success:!1,files:[],message:t})},a=function(){let e="unknown";return e="h5",e="weixin",e="alipay",e="app","app"}();"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=fe(e.path);return{id:me(t),name:`file_${t}`,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(de(n,e))},fail:o}):s.chooseMessageFile({count:n,type:"all",success:t=>{const n=t.tempFiles.map((e,t)=>{const n=fe(e.name||e.path);return{id:me(t),name:e.name,size:e.size,path:e.path,ext:n,source:"file",platform:a,raw:e}});r(de(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=fe(e.path);return{id:me(t),name:`image_${t}`,size:e.size,path:e.path,ext:n,source:"album",platform:a,raw:e}});r(de(n,e))},fail:o})})}(e)}(e);if(!r.success){const e=r.message||n;return t&&e&&N(e,!1,"none"),[{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],i=await he(a,t,n);r[s]=i}},i=[];for(let e=0;e<s;e+=1)i.push(a());return await Promise.all(i),r}(s,e,o)}catch(e){const r=n;return t&&r&&N(r,!1,"none"),[{file:null,success:!1,message:r}]}}async function ye(e){return pe({...e,type:"image"})}const we=r.getInstance(),Ee=(e,t,r)=>new Promise(s=>{o(()=>{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 o(){try{window.WeixinJSBridge.invoke("getBrandWCPayRequest",e,function(e){console.log("🚀 ~ 微信支付结果:",e),"get_brand_wcpay_request:ok"===e.err_msg?(console.log("✅ 微信支付成功"),t?.(e),s(!0)):(console.warn("❌ 微信支付失败或取消:",e.err_msg),r?.(e),s(!1))})}catch(e){we.handleError(new n("WECHAT_PAY_INVOKE_ERROR",`调用微信支付接口失败: ${e instanceof Error?e.message:String(e)}`,"payment"),"payment");const t={err_msg:"get_brand_wcpay_request:fail",err_desc:e instanceof Error?e.message:"未知错误"};r?.(t),s(!1)}}if(void 0===window.WeixinJSBridge){const e=window.document;e.addEventListener?e.addEventListener("WeixinJSBridgeReady",o,!1):e.attachEvent&&(e.attachEvent("WeixinJSBridgeReady",o),e.attachEvent("onWeixinJSBridgeReady",o))}else o();return!0},"payment","WECHAT_PAY_ERROR",!1)||s(!1)}),Re=r.getInstance(),Se=()=>!("undefined"==typeof navigator||!navigator.userAgent)&&navigator.userAgent.toLowerCase().includes("micromessenger"),Te=()=>"undefined"!=typeof window&&"undefined"!=typeof document,_e=()=>Te()&&Se()&&window.wx||null;let Ae=!1,ve=null;const Oe=(e={})=>{const{timeoutMs:t=1e4}=e;if(Ae||Te()&&window.wx)return Ae=!0,Promise.resolve(!0);if(!Te())return Promise.resolve(!1);if(ve)return ve;const n=e.cdnUrls&&e.cdnUrls.length>0?e.cdnUrls:["https://res.wx.qq.com/open/js/jweixin-1.6.0.js","https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"];return ve=new Promise(e=>{let r=!1,s=null,o=null,a=0;const i=t=>{r||(r=!0,s&&(clearTimeout(s),s=null),o&&o.parentNode&&o.parentNode.removeChild(o),t&&(Ae=!0),ve=null,e(t))},c=()=>{if(a>=n.length)return void i(!1);if(!document.head)return void i(!1);const e=n[a];a+=1;const t=document.createElement("script");o=t,t.src=e,t.async=!0,t.onload=()=>i(!0),t.onerror=()=>{t.parentNode&&t.parentNode.removeChild(t),o=null,c()},document.head.appendChild(t)};s=setTimeout(()=>{i(!1)},t),c()}),ve};let Pe=null;const Ce=async(e,t={})=>{const{timeoutMs:r=1e4}=t;if(!Se())return console.warn("当前不在微信环境中"),!1;if(Pe)return Pe;if(!await Oe({timeoutMs:r}))return Re.handleError(new n("WECHAT_JSSDK_LOAD_FAILED","微信 JS-SDK 加载失败","weixin"),"weixin"),!1;if(!Te())return!1;const s=window.wx;return!!s&&(Pe=new Promise(t=>{let o=!1,a=null;const i=e=>{o||(o=!0,a&&(clearTimeout(a),a=null),Pe=null,t(e))};a=setTimeout(()=>i(!1),r);try{s.config({debug:e.debug||!1,appId:e.appId,timestamp:e.timestamp,nonceStr:e.nonceStr,signature:e.signature,jsApiList:e.jsApiList}),s.ready(()=>{console.log("微信 JS-SDK 初始化完成"),i(!0)}),s.error(e=>{Re.handleError(new n("WECHAT_JSSDK_CONFIG_ERROR",`微信 JS-SDK 配置错误: ${JSON.stringify(e)}`,"weixin"),"weixin"),i(!1)})}catch(e){Re.handleError(new n("WECHAT_JSSDK_CONFIG_EXCEPTION",`微信 JS-SDK 配置异常: ${e instanceof Error?e.message:String(e)}`,"weixin"),"weixin"),i(!1)}}),Pe)},Ie=(e,t={})=>{const{timeoutMs:r=8e3}=t;return new Promise(t=>{const s=_e();if(!s||"function"!=typeof s.checkJsApi)return void t({});let o=!1;const a=e=>{o||(o=!0,t(e))},i=setTimeout(()=>a({}),r);try{s.checkJsApi({jsApiList:e,success:e=>{clearTimeout(i),a(e?.checkResult||{})}})}catch(e){clearTimeout(i),Re.handleError(new n("CHECK_WECHAT_JSAPI_ERROR",`检查微信 JS-SDK API 异常: ${e instanceof Error?e.message:String(e)}`,"weixin"),"weixin"),a({})}})},$e=e=>{const t=_e();t&&(t.updateTimelineShareData?t.updateTimelineShareData(e):t.onMenuShareTimeline&&t.onMenuShareTimeline(e))},xe=e=>{const t=_e();t&&(t.updateAppMessageShareData?t.updateAppMessageShareData(e):t.onMenuShareAppMessage&&t.onMenuShareAppMessage(e))};class Le{static instance;isConfigured=!1;config=null;initPromise=null;constructor(){}static getInstance(){return Le.instance||(Le.instance=new Le),Le.instance}async init(e){return this.initPromise||(this.config=e,this.initPromise=Ce(e).then(e=>(this.isConfigured=e,e)).finally(()=>{this.initPromise=null})),this.initPromise}isReady(){return this.isConfigured&&Se()}getConfig(){return this.config}setShareData(e){this.isReady()?($e(e),xe(e)):console.warn("微信 SDK 未就绪")}}const Me="4.0.0",be={info:0,warn:1,error:2};function De(e={}){const{enableErrorHandler:t=!0,onError:n=null,showInitMessage:s=!1,silent:o=!1,logLevel:a="warn"}=e,i=be[a]||be.warn;if(t){const e=r.getInstance();"function"==typeof n?e.onError(n):e.onError(e=>{((...e)=>{!o&&i<=be.error&&console.error(...e)})(`[UniAppTools] ${e.module} - ${e.code}: ${e.message}`,e)})}if(((...e)=>{!o&&i<=be.info&&console.log(...e)})(`[UniAppTools] v${Me} 初始化完成`),s&&"undefined"!=typeof uni)try{uni.showToast({title:`工具库v${Me}已就绪`,icon:"none",duration:2e3})}catch(e){}}export{r as ErrorHandler,n as UniAppToolsError,Me as VERSION,Le as WechatSDK,b as areaList,le as batchGetStorage,ue as batchSetStorage,H as buildUrl,Ie as checkWechatJSAPI,ce as cleanExpiredStorage,se as clearStorageSync,l as clearSystemCache,Ce as configWechatJSSDK,Q as copyText,I as debounce,O as deepClone,P as deepMerge,M as extractUrlParts,h as getCurrentEnv,V as getCurrentPageInfo,L as getH5UrlParams,w as getMenuButtonBoundingClientRect,T as getNavHeight,E as getNavigationBarHeight,Y as getPageStack,g as getPlatform,y as getStatusBarHeight,ae as getStorage,ie as getStorageInfo,re as getStorageSync,R as getTopBarMetrics,S as getTopNavBarHeight,De as initUniAppTools,Se as isWechat,Oe as loadWechatJSSDK,C as mergeObjects,j as navigateTo,p as onCheckForUpdate,B as reLaunch,G as redirectTo,s as safeAsync,z as safeNavigateTo,o as safeSync,pe as selectAndUpload,ye as selectAndUploadImage,A as setPageIcon,_ as setPageTitle,oe as setStorage,ne as setStorageSync,xe as shareToFriend,$e as shareToTimeline,J as switchTab,$ as throttle,W as useBack,q as useBackDebounced,K as useBackOrHome,D as useCascaderAreaData,U as useRegions,N as useToast,x as useTryCatch,d as useWindowInfo,Ee as weChatOfficialAccountPayment};
@@ -7,18 +7,12 @@
7
7
  * 3. 移除 safeAsync 包装(让错误自然抛出)
8
8
  * 4. 移除性能监控(在开发环境手动测量即可)
9
9
  * 5. 简化代码逻辑,提升可维护性
10
+ * 6. v4.0.0: 函数重新排序,抽取公共错误处理,补充详细注释
10
11
  */
11
- /**
12
- * 导航配置选项
13
- */
14
- interface NavigationOptions {
15
- delta?: number;
16
- timeout?: number;
17
- }
18
12
  /**
19
13
  * 页面跳转选项
20
14
  */
21
- interface NavigateOptions {
15
+ export interface NavigateOptions {
22
16
  url: string;
23
17
  params?: Record<string, any>;
24
18
  animationType?: 'auto' | 'none' | 'slide-in-right' | 'slide-in-left' | 'slide-in-top' | 'slide-in-bottom' | 'fade-in' | 'zoom-out' | 'zoom-fade-out' | 'pop-in';
@@ -26,57 +20,217 @@ interface NavigateOptions {
26
20
  events?: Record<string, Function>;
27
21
  }
28
22
  /**
29
- * 跳转到指定页面
23
+ * 返回导航配置选项
24
+ */
25
+ export interface BackOptions {
26
+ delta?: number;
27
+ timeout?: number;
28
+ }
29
+ /**
30
+ * 返回上一页或跳转首页选项
31
+ */
32
+ export interface BackOrHomeOptions extends BackOptions {
33
+ homePage?: string;
34
+ homeParams?: Record<string, any>;
35
+ }
36
+ /**
37
+ * 构建完整 URL(带参数)
38
+ *
39
+ * @param url 基础URL路径
40
+ * @param params URL查询参数对象
41
+ * @returns 完整的URL字符串
42
+ *
43
+ * @example
44
+ * buildUrl('/pages/detail/detail', { id: 123, type: 'product' })
45
+ * // 返回: '/pages/detail/detail?id=123&type=product'
46
+ */
47
+ export declare function buildUrl(url: string, params?: Record<string, any>): string;
48
+ /**
49
+ * 跳转到指定页面(保留当前页面)
50
+ *
30
51
  * @param options 导航选项
31
- * @returns Promise<boolean> 是否成功
52
+ * @param options.url 目标页面路径(必填)
53
+ * @param options.params URL参数对象
54
+ * @param options.animationType 窗口显示动画效果
55
+ * @param options.animationDuration 窗口动画持续时间(毫秒)
56
+ * @param options.events 页面间通信接口
57
+ * @returns Promise<boolean> 返回 true 表示跳转成功,false 表示失败
58
+ *
59
+ * @example
60
+ * // 基础跳转
61
+ * await navigateTo({ url: '/pages/detail/detail' });
62
+ *
63
+ * // 带参数跳转
64
+ * await navigateTo({
65
+ * url: '/pages/detail/detail',
66
+ * params: { id: 123, type: 'product' }
67
+ * });
68
+ *
69
+ * // 带动画效果跳转
70
+ * await navigateTo({
71
+ * url: '/pages/detail/detail',
72
+ * animationType: 'slide-in-right',
73
+ * animationDuration: 300
74
+ * });
32
75
  */
33
76
  export declare function navigateTo(options: NavigateOptions): Promise<boolean>;
34
77
  /**
35
- * 重定向到指定页面
78
+ * 重定向到指定页面(关闭当前页面)
79
+ *
36
80
  * @param options 导航选项
37
- * @returns Promise<boolean> 是否成功
81
+ * @param options.url 目标页面路径(必填)
82
+ * @param options.params URL参数对象
83
+ * @returns Promise<boolean> 返回 true 表示重定向成功,false 表示失败
84
+ *
85
+ * @example
86
+ * // 重定向到登录页
87
+ * await redirectTo({ url: '/pages/login/login' });
88
+ *
89
+ * // 带参数重定向
90
+ * await redirectTo({
91
+ * url: '/pages/result/result',
92
+ * params: { status: 'success', orderId: '12345' }
93
+ * });
38
94
  */
39
95
  export declare function redirectTo(options: NavigateOptions): Promise<boolean>;
96
+ /**
97
+ * 重新启动到指定页面(关闭所有页面)
98
+ *
99
+ * @param options 导航选项
100
+ * @param options.url 目标页面路径(必填)
101
+ * @param options.params URL参数对象
102
+ * @returns Promise<boolean> 返回 true 表示重启成功,false 表示失败
103
+ *
104
+ * @example
105
+ * // 重启到首页
106
+ * await reLaunch({ url: '/pages/index/index' });
107
+ *
108
+ * // 登录成功后重启应用
109
+ * await reLaunch({
110
+ * url: '/pages/home/home',
111
+ * params: { user: 'john' }
112
+ * });
113
+ */
114
+ export declare function reLaunch(options: NavigateOptions): Promise<boolean>;
115
+ /**
116
+ * 切换到Tab页面(只能打开app.json的tabBar字段定义的页面)
117
+ *
118
+ * @param url Tab页面路径
119
+ * @returns Promise<boolean> 返回 true 表示切换成功,false 表示失败
120
+ *
121
+ * @example
122
+ * // 切换到首页Tab
123
+ * await switchTab('/pages/index/index');
124
+ *
125
+ * // 切换到我的Tab
126
+ * await switchTab('/pages/user/user');
127
+ */
128
+ export declare function switchTab(url: string): Promise<boolean>;
40
129
  /**
41
130
  * 返回上一页
42
- * @param params 返回上一页时传入的参数
131
+ *
132
+ * @param params 返回上一页时传入的参数(会调用目标页面的 init 方法)
43
133
  * @param options 导航选项
44
- * @returns Promise<boolean> 是否成功
134
+ * @param options.delta 返回的页面数,默认1
135
+ * @param options.timeout 超时时间(毫秒),默认5000
136
+ * @returns Promise<boolean> 返回 true 表示导航成功,false 表示失败(页面栈不足或超时)
137
+ *
138
+ * @example
139
+ * // 基础返回
140
+ * await useBack();
141
+ *
142
+ * // 返回并传递刷新参数
143
+ * await useBack({ refresh: true, updatedData: {...} });
144
+ *
145
+ * // 返回两层页面
146
+ * await useBack('', { delta: 2 });
147
+ *
148
+ * // 设置超时时间
149
+ * await useBack('', { timeout: 3000 });
45
150
  */
46
- export declare function useBack(params?: any, options?: NavigationOptions): Promise<boolean>;
151
+ export declare function useBack(params?: any, options?: BackOptions): Promise<boolean>;
47
152
  /**
48
- * 返回上一页或跳转首页选项
153
+ * 安全的页面跳转(带重试机制)
154
+ *
155
+ * @param options 导航选项
156
+ * @param maxRetries 最大重试次数,默认3次
157
+ * @returns Promise<boolean> 返回 true 表示跳转成功,false 表示所有重试都失败
158
+ *
159
+ * @description
160
+ * 当页面跳转失败时,会自动重试指定次数。
161
+ * 重试间隔会逐渐增加:第1次等待1秒,第2次等待2秒,第3次等待3秒
162
+ *
163
+ * @example
164
+ * // 使用默认重试次数(3次)
165
+ * const success = await safeNavigateTo({ url: '/pages/detail/detail' });
166
+ *
167
+ * // 自定义重试次数
168
+ * const success = await safeNavigateTo(
169
+ * { url: '/pages/detail/detail' },
170
+ * 5 // 最多重试5次
171
+ * );
49
172
  */
50
- interface BackOrHomeOptions extends NavigationOptions {
51
- homePage?: string;
52
- homeParams?: Record<string, any>;
53
- }
173
+ export declare function safeNavigateTo(options: NavigateOptions, maxRetries?: number): Promise<boolean>;
54
174
  /**
55
- * 返回上一页,若没有上一页则重定向到首页
175
+ * 返回上一页,若页面栈不足则重定向到首页
176
+ *
56
177
  * @param params 返回上一页时传入的参数
57
178
  * @param options 导航选项
58
- * @returns Promise<boolean> 是否成功
179
+ * @param options.delta 返回的页面数,默认1
180
+ * @param options.timeout 超时时间(毫秒),默认5000
181
+ * @param options.homePage 首页路径,默认 'pages/index/index'
182
+ * @param options.homeParams 首页参数
183
+ * @returns Promise<boolean> 返回 true 表示操作成功,false 表示失败
184
+ *
185
+ * @description
186
+ * 智能返回函数:
187
+ * - 如果页面栈深度足够,执行正常返回
188
+ * - 如果页面栈深度不足(如只有1个页面),则重定向到首页
189
+ *
190
+ * @example
191
+ * // 基础使用(页面栈不足时跳转到默认首页)
192
+ * await useBackOrHome();
193
+ *
194
+ * // 自定义首页路径
195
+ * await useBackOrHome('', {
196
+ * homePage: '/pages/home/home',
197
+ * homeParams: { from: 'auto' }
198
+ * });
199
+ *
200
+ * // 返回两层,不足则跳首页
201
+ * await useBackOrHome('', { delta: 2 });
59
202
  */
60
203
  export declare function useBackOrHome(params?: any, options?: BackOrHomeOptions): Promise<boolean>;
61
204
  /**
62
205
  * 防抖版本的返回上一页
206
+ *
207
+ * @description
208
+ * 300毫秒内的多次调用会被合并为一次,防止用户快速点击导致的重复返回
209
+ *
210
+ * @example
211
+ * // 在按钮点击事件中使用
212
+ * <button @click="useBackDebounced()">返回</button>
63
213
  */
64
214
  export declare const useBackDebounced: typeof useBack;
65
- /**
66
- * 切换到Tab页面
67
- * @param url Tab页面路径
68
- * @returns Promise<boolean> 是否成功
69
- */
70
- export declare function switchTab(url: string): Promise<boolean>;
71
- /**
72
- * 重新启动到指定页面
73
- * @param options 导航选项
74
- * @returns Promise<boolean> 是否成功
75
- */
76
- export declare function reLaunch(options: NavigateOptions): Promise<boolean>;
77
215
  /**
78
216
  * 获取当前页面信息
79
- * @returns 当前页面信息
217
+ *
218
+ * @returns 当前页面信息对象,包含路由路径和参数;如果获取失败返回 null
219
+ * @returns {string} route 当前页面的路由路径
220
+ * @returns {any} options 当前页面的参数对象
221
+ *
222
+ * @example
223
+ * const pageInfo = getCurrentPageInfo();
224
+ * if (pageInfo) {
225
+ * console.log('当前页面路由:', pageInfo.route);
226
+ * console.log('当前页面参数:', pageInfo.options);
227
+ * }
228
+ *
229
+ * // 示例返回值
230
+ * // {
231
+ * // route: 'pages/detail/detail',
232
+ * // options: { id: '123', type: 'product' }
233
+ * // }
80
234
  */
81
235
  export declare function getCurrentPageInfo(): {
82
236
  route: string;
@@ -84,17 +238,27 @@ export declare function getCurrentPageInfo(): {
84
238
  } | null;
85
239
  /**
86
240
  * 获取页面栈信息
87
- * @returns 页面栈数组
241
+ *
242
+ * @returns 页面栈数组,包含所有页面的路由和参数;如果获取失败返回空数组
243
+ *
244
+ * @description
245
+ * 返回完整的页面栈信息,从第一个页面到当前页面。
246
+ * 数组索引0是最底层的页面,最后一个元素是当前页面。
247
+ *
248
+ * @example
249
+ * const stack = getPageStack();
250
+ * console.log('页面栈深度:', stack.length);
251
+ * console.log('第一个页面:', stack[0]);
252
+ * console.log('当前页面:', stack[stack.length - 1]);
253
+ *
254
+ * // 示例返回值
255
+ * // [
256
+ * // { route: 'pages/index/index', options: {} },
257
+ * // { route: 'pages/list/list', options: { category: 'tech' } },
258
+ * // { route: 'pages/detail/detail', options: { id: '123' } }
259
+ * // ]
88
260
  */
89
261
  export declare function getPageStack(): Array<{
90
262
  route: string;
91
263
  options: any;
92
264
  }>;
93
- /**
94
- * 安全的页面跳转(带重试机制)
95
- * @param options 导航选项
96
- * @param maxRetries 最大重试次数
97
- * @returns Promise<boolean> 是否成功
98
- */
99
- export declare function safeNavigateTo(options: NavigateOptions, maxRetries?: number): Promise<boolean>;
100
- export {};