qsh-webview-sdk 2.2.2 → 2.3.0

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,2 +1,2 @@
1
- (function(C,I){typeof exports=="object"&&typeof module!="undefined"?module.exports=I():typeof define=="function"&&define.amd?define(I):(C=typeof globalThis!="undefined"?globalThis:C||self,C.qsh=I())})(this,function(){"use strict";var Zn=Object.defineProperty,Qn=Object.defineProperties;var ei=Object.getOwnPropertyDescriptors;var Ft=Object.getOwnPropertySymbols;var ti=Object.prototype.hasOwnProperty,ri=Object.prototype.propertyIsEnumerable;var Be=(C,I,h)=>I in C?Zn(C,I,{enumerable:!0,configurable:!0,writable:!0,value:h}):C[I]=h,g=(C,I)=>{for(var h in I||(I={}))ti.call(I,h)&&Be(C,h,I[h]);if(Ft)for(var h of Ft(I))ri.call(I,h)&&Be(C,h,I[h]);return C},y=(C,I)=>Qn(C,ei(I));var K=(C,I,h)=>Be(C,typeof I!="symbol"?I+"":I,h);var w=(C,I,h)=>new Promise((re,J)=>{var ne=D=>{try{H(h.next(D))}catch(le){J(le)}},ie=D=>{try{H(h.throw(D))}catch(le){J(le)}},H=D=>D.done?re(D.value):Promise.resolve(D.value).then(ne,ie);H((h=h.apply(C,I)).next())});function C(){return typeof window!="undefined"?window:void 0}function I(){return typeof navigator=="undefined"?"":navigator.userAgent||""}function h(){const t=C();if(!t)return!1;if(t.__wxjs_environment==="miniprogram"||t.wx&&t.wx.miniProgram)return!0;const e=I();return!!(e&&/micromessenger/i.test(e)&&/miniProgram/i.test(e))}function re(){const t=C();return!!(t&&t.plus)}function J(){const t=C();return!!(t&&(t.__dcloud_weex_postMessage||t.__dcloud_weex_))}function ne(){const t=C();return!!(t&&(t.__uniapp_x_postMessage||t.__uniapp_x_))}function ie(){const t=I();return/uni-app/i.test(t)}function H(){const t=I();return/Html5Plus/i.test(t)}function D(){return ie()||H()}function le(){return ne()?"uvue":J()?"nvue":h()?"weixin":re()?"plus":D()?"webview":ie()?"UniApp":"h5"}let ye=null;function fe(t=!1){return ye&&!t||(ye={isWeixinMiniProgram:h(),isAppPlus:re(),isNvue:J(),isUvue:ne(),isUniApp:ie(),isHtml5Plus:H(),isUniAppWebView:D(),type:le()}),ye}const u=fe(),b={PLATFORM_NOT_SUPPORTED:"PLATFORM_NOT_SUPPORTED",API_CALL_FAILED:"API_CALL_FAILED",BRIDGE_NOT_READY:"BRIDGE_NOT_READY",INVALID_PARAMETERS:"INVALID_PARAMETERS",NETWORK_ERROR:"NETWORK_ERROR"};class N extends Error{constructor(e,r,n={},i=null){super(r),this.name="QshError",this.type=e,this.context=n,this.originalError=i,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,N)}toJSON(){return{name:this.name,type:this.type,message:this.message,context:this.context,timestamp:this.timestamp,stack:this.stack}}}const _=class _{static setDebugMode(e){_.isDebugMode=e}static addErrorCallback(e){typeof e=="function"&&_.errorCallbacks.push(e)}static removeErrorCallback(e){const r=_.errorCallbacks.indexOf(e);r>-1&&_.errorCallbacks.splice(r,1)}static handleApiError(e,r={}){let n;return e instanceof N?n=e:e instanceof Error?n=new N(b.API_CALL_FAILED,e.message,r,e):n=new N(b.API_CALL_FAILED,String(e),r),_.logError(n),_.notifyCallbacks(n),n}static handlePlatformNotSupported(e,r){const n=new N(b.PLATFORM_NOT_SUPPORTED,`API "${r}" is not supported on platform "${e}"`,{platformType:e,apiName:r});return _.logError(n),_.notifyCallbacks(n),n}static handleBridgeNotReady(e){const r=new N(b.BRIDGE_NOT_READY,`Bridge is not ready when calling "${e}"`,{apiName:e});return _.logError(r),_.notifyCallbacks(r),r}static handleInvalidParameters(e,r,n,i){const a=new N(b.INVALID_PARAMETERS,`Invalid parameter "${r}" in "${e}": expected ${n}, got ${typeof i}`,{apiName:e,paramName:r,expectedType:n,actualValue:i});return _.logError(a),_.notifyCallbacks(a),a}static safeExecute(e,r={}){try{return e()}catch(n){return _.handleApiError(n,r)}}static safeExecuteAsync(n){return w(this,arguments,function*(e,r={}){try{return yield e()}catch(i){return _.handleApiError(i,r)}})}static logError(e){if(typeof console!="undefined"){const r=`[QSH-SDK Error] ${e.type}: ${e.message}`;_.isDebugMode?console.error(r,{context:e.context,originalError:e.originalError,stack:e.stack,timestamp:e.timestamp}):console.error(r)}}static notifyCallbacks(e){_.errorCallbacks.forEach(r=>{try{r(e)}catch(n){typeof console!="undefined"&&console.error("[QSH-SDK] Error in error callback:",n)}})}static createErrorDecorator(e={}){return function(r,n,i){const a=i.value;return i.value=function(...o){return _.safeExecute(()=>a.apply(this,o),y(g({},e),{method:n,target:r.constructor.name}))},i}}};K(_,"isDebugMode",!1),K(_,"errorCallbacks",[]);let l=_;const x={UNINITIALIZED:"uninitialized",INITIALIZING:"initializing",READY:"ready",ERROR:"error"};class Bt{constructor(){this.state=x.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null,this.handleBridgeReady=this.handleBridgeReady.bind(this),this.handleInitializationError=this.handleInitializationError.bind(this)}getState(){return this.state}isReady(){return this.state===x.READY}isInitializing(){return this.state===x.INITIALIZING}hasError(){return this.state===x.ERROR}getInitializationError(){return this.initializationError}waitForReady(){return this.isReady()?Promise.resolve():this.hasError()?Promise.reject(this.initializationError):(this.readyPromise||(this.readyPromise=new Promise((e,r)=>{this.isReady()?e():this.hasError()?r(this.initializationError):(this.readyCallbacks.push(e),this.errorCallbacks.push(r))})),this.readyPromise)}startInitialization(e){return w(this,null,function*(){if(this.state!==x.UNINITIALIZED)return this.waitForReady();this.state=x.INITIALIZING;try{yield e(),this.handleBridgeReady()}catch(r){throw this.handleInitializationError(r),r}return this.waitForReady()})}handleBridgeReady(){this.state===x.INITIALIZING&&(this.state=x.READY,this.readyCallbacks.forEach(e=>{try{e()}catch(r){l.handleApiError(r,{context:"StateManager.handleBridgeReady"})}}),this.readyCallbacks=[],this.errorCallbacks=[])}handleInitializationError(e){this.state=x.ERROR,this.initializationError=e,this.errorCallbacks.forEach(r=>{try{r(e)}catch(n){l.handleApiError(n,{context:"StateManager.handleInitializationError"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}reset(){this.state=x.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null}onStateChange(e,r){if(this.state===e)return setTimeout(()=>r(this.state),0),()=>{};const n=()=>{this.state===e&&r(this.state)};return e===x.READY?this.readyCallbacks.push(n):e===x.ERROR&&this.errorCallbacks.push(n),()=>{const i=this.readyCallbacks.indexOf(n);i>-1&&this.readyCallbacks.splice(i,1);const a=this.errorCallbacks.indexOf(n);a>-1&&this.errorCallbacks.splice(a,1)}}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasReadyPromise:!!this.readyPromise,hasInitializationError:!!this.initializationError}}}const Y=new Bt,ke=()=>Y.waitForReady(),kt=()=>Y.isReady(),zt=()=>Y.getState(),A={ERROR:0,WARN:1,INFO:2,DEBUG:3,TRACE:4},de={[A.ERROR]:"ERROR",[A.WARN]:"WARN",[A.INFO]:"INFO",[A.DEBUG]:"DEBUG",[A.TRACE]:"TRACE"},f=class f{static setLevel(e){e>=A.ERROR&&e<=A.TRACE&&(f.currentLevel=e,f.log(A.INFO,"Logger",`日志级别设置为: ${de[e]}`))}static enableDevMode(){f.setLevel(A.DEBUG),f.log(A.INFO,"Logger","开发模式已启用")}static enableProdMode(){f.setLevel(A.WARN),f.log(A.INFO,"Logger","生产模式已启用")}static enableModule(e){f.enabledModules.add(e),f.log(A.INFO,"Logger",`模块日志已启用: ${e}`)}static disableModule(e){f.enabledModules.delete(e),f.log(A.INFO,"Logger",`模块日志已禁用: ${e}`)}static shouldLog(e,r){return e>f.currentLevel?!1:r&&f.enabledModules.size>0?f.enabledModules.has(r):!0}static log(e,r,n,...i){if(!f.shouldLog(e,r))return;const a=new Date().toISOString(),o=de[e],d=r?`[${r}]`:"",p=`${f.prefix} ${d} ${n}`,P={timestamp:a,level:e,levelName:o,module:r,message:n,args:i};if(f.addToHistory(P),typeof f.reporter=="function")try{f.reporter(P)}catch(v){}f.outputToConsole(e,p,...i)}static addToHistory(e){f.logHistory.push(e),f.logHistory.length>f.maxHistorySize&&f.logHistory.shift()}static outputToConsole(e,r,...n){if(typeof console=="undefined")return;const i=n&&n.length>0;switch(e){case A.ERROR:i?console.error(r,...n):console.error(r);break;case A.WARN:i?console.warn(r,...n):console.warn(r);break;case A.INFO:i?console.info(r,...n):console.info(r);break;case A.DEBUG:case A.TRACE:i?console.log(r,...n):console.log(r);break}}static error(e,r,...n){f.log(A.ERROR,e,r,...n)}static warn(e,r,...n){f.log(A.WARN,e,r,...n)}static info(e,r,...n){f.log(A.INFO,e,r,...n)}static debug(e,r,...n){f.log(A.DEBUG,e,r,...n)}static trace(e,r,...n){f.log(A.TRACE,e,r,...n)}static getHistory(e){return e&&e>0?f.logHistory.slice(-e):[...f.logHistory]}static clearHistory(){f.logHistory=[],f.log(A.INFO,"Logger","日志历史已清空")}static getStats(){const e={currentLevel:f.currentLevel,currentLevelName:de[f.currentLevel],enabledModules:Array.from(f.enabledModules),historySize:f.logHistory.length,maxHistorySize:f.maxHistorySize},r={};for(const n of Object.keys(de))r[de[n]]=0;return f.logHistory.forEach(n=>{r[n.levelName]++}),e.levelCounts=r,e}static exportToJSON(e){const r=f.getHistory(e),n=f.getStats();return JSON.stringify({exportTime:new Date().toISOString(),stats:n,logs:r},null,2)}static createModuleLogger(e){return{error:(r,...n)=>f.error(e,r,...n),warn:(r,...n)=>f.warn(e,r,...n),info:(r,...n)=>f.info(e,r,...n),debug:(r,...n)=>f.debug(e,r,...n),trace:(r,...n)=>f.trace(e,r,...n)}}static setReporter(e){f.reporter=typeof e=="function"?e:null}};K(f,"currentLevel",A.ERROR),K(f,"enabledModules",new Set),K(f,"logHistory",[]),K(f,"maxHistorySize",1e3),K(f,"prefix","[QSH-SDK]"),K(f,"reporter",null);let M=f;if(typeof window!="undefined"){const t=window.location&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname.includes("192.168.")),e=window.location&&(window.location.search.includes("debug=true")||window.location.search.includes("qsh_debug=1"));let r=!1;try{r=localStorage&&localStorage.getItem("qsh_debug")==="true"}catch(n){}(t||e||r)&&M.enableDevMode()}const O=M.createModuleLogger("Bridge"),m=M.createModuleLogger("Platform"),s=M.createModuleLogger("API"),U=M.createModuleLogger("State"),Re=/complete|loaded|interactive/;function Kt(t){return ie()||H()?(O.debug("检测到 APP 环境,开始初始化"),window.__uniapp_x_postMessage||window.__uniapp_x_||window.__dcloud_weex_postMessage||window.__dcloud_weex_?(O.debug("NVUE/UVUE 环境,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)):window.plus&&Re.test(document.readyState)?(O.debug("Plus 环境已就绪,立即初始化"),setTimeout(t,0)):window.plus?(O.debug("Plus 环境,等待 plusready 事件"),document.addEventListener("plusready",t)):Re.test(document.readyState)?setTimeout(t,0):document.addEventListener("DOMContentLoaded",t,{once:!0}),!0):!1}function Gt(t){return window.wx&&window.wx.miniProgram?(O.debug("检测到微信小程序环境,开始初始化"),window.WeixinJSBridge&&window.WeixinJSBridge.invoke?(O.debug("微信 JSBridge 已就绪,立即初始化"),setTimeout(t,0)):(O.debug("微信 JSBridge 未就绪,等待 WeixinJSBridgeReady 事件"),document.addEventListener("WeixinJSBridgeReady",t)),!0):!1}function Vt(t){return O.info("开始初始化 JSBridge"),Kt(t)?(O.info("使用 APP 环境初始化"),!0):Gt(t)?(O.info("使用微信小程序环境初始化"),!0):(O.debug("使用默认 H5 环境初始化"),Re.test(document.readyState)?(O.debug("DOM 已就绪,立即初始化"),setTimeout(t,0)):(O.debug("DOM 未就绪,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)),!0)}function jt(){return Y.waitForReady()}function ze(){return Y.startInitialization(()=>w(null,null,function*(){return new Promise((t,e)=>{const r=()=>{t()},n=i=>{const a=l.handleApiError(i,{context:"bridge initialization"});e(a)};try{Vt(()=>{r()})}catch(i){n(i)}})}))}const S={UNINITIALIZED:"uninitialized",CONFIGURING:"configuring",CONFIGURED:"configured",ERROR:"error"};function F(){return typeof window=="undefined"||!window.wx?!1:typeof window.wx.config=="function"&&typeof window.wx.ready=="function"&&typeof window.wx.error=="function"}class qt{constructor(){this.state=S.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,this.runtimeConfig={clientId:null,isProd:!1},this.CONFIG_API_URL=this.getConfigApiUrl(this.runtimeConfig.isProd),this.DEFAULT_JS_API_LIST=["chooseImage","uploadImage","previewImage","downloadImage","getLocalImgData","scanQRCode","getLocation","openLocation","updateAppMessageShareData","updateTimelineShareData"],this.handleConfigSuccess=this.handleConfigSuccess.bind(this),this.handleConfigError=this.handleConfigError.bind(this)}configure(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new N(b.INVALID_PARAMETERS,"config参数异常",{config:e});if(!Object.prototype.hasOwnProperty.call(e,"clientId"))throw this.createMissingClientIdError();if(typeof e.clientId!="string"||!e.clientId.trim())throw new N(b.INVALID_PARAMETERS,"clientId参数异常",{clientId:e.clientId});if(Object.prototype.hasOwnProperty.call(e,"isProd")&&typeof e.isProd!="boolean")throw new N(b.INVALID_PARAMETERS,"isProd参数异常",{isProd:e.isProd});const r=e.clientId.trim(),n=e.isProd===!0,i=r!==this.runtimeConfig.clientId||n!==this.runtimeConfig.isProd;return this.runtimeConfig=y(g({},this.runtimeConfig),{clientId:r,isProd:n}),this.CONFIG_API_URL=this.getConfigApiUrl(n),(this.state===S.ERROR||i&&(this.state===S.CONFIGURING||this.state===S.CONFIGURED))&&this.reset(),m.info("Updated Weixin runtime config",{clientId:this.runtimeConfig.clientId,isProd:this.runtimeConfig.isProd,configApiUrl:this.CONFIG_API_URL}),this.getRuntimeConfig()}getRuntimeConfig(){return g({},this.runtimeConfig)}hasClientId(){return typeof this.runtimeConfig.clientId=="string"&&this.runtimeConfig.clientId.length>0}hasRequiredConfig(){return this.isTestMode()||this.hasClientId()}createMissingClientIdError(){return new N(b.INVALID_PARAMETERS,"clientId错误",{field:"clientId"})}getConfigApiUrl(e=!1){return e?"https://tyck-service.xj-agri.gov.cn/api/wechat/mp/jssdk-sign":"https://unified-platform-service.xjy2.cn/api/wechat/mp/jssdk-sign"}getCurrentPageUrl(){if(typeof window=="undefined"||!window.location)throw new Error("无法获取当前页面URL");const e=window.location.href,r=e.indexOf("#");return r!==-1?e.substring(0,r):e}fetchWeixinConfig(){return w(this,null,function*(){const e=this.getCurrentPageUrl();if(this.isTestMode())return m.info("使用测试模式,返回模拟配置"),this.getMockConfig();if(!this.hasClientId())throw this.createMissingClientIdError();const r=this.getConfigApiUrl(this.runtimeConfig.isProd);this.CONFIG_API_URL=r;const n=`${r}?clientId=${this.runtimeConfig.clientId}&url=${encodeURIComponent(e)}`;m.debug("请求微信配置",{url:n});try{const i=yield fetch(n);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);const a=yield i.json();if(m.debug("微信配置响应",a),!a.success||a.code!==200)throw new Error(`配置获取失败: ${a.message||"未知错误"}`);const{data:o}=a;if(!o||!o.appId||!o.timestamp||!o.nonceStr||!o.signature)throw new Error("配置数据格式不正确,缺少必需字段");return o}catch(i){if(m.error("获取微信配置失败",i),this.shouldUseTestMode(i))return m.warn("网络请求失败,降级到测试模式"),this.getMockConfig();throw new N(b.NETWORK_ERROR,`获取微信配置失败: ${i.message}`,{url:n,originalError:i})}})}isTestMode(){if(typeof window=="undefined")return!1;if(new URLSearchParams(window.location.search).get("qsh_test")==="true")return!0;try{if(localStorage.getItem("qsh_test")==="true")return!0}catch(r){}return!1}shouldUseTestMode(e){if(typeof window=="undefined")return!1;const r=window.location.hostname==="localhost"||window.location.hostname.includes("natappfree.cc"),n=!window.wx||!window.wx.miniProgram,i=e.message.includes("CORS")||e.message.includes("Failed to fetch");return r&&n&&i}getMockConfig(){return{appId:"wx_test_app_id",timestamp:Math.floor(Date.now()/1e3).toString(),nonceStr:Math.random().toString(36).substring(2,15),signature:"test_signature_"+Math.random().toString(36).substring(2,10)}}executeWeixinConfig(e){if(this.isTestMode()||e.appId==="wx_test_app_id"){m.info("测试模式:模拟微信配置成功"),setTimeout(()=>{this.handleConfigSuccess()},100);return}if(!F())throw new Error("微信JS-SDK未加载");const r={debug:!1,appId:e.appId,timestamp:parseInt(e.timestamp),nonceStr:e.nonceStr,signature:e.signature,jsApiList:this.DEFAULT_JS_API_LIST};m.info("执行微信配置",r),window.wx.ready(this.handleConfigSuccess),window.wx.error(this.handleConfigError),window.wx.config(r)}handleConfigSuccess(){m.info("微信配置成功"),this.state=S.CONFIGURED,this.lastError=null,this.configPromise=null;const e=[...this.readyCallbacks];this.readyCallbacks=[],this.errorCallbacks=[],e.forEach(r=>{try{r()}catch(n){l.handleApiError(n,{context:"WeixinConfigManager.handleConfigSuccess"})}})}handleConfigError(e){const r=`微信配置验证失败: ${JSON.stringify(e)}`;m.error(r,e);const n=new N(b.API_CALL_FAILED,r,{weixinErrorResponse:e});this.state=S.ERROR,this.lastError=n,this.configPromise=null;const i=[...this.errorCallbacks];this.readyCallbacks=[],this.errorCallbacks=[],i.forEach(a=>{try{a(n)}catch(o){l.handleApiError(o,{context:"WeixinConfigManager.handleConfigError"})}})}autoConfig(){return w(this,null,function*(){return this.hasRequiredConfig()?this.state===S.CONFIGURED?Promise.resolve():this.state===S.ERROR?Promise.reject(this.lastError):this.configPromise?this.configPromise:(this.state=S.CONFIGURING,this.configPromise=this.performAutoConfig(),this.configPromise):(m.warn("clientId为空,等待qsh.config({ clientId })"),Promise.resolve())})}performAutoConfig(){return w(this,null,function*(){try{if(typeof window=="undefined")throw new Error("非浏览器环境无法执行微信配置");if(!F())throw new Error("微信JS-SDK未加载,无法执行配置");const e=yield this.fetchWeixinConfig();return this.executeWeixinConfig(e),yield new Promise((r,n)=>{if(this.state===S.CONFIGURED){r();return}if(this.state===S.ERROR){n(this.lastError);return}this.readyCallbacks.push(r),this.errorCallbacks.push(n)})}catch(e){const r=e instanceof N?e:l.handleApiError(e,{context:"WeixinConfigManager.performAutoConfig"});this.state=S.ERROR,this.lastError=r,this.configPromise=null;const n=[...this.errorCallbacks];throw this.readyCallbacks=[],this.errorCallbacks=[],n.forEach(i=>{try{i(r)}catch(a){l.handleApiError(a,{context:"WeixinConfigManager.performAutoConfig.errorCallback"})}}),r}})}waitForReady(){return this.state===S.CONFIGURED?Promise.resolve():this.state===S.ERROR?Promise.reject(this.lastError):this.hasRequiredConfig()?this.state===S.UNINITIALIZED?this.autoConfig():new Promise((e,r)=>{this.readyCallbacks.push(e),this.errorCallbacks.push(r)}):Promise.reject(this.createMissingClientIdError())}isReady(){return this.state===S.CONFIGURED}getState(){return this.state}getLastError(){return this.lastError}reset(){this.state=S.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,m.debug("微信配置管理器已重置")}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasConfigPromise:!!this.configPromise,hasLastError:!!this.lastError,configApiUrl:this.CONFIG_API_URL,clientId:this.runtimeConfig.clientId,isProd:this.runtimeConfig.isProd,jsApiList:this.DEFAULT_JS_API_LIST}}}const T=new qt;let se=!1,ge=!1,W=null,Ie=!1;function Jt(t){return new Promise(e=>{let r=!1,n=null;const i=d=>w(null,null,function*(){if(!r){if(r=!0,n&&clearTimeout(n),se=!1,ge=d,d)try{yield Ke()}catch(p){m.error("微信配置失败,将使用消息桥作为后备",p)}e()}}),a=()=>i(F()),o=()=>{m.warn("已存在的微信 JS-SDK 脚本加载失败,SDK 将使用消息桥作为后备"),i(!1)};t.addEventListener("load",a,{once:!0}),t.addEventListener("error",o,{once:!0}),setTimeout(()=>{F()&&a()},0),n=setTimeout(()=>{i(F())},3e3)})}function Se(){return w(this,arguments,function*(t={}){const{force:e=!1,recoverFromError:r=!1}=t;if(yield Ge({force:e}),!F())throw new Error("微信 JS-SDK 未正确加载,无法执行配置");r&&Yt()})}function Ht(t=!1){if(typeof window=="undefined")return!1;if(F())return ge=!0,!1;if(ge)return!1;if(t)return!0;const e=navigator.userAgent||"",r=/micromessenger/i.test(e),n=/miniProgram/i.test(e),i=typeof window.__wxjs_environment!="undefined"&&window.__wxjs_environment==="miniprogram",a=!!(window.wx&&window.wx.miniProgram);return r&&(n||i||a)}function Yt(){T.getState()==="error"&&(T.reset(),Ie=!1)}function Ke(){return w(this,null,function*(){if(Ie)return T.waitForReady();Ie=!0,m.info("开始自动配置微信JS-SDK");try{yield T.autoConfig(),m.info("微信JS-SDK自动配置完成")}catch(t){m.error("微信JS-SDK自动配置失败",t)}})}function Ge(t={}){const{force:e=!1}=t;if(typeof window=="undefined")return Promise.resolve();if(F())return ge=!0,Promise.resolve();const r=document.getElementById("weixin-jssdk");return r?W||(se=!0,W=Jt(r).finally(()=>{W=null}),W):Ht(e)?W||(W=new Promise(n=>{se=!0;try{const i=document.createElement("script");i.id="weixin-jssdk",i.type="text/javascript",i.async=!0,i.src="https://res.wx.qq.com/open/js/jweixin-1.6.2.js",i.onload=function(){return w(this,null,function*(){ge=!0,se=!1,m.info("微信 JS-SDK 已自动加载");try{yield Ke()}catch(o){m.error("微信配置失败,将使用消息桥作为后备",o)}n()})},i.onerror=function(){se=!1,m.warn("微信 JS-SDK 加载失败,SDK 将使用消息桥作为后备"),n()},(document.getElementsByTagName("head")[0]||document.documentElement).appendChild(i)}catch(i){se=!1,m.error("注入微信 JS-SDK 失败",i),n()}}).finally(()=>{W=null}),W):Promise.resolve()}function B(){return Se({force:!0,recoverFromError:!0}).then(()=>T.waitForReady())}function Ve(t={}){const e=T.configure(t);return typeof window=="undefined"||Se({force:!0,recoverFromError:T.getState()==="error"}).then(()=>{if(!T.isReady())return T.waitForReady().catch(r=>{m.error("Failed to auto-configure Weixin after qsh.config()",r)});window.wx&&!F()&&m.warn("window.wx 已存在,但微信 JS-SDK 尚未就绪,跳过自动配置")}).catch(r=>{m.error("Failed to preload Weixin JS-SDK",r)}),e}function G(){return T.isReady()}function Xt(){return T.getState()}function Ne(){return T}function Zt(){return w(this,null,function*(){return m.info("手动重试微信配置"),T.reset(),Ie=!1,yield Se({force:!0}),T.waitForReady()})}class Qt{constructor(){this.plugins=new Map,this.installed=new Set,this.installOrder=[],s.debug("插件管理器已初始化")}register(e){return l.safeExecute(()=>{this.validatePlugin(e);const{name:r,version:n}=e;if(this.plugins.has(r)){const i=this.plugins.get(r);s.warn(`插件 ${r} 已注册(版本 ${i.version}),将被覆盖为版本 ${n}`)}return this.plugins.set(r,e),s.info(`插件已注册: ${r}@${n}`),this},{context:"PluginManager.register",pluginName:e==null?void 0:e.name})}validatePlugin(e){if(!e||typeof e!="object")throw new Error("插件必须是一个对象");if(!e.name||typeof e.name!="string")throw new Error("插件必须有 name 属性(字符串)");if(!e.version||typeof e.version!="string")throw new Error(`插件 ${e.name} 必须有 version 属性(字符串)`);if(!e.install||typeof e.install!="function")throw new Error(`插件 ${e.name} 必须实现 install 方法`);if(e.dependencies&&!Array.isArray(e.dependencies))throw new Error(`插件 ${e.name} 的 dependencies 必须是数组`)}install(e,r){return w(this,null,function*(){return l.safeExecute(()=>w(this,null,function*(){if(!this.plugins.has(e))throw new Error(`插件 ${e} 未注册`);if(this.installed.has(e)){s.debug(`插件 ${e} 已安装,跳过`);return}const n=this.plugins.get(e);if(n.dependencies&&n.dependencies.length>0){s.debug(`安装插件 ${e} 的依赖:`,n.dependencies);for(const i of n.dependencies)yield this.install(i,r)}s.info(`开始安装插件: ${e}@${n.version}`),yield n.install(r),this.installed.add(e),this.installOrder.push(e),s.info(`插件安装成功: ${e}@${n.version}`)}),{context:"PluginManager.install",pluginName:e})})}uninstall(e,r){return w(this,null,function*(){return l.safeExecute(()=>w(this,null,function*(){if(!this.installed.has(e)){s.debug(`插件 ${e} 未安装,跳过卸载`);return}const n=this.plugins.get(e);n.uninstall&&typeof n.uninstall=="function"&&(s.info(`开始卸载插件: ${e}`),yield n.uninstall(r)),this.installed.delete(e);const i=this.installOrder.indexOf(e);i>-1&&this.installOrder.splice(i,1),s.info(`插件已卸载: ${e}`)}),{context:"PluginManager.uninstall",pluginName:e})})}uninstallAll(e){return w(this,null,function*(){const r=[...this.installOrder].reverse();for(const n of r)yield this.uninstall(n,e)})}registerAll(e){if(!Array.isArray(e))throw new Error("plugins 必须是数组");return e.forEach(r=>this.register(r)),this}installAll(e,r){return w(this,null,function*(){if(!Array.isArray(e))throw new Error("names 必须是数组");for(const n of e)yield this.install(n,r)})}isRegistered(e){return this.plugins.has(e)}isInstalled(e){return this.installed.has(e)}getPlugin(e){return this.plugins.get(e)}getPluginList(){return Array.from(this.plugins.entries()).map(([e,r])=>({name:e,version:r.version,installed:this.installed.has(e),dependencies:r.dependencies||[]}))}getStats(){return{registered:this.plugins.size,installed:this.installed.size,plugins:this.getPluginList()}}clear(){this.plugins.clear(),this.installed.clear(),this.installOrder=[]}}const he=new Qt;class er{constructor(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("拦截器链已初始化")}useRequest(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.requestInterceptors.push({fn:e,priority:n}),this.requestInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("请求拦截器已注册",{priority:n}),()=>{const i=this.requestInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.requestInterceptors.splice(i,1),s.debug("请求拦截器已移除"))}}useResponse(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.responseInterceptors.push({fn:e,priority:n}),this.responseInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("响应拦截器已注册",{priority:n}),()=>{const i=this.responseInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.responseInterceptors.splice(i,1),s.debug("响应拦截器已移除"))}}runRequest(e){return w(this,null,function*(){let r=g({},e);for(const{fn:n}of this.requestInterceptors){if(r.abort){s.debug("请求被中止",{apiName:r.apiName});break}try{const i=yield n(r);i&&(r=i)}catch(i){s.error("请求拦截器执行失败",i),r.abort=!0,r.error=i;break}}return r})}runResponse(e,r){return w(this,null,function*(){let n=e;for(const{fn:i}of this.responseInterceptors)try{const a=yield i(n,r);a!==void 0&&(n=a)}catch(a){s.error("响应拦截器执行失败",a)}return n})}clear(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("所有拦截器已清空")}getStats(){return{requestInterceptors:this.requestInterceptors.length,responseInterceptors:this.responseInterceptors.length}}}const X=new er,tr={request:t=>(t.startTime=Date.now(),s.debug(`[API 调用] ${t.apiName}`,{params:t.params}),t),response:(t,e)=>{const r=Date.now()-e.startTime;return s.debug(`[API 完成] ${e.apiName}`,{duration:`${r}ms`,success:t==null?void 0:t.success}),t}},V={metrics:new Map,request:t=>(t.perfStartTime=performance.now(),t),response:(t,e)=>{const r=performance.now()-e.perfStartTime;V.metrics.has(e.apiName)||V.metrics.set(e.apiName,{count:0,totalTime:0,minTime:1/0,maxTime:0,avgTime:0});const n=V.metrics.get(e.apiName);return n.count++,n.totalTime+=r,n.minTime=Math.min(n.minTime,r),n.maxTime=Math.max(n.maxTime,r),n.avgTime=n.totalTime/n.count,t},getReport:()=>{const t={};return V.metrics.forEach((e,r)=>{t[r]=g({},e)}),t},clearMetrics:()=>{V.metrics.clear()}};function rr(t={}){const{maxRetries:e=3,retryDelay:r=1e3,shouldRetry:n=i=>!i.success}=t;return{response:(i,a)=>w(null,null,function*(){return a.retryCount||(a.retryCount=0),n(i)&&a.retryCount<e&&(a.retryCount++,s.warn(`API 调用失败,第 ${a.retryCount} 次重试: ${a.apiName}`),yield new Promise(o=>setTimeout(o,r)),i.shouldRetry=!0,i.retryContext=a),i})}}function nr(t={}){return{request:e=>{const r=t[e.apiName];if(r&&typeof r=="function"){const n=r(e.params);n&&(s.error(`参数验证失败: ${e.apiName}`,n),e.abort=!0,e.validationError=n)}return e}}}class ir{constructor(){this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:{type:u.type,isWeixinMiniProgram:u.isWeixinMiniProgram,isAppPlus:u.isAppPlus,isNvue:u.isNvue,isUvue:u.isUvue,features:{}},weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},this.listeners=new Map,this.wildcardListeners=new Set,this.initNetworkListener(),U.debug("状态仓库已初始化")}get(e){return e.split(".").reduce((n,i)=>n!=null?n[i]:void 0,this.state)}set(e,r){const n=e.split("."),i=n.pop(),a=n.reduce((d,p)=>((!d[p]||typeof d[p]!="object")&&(d[p]={}),d[p]),this.state),o=a[i];o!==r&&(a[i]=r,U.debug(`状态已更新: ${e}`,{oldValue:o,newValue:r}),this.notify(e,r,o))}batchUpdate(e){Object.entries(e).forEach(([r,n])=>{this.set(r,n)})}subscribe(e,r){if(typeof r!="function")throw new Error("listener 必须是函数");return e==="*"?(this.wildcardListeners.add(r),U.debug("添加通配符订阅者"),()=>{this.wildcardListeners.delete(r),U.debug("移除通配符订阅者")}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),U.debug(`添加订阅者: ${e}`),()=>{const n=this.listeners.get(e);n&&(n.delete(r),n.size===0&&this.listeners.delete(e),U.debug(`移除订阅者: ${e}`))})}subscribeOnce(e,r){const n=this.subscribe(e,(i,a,o)=>{r(i,a,o),n()});return n}notify(e,r,n){const i=this.listeners.get(e);i&&i.forEach(o=>{try{o(r,n,e)}catch(d){U.error("订阅者执行失败",d)}});const a=e.split(".");for(let o=1;o<a.length;o++){const d=a.slice(0,o).join("."),p=this.listeners.get(d);if(p){const P=this.get(d);p.forEach(v=>{try{v(P,void 0,d)}catch(L){U.error("父路径订阅者执行失败",L)}})}}this.wildcardListeners.forEach(o=>{try{o(r,n,e)}catch(d){U.error("通配符订阅者执行失败",d)}})}initNetworkListener(){if(typeof window!="undefined"&&(window.addEventListener("online",()=>{this.set("network.online",!0)}),window.addEventListener("offline",()=>{this.set("network.online",!1)}),navigator.connection)){const e=navigator.connection,r=()=>{this.set("network.type",e.effectiveType||"unknown")};e.addEventListener("change",r),r()}}setApiLoading(e,r=!0){const n=`api.${e}`,i=this.get(n)||{};this.set(n,y(g({},i),{loading:r,lastCall:r?Date.now():i.lastCall}))}setApiResult(e,r){const n=`api.${e}`,i=this.get(n)||{};this.set(n,y(g({},i),{loading:!1,lastResult:r,lastCallEnd:Date.now()}))}getSnapshot(){return JSON.parse(JSON.stringify(this.state))}reset(){const{platform:e}=this.state;this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:e,weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},U.debug("状态已重置")}getStats(){return{listeners:this.listeners.size,wildcardListeners:this.wildcardListeners.size,apiStates:Object.keys(this.state.api).length}}}const k=new ir,c={SDK_NOT_READY:"E_SDK_001",SDK_INIT_FAILED:"E_SDK_002",SDK_CONFIG_FAILED:"E_SDK_003",PLATFORM_NOT_SUPPORTED:"E_SDK_004",NETWORK_ERROR:"E_NET_001",NETWORK_TIMEOUT:"E_NET_002",NETWORK_OFFLINE:"E_NET_003",IMAGE_CANCELLED:"E_IMG_001",IMAGE_NO_PERMISSION:"E_IMG_002",IMAGE_SIZE_EXCEED:"E_IMG_003",IMAGE_COUNT_EXCEED:"E_IMG_004",IMAGE_FORMAT_ERROR:"E_IMG_005",IMAGE_CONFIG_NOT_READY:"E_IMG_006",LOCATION_CANCELLED:"E_LOC_001",LOCATION_NO_PERMISSION:"E_LOC_002",LOCATION_UNAVAILABLE:"E_LOC_003",LOCATION_TIMEOUT:"E_LOC_004",SCAN_CANCELLED:"E_SCAN_001",SCAN_NO_PERMISSION:"E_SCAN_002",SCAN_INVALID_CODE:"E_SCAN_003",SCAN_CONFIG_NOT_READY:"E_SCAN_004",PERMISSION_DENIED:"E_PERM_001",PERMISSION_CAMERA:"E_PERM_002",PERMISSION_LOCATION:"E_PERM_003",PERMISSION_ALBUM:"E_PERM_004",PERMISSION_MICROPHONE:"E_PERM_005",PARAM_INVALID:"E_PARAM_001",PARAM_MISSING:"E_PARAM_002",PARAM_TYPE_ERROR:"E_PARAM_003",API_TIMEOUT:"E_TIMEOUT_001",UNKNOWN_ERROR:"E_UNKNOWN_999"},Te={[c.SDK_NOT_READY]:"SDK 未就绪",[c.SDK_INIT_FAILED]:"SDK 初始化失败",[c.SDK_CONFIG_FAILED]:"SDK 配置失败",[c.PLATFORM_NOT_SUPPORTED]:"当前平台不支持此功能",[c.NETWORK_ERROR]:"网络错误",[c.NETWORK_TIMEOUT]:"网络超时",[c.NETWORK_OFFLINE]:"网络已断开",[c.IMAGE_CANCELLED]:"用户取消选择图片",[c.IMAGE_NO_PERMISSION]:"无相机/相册权限",[c.IMAGE_SIZE_EXCEED]:"图片大小超出限制",[c.IMAGE_COUNT_EXCEED]:"图片数量超出限制",[c.IMAGE_FORMAT_ERROR]:"图片格式不支持",[c.IMAGE_CONFIG_NOT_READY]:"微信配置未完成",[c.LOCATION_CANCELLED]:"用户取消定位",[c.LOCATION_NO_PERMISSION]:"无定位权限",[c.LOCATION_UNAVAILABLE]:"定位服务不可用",[c.LOCATION_TIMEOUT]:"定位超时",[c.SCAN_CANCELLED]:"用户取消扫码",[c.SCAN_NO_PERMISSION]:"无相机权限",[c.SCAN_INVALID_CODE]:"无效的二维码/条形码",[c.SCAN_CONFIG_NOT_READY]:"微信配置未完成",[c.PERMISSION_DENIED]:"权限被拒绝",[c.PERMISSION_CAMERA]:"无相机权限",[c.PERMISSION_LOCATION]:"无定位权限",[c.PERMISSION_ALBUM]:"无相册权限",[c.PERMISSION_MICROPHONE]:"无麦克风权限",[c.PARAM_INVALID]:"参数无效",[c.PARAM_MISSING]:"缺少必需参数",[c.PARAM_TYPE_ERROR]:"参数类型错误",[c.API_TIMEOUT]:"API 调用超时",[c.UNKNOWN_ERROR]:"未知错误"},$={USER_CANCEL:"user_cancel",PERMISSION:"permission",NETWORK:"network",PARAM:"param",SYSTEM:"system",CONFIG:"config",UNKNOWN:"unknown"},sr={"IMAGE/USER_CANCEL":c.IMAGE_CANCELLED,"IMAGE/PERMISSION_DENIED":c.IMAGE_NO_PERMISSION,"COMMON/UNKNOWN":c.UNKNOWN_ERROR,"COMMON/CONFIG_NOT_READY":c.IMAGE_CONFIG_NOT_READY,"COMMON/PLATFORM_NOT_SUPPORTED":c.PLATFORM_NOT_SUPPORTED},je={weixin:{patterns:[{pattern:/cancel/i,code:c.IMAGE_CANCELLED},{pattern:/permission|auth\s*deny/i,code:c.IMAGE_NO_PERMISSION},{pattern:/config/i,code:c.IMAGE_CONFIG_NOT_READY},{pattern:/timeout/i,code:c.API_TIMEOUT},{pattern:/network/i,code:c.NETWORK_ERROR}],default:c.UNKNOWN_ERROR},uniapp:{patterns:[{pattern:/cancel/i,code:c.IMAGE_CANCELLED},{pattern:/permission|denied/i,code:c.IMAGE_NO_PERMISSION},{pattern:/timeout/i,code:c.API_TIMEOUT},{pattern:/network/i,code:c.NETWORK_ERROR},{pattern:/not_in_container/i,code:c.PLATFORM_NOT_SUPPORTED}],default:c.UNKNOWN_ERROR}},qe={chooseImage:{"fail cancel":c.IMAGE_CANCELLED,"fail auth deny":c.IMAGE_NO_PERMISSION,"fail No Permission":c.IMAGE_NO_PERMISSION,NOT_IN_CONTAINER:c.PLATFORM_NOT_SUPPORTED},scanCode:{"fail cancel":c.SCAN_CANCELLED,"fail auth deny":c.SCAN_NO_PERMISSION,"fail No Permission":c.SCAN_NO_PERMISSION,NOT_IN_CONTAINER:c.PLATFORM_NOT_SUPPORTED}};function Je(t){return t?t.includes("CANCEL")?$.USER_CANCEL:t.includes("PERM")||t.includes("PERMISSION")?$.PERMISSION:t.includes("NET")||t.includes("NETWORK")?$.NETWORK:t.includes("PARAM")?$.PARAM:t.includes("CONFIG")?$.CONFIG:t.includes("SDK")||t.includes("PLATFORM")?$.SYSTEM:$.UNKNOWN:$.UNKNOWN}function ar(t){return t.includes("NET_")||t.includes("TIMEOUT")||t===c.NETWORK_ERROR||t===c.NETWORK_TIMEOUT||t===c.API_TIMEOUT}function or(t){return t.includes("CANCEL")||Je(t)===$.USER_CANCEL}function ae(t){return Te[t]||Te[c.UNKNOWN_ERROR]}class z extends Error{constructor(e,r,n={}){super(r),this.name="StandardError",this.code=e,this.message=r||ae(e),this.platform=n.platform||u.type,this.apiName=n.apiName,this.category=n.category||Je(e),this.retriable=n.retriable!==void 0?n.retriable:ar(e),this.originalError=n.originalError,this.details=n.details||{},this.timestamp=Date.now()}isRetriable(){return this.retriable}isUserAction(){return or(this.code)}toJSON(){return g({code:this.code,message:this.message,platform:this.platform,apiName:this.apiName,category:this.category,retriable:this.retriable,timestamp:this.timestamp,details:this.details},process.env.NODE_ENV!=="production"&&this.originalError?{originalError:this.originalError}:{})}}function He(t,e={}){if(t instanceof z)return t;const{apiName:r,platform:n=u.type}=e;return t&&typeof t.code=="string"&&t.code.includes("/")?cr(t,{apiName:r,platform:n}):t&&(t.errMsg||t.message)?ur(t,{apiName:r,platform:n}):typeof t=="string"?new z(c.UNKNOWN_ERROR,t,{apiName:r,platform:n,originalError:t}):new z(c.UNKNOWN_ERROR,"未知错误",{apiName:r,platform:n,originalError:t,details:{errorType:typeof t}})}function cr(t,e){const{apiName:r,platform:n}=e,i=t.code,a=sr[i]||c.UNKNOWN_ERROR;return s.debug("转换旧版错误码",{legacy:i,new:a}),new z(a,t.message||ae(a),{apiName:r,platform:t.platform||n,originalError:t,details:g({legacyCode:i,legacyVersion:t.version},t.details)})}function ur(t,e){const{apiName:r,platform:n}=e,i=(t.errMsg||t.message||"").toLowerCase();if(r&&qe[r]){const d=qe[r];for(const[p,P]of Object.entries(d))if(i.includes(p.toLowerCase()))return new z(P,ae(P),{apiName:r,platform:n,originalError:t})}const a=je[n]||je.uniapp;for(const{pattern:d,code:p}of a.patterns)if(d.test(i))return new z(p,ae(p),{apiName:r,platform:n,originalError:t});const o=a.default||c.UNKNOWN_ERROR;return new z(o,t.errMsg||t.message||ae(o),{apiName:r,platform:n,originalError:t})}const Ye={response:(t,e)=>{if(!t.success&&t.error){const r=He(t.error,{apiName:e.apiName,platform:u.type});t.error=r.toJSON(),t.errorCode=r.code,t.errorCategory=r.category,t.retriable=r.isRetriable(),s.debug("错误已标准化",{api:e.apiName,code:r.code,category:r.category})}return t}};function lr(t,e={}){return new z(t,ae(t),e)}function fr(t){return t instanceof z}function dr(t,e,r){return e?Promise.race([t(),new Promise((n,i)=>setTimeout(()=>i(new Error(`Init task timeout: ${r}`)),e))]):t()}function gr(){return w(this,arguments,function*(t=[],e={}){for(const r of t){const n=(r==null?void 0:r.name)||"anonymous-task",i=(r==null?void 0:r.run)||r;if(typeof i=="function")try{yield dr(()=>Promise.resolve().then(()=>i()),r.timeoutMs,n),typeof r.onSuccess=="function"&&r.onSuccess()}catch(a){if(typeof r.onError=="function"&&r.onError(a),typeof e.onError=="function")e.onError(a,r);else throw a}}})}class Xe{constructor(e){this.name=e}processNavigationOptions(e={}){const{url:r,delta:n=1}=e,i=r&&encodeURI(r),a=parseInt(n)||1;return y(g({},e),{url:i,delta:a})}processMessageOptions(e={}){const{data:r={}}=e;return{data:r}}navigateTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("navigateTo",r)}navigateBack(e={}){const r=this.processNavigationOptions(e);return this.performNavigation("navigateBack",r)}switchTab(e){const r=this.processNavigationOptions(e);return this.performNavigation("switchTab",r)}reLaunch(e){const r=this.processNavigationOptions(e);return this.performNavigation("reLaunch",r)}redirectTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("redirectTo",r)}postMessage(e={}){const r=this.processMessageOptions(e);return this.performPostMessage(r)}getEnv(e){return this.performGetEnv(e)}performNavigation(e,r){throw new Error(`${this.name} platform must implement performNavigation method`)}performPostMessage(e){throw new Error(`${this.name} platform must implement performPostMessage method`)}performGetEnv(e){throw new Error(`${this.name} platform must implement performGetEnv method`)}}let pe=[];function hr(){if(pe.length===0&&window.plus){const t=plus.webview.currentWebview();if(!t)throw new Error("plus.webview.currentWebview() is undefined");const e=t.parent(),r=e?e.id:t.id;pe.push(r)}return pe}function pr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:e};return window.__uniapp_x_postMessage?window.__uniapp_x_postMessage(i):window.__uniapp_x_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:pe}};window.__uniapp_x_postMessage?window.__uniapp_x_postMessageToService(n):window.__uniapp_x_.postMessageToService(JSON.stringify(n))}function mr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:[e]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(i):window.__dcloud_weex_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:pe}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(n):window.__dcloud_weex_.postMessageToService(JSON.stringify(n))}function wr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e},n=hr();if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:n}},"__uniapp__service");else{const i=JSON.stringify(r),a=JSON.stringify(n);plus.webview.getLaunchWebview().evalJS(`UniPlusBridge.subscribeHandler("WEB_INVOKE_APPSERVICE",${i},${a});`)}}function Er(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""},"*")}function me(t,e){ne()?pr(t,e):J()?mr(t,e):re()?wr(t,e):Er(t,e)}class Ze extends Xe{constructor(){super("weixin")}isWeixinApiAvailable(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram}performNavigation(e,r){return l.safeExecute(()=>{const{url:n,delta:i}=r;if(m.debug(`微信平台执行导航操作: ${e}`,r),this.isWeixinApiAvailable()){const o=window.wx.miniProgram[e];if(typeof o=="function"){m.debug(`使用微信原生 API: wx.miniProgram.${e}`);const d=e==="navigateBack"?{delta:i}:{url:n};return o.call(window.wx.miniProgram,d)}}m.debug(`使用消息桥接执行: ${e}`),me(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return l.safeExecute(()=>{const{data:r}=e;if(this.isWeixinApiAvailable())return window.wx.miniProgram.postMessage({data:r});me("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return l.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");if(this.isWeixinApiAvailable()&&window.wx.miniProgram.getEnv)return window.wx.miniProgram.getEnv(e);e({miniprogram:!0,weixin:!0})},{platform:this.name,method:"performGetEnv"})}}const Z=new Ze;var Qe=Object.freeze({__proto__:null,WeixinPlatform:Ze,getEnv:t=>Z.getEnv(t),navigateBack:t=>Z.navigateBack(t),navigateTo:t=>Z.navigateTo(t),postMessage:t=>Z.postMessage(t),reLaunch:t=>Z.reLaunch(t),redirectTo:t=>Z.redirectTo(t),switchTab:t=>Z.switchTab(t)});class et extends Xe{constructor(){super("app")}performNavigation(e,r){return l.safeExecute(()=>{const{url:n,delta:i}=r;me(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return l.safeExecute(()=>{const{data:r}=e;me("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return l.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");const r={};let n=!1;ne()?(r.uvue=!0,n=!0):J()?(r.nvue=!0,n=!0):re()&&(r.plus=!0,n=!0),n?r.app=!0:r.h5=!0,e(r)},{platform:this.name,method:"performGetEnv"})}}const Q=new et;var tt=Object.freeze({__proto__:null,AppPlatform:et,getEnv:t=>Q.getEnv(t),navigateBack:t=>Q.navigateBack(t),navigateTo:t=>Q.navigateTo(t),postMessage:t=>Q.postMessage(t),reLaunch:t=>Q.reLaunch(t),redirectTo:t=>Q.redirectTo(t),switchTab:t=>Q.switchTab(t)});function we(){return h()?Qe:tt}function yr(t){return we().navigateTo(t)}function Ir(t){return we().navigateBack(t)}function Ar(t){return we().switchTab(t)}function Or(t){return we().reLaunch(t)}function Cr(t){return we().redirectTo(t)}function rt(){return h()?Qe:tt}function _r(t={}){return rt().postMessage(t)}function Pr(t){return rt().getEnv(t)}function Rr(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function Sr(){return"qsh_callback_"+Date.now()+"_"+Math.random().toString(36).substring(2,9)}class Nr{constructor(){this.callbacks=new Map,this.timeouts=new Map,this.persistentCallbacksByApi=new Map,this.defaultTimeout=3e4,typeof window!="undefined"&&(window.qshWebviewCallbacks||(window.qshWebviewCallbacks={})),O.debug("WebView 桥接器已初始化")}callApi(i){return w(this,arguments,function*(e,r={},n={}){return l.safeExecute(()=>w(this,null,function*(){var P;if(typeof window!="undefined"&&window===window.parent&&!window.plus&&!window.__uniapp_x_postMessage&&!window.__uniapp_x_&&!window.__dcloud_weex_postMessage&&!window.__dcloud_weex_){const v=new N(b.PLATFORM_NOT_SUPPORTED,"当前不在宿主 WebView 容器中,无法发送消息");n&&typeof n.fail=="function"&&n.fail({errMsg:v.message,code:"NOT_IN_CONTAINER"}),n&&typeof n.complete=="function"&&n.complete({success:!1,error:{errMsg:v.message}});return}const o={apiName:e,params:r,callbacks:n,timestamp:Date.now(),abort:!1,metadata:{}};k.setApiLoading(e,!0);const d=yield X.runRequest(o);if(d.abort){O.warn("API 调用被拦截器中止",{api:e}),k.setApiLoading(e,!1),n.fail&&n.fail({errMsg:((P=d.error)==null?void 0:P.message)||"API 调用被中止",code:"INTERCEPTED"}),n.complete&&n.complete({success:!1});return}const p=Sr();if(n.success||n.fail||n.complete){if(this.callbacks.set(p,y(g({},n),{context:d})),window.qshWebviewCallbacks[p]=Fe=>{this.handleCallback(p,Fe)},r.isPersistent&&(this.persistentCallbacksByApi.has(e)||this.persistentCallbacksByApi.set(e,new Set),this.persistentCallbacksByApi.get(e).add(p)),r.isPersistent||r.disableTimeout)O.info(`API ${e} 禁用超时清理,将等待回调返回后清理`,{callbackId:p,isPersistent:r.isPersistent,disableTimeout:r.disableTimeout});else{const Fe=setTimeout(()=>{O.warn("API 调用超时,自动清理回调",{api:e,callbackId:p}),n.fail&&n.fail({errMsg:`API ${e} 调用超时`,code:"TIMEOUT"}),this.cleanupCallback(p)},r.timeout||this.defaultTimeout);this.timeouts.set(p,Fe)}const L={type:"qsh_api_call",api:e,params:d.params,callbackId:p,timestamp:Date.now()};O.info("发送 API 调用消息",{api:e,callbackId:p,hasSuccess:!!n.success,hasFail:!!n.fail}),console.log("message:",JSON.stringify(Rr(L),null,2)),me("postMessage",L)}}),{context:"WebViewBridge.callApi",api:e})})}handleCallback(e,r){return w(this,null,function*(){return l.safeExecute(()=>w(this,null,function*(){var v,L;const n=this.callbacks.get(e);if(!n){O.warn("未找到回调函数",{callbackId:e});return}const{success:i,fail:a,complete:o,context:d}=n;O.debug("处理回调",{callbackId:e,result:r});const p=yield X.runResponse(r,d);d&&k.setApiResult(d.apiName,p),p.success&&i?i(p.data):!p.success&&a&&a(p.error||{errMsg:"操作失败"}),o&&o(p),((L=(v=n.context)==null?void 0:v.params)==null?void 0:L.isPersistent)?O.debug("持久监听API:保留回调",{callbackId:e}):(this.cleanupCallback(e),O.debug("回调执行完成,已清理",{callbackId:e}))}),{context:"WebViewBridge.handleCallback",callbackId:e})})}cleanupCallback(e){const r=this.timeouts.get(e);if(r&&(clearTimeout(r),this.timeouts.delete(e)),this.callbacks.delete(e),typeof window!="undefined"&&window.qshWebviewCallbacks&&delete window.qshWebviewCallbacks[e],this.persistentCallbacksByApi&&this.persistentCallbacksByApi.size>0){const n=[];this.persistentCallbacksByApi.forEach((i,a)=>{i.has(e)&&(i.delete(e),i.size===0&&n.push(a))}),n.forEach(i=>this.persistentCallbacksByApi.delete(i))}}clearCallbacks(){O.debug("清理所有回调",{count:this.callbacks.size}),this.timeouts.forEach(e=>clearTimeout(e)),this.timeouts.clear(),this.callbacks.clear(),this.persistentCallbacksByApi&&this.persistentCallbacksByApi.clear(),typeof window!="undefined"&&window.qshWebviewCallbacks&&Object.keys(window.qshWebviewCallbacks).forEach(e=>{e.startsWith("qsh_callback_")&&delete window.qshWebviewCallbacks[e]})}cleanupPersistentCallbacksByApi(e){const r=this.persistentCallbacksByApi.get(e);if(!r||r.size===0)return 0;const n=Array.from(r);return n.forEach(i=>this.cleanupCallback(i)),this.persistentCallbacksByApi.delete(e),O.info("已清理持久回调",{api:e,count:n.length}),n.length}getStatus(){return{isSupported:typeof window!="undefined"&&window.uni&&typeof window.uni.postMessage=="function",activeCallbacks:this.callbacks.size,globalCallbacksCount:typeof window!="undefined"&&window.qshWebviewCallbacks?Object.keys(window.qshWebviewCallbacks).length:0}}}const nt=new Nr,R=(t,e,r)=>nt.callApi(t,e,r),oe=t=>nt.cleanupPersistentCallbacksByApi(t),Ae={ALBUM:"album",CAMERA:"camera"},Oe={ORIGINAL:"original",COMPRESSED:"compressed"},Tr={count:9,sizeType:[Oe.ORIGINAL,Oe.COMPRESSED],sourceType:[Ae.ALBUM,Ae.CAMERA]};function Mr(t={}){const e=g(g({},Tr),t);return Array.isArray(e.sizeType)||(e.sizeType=[e.sizeType].filter(Boolean)),Array.isArray(e.sourceType)||(e.sourceType=[e.sourceType].filter(Boolean)),e.count=Math.max(1,Math.min(9,parseInt(e.count)||1)),e.sizeType.length===0&&(e.sizeType=[Oe.COMPRESSED]),e.sourceType.length===0&&(e.sourceType=[Ae.ALBUM]),e}function it(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(u.type)}function st(t){return l.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!G()){s.info("等待微信配置完成"),B().then(()=>st(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信图片选择",t),window.wx.chooseImage({count:t.count,sizeType:t.sizeType,sourceType:t.sourceType,success:r=>{var n,i;s.info("微信图片选择成功",{count:((n=r.localIds)==null?void 0:n.length)||0}),(i=t.success)==null||i.call(t,r)},fail:r=>{var n;s.error("微信图片选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"chooseImageInWeixin",platform:"weixin"})}function Lr(t){return l.safeExecute(()=>{s.debug("通过 WebView 桥接调用图片选择",t),R("chooseImage",y(g({},t),{disableTimeout:!0}),{success:e=>{var r,n;s.info("UniApp 图片选择成功",{count:((r=e==null?void 0:e.tempFilePaths)==null?void 0:r.length)||0}),(n=t.success)==null||n.call(t,e)},fail:e=>{var r;s.error("UniApp 图片选择失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"chooseImageInUniApp",platform:"uniapp"})}function br(t={}){return l.safeExecute(()=>{var r;if(!it()){const n={errMsg:`当前环境 (${u.type}) 不支持图片选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持图片选择",{platform:u.type}),(r=t.fail)==null||r.call(t,n);return}const e=Mr(t);s.info("开始选择图片",{platform:u.type,count:e.count,sizeType:e.sizeType,sourceType:e.sourceType}),h()?st(e):Lr(e)},{context:"chooseImage",options:t})}function xr(){return{supported:it(),environment:u.type,implementation:h()?"weixin":"webview",features:{multipleSelection:!0,sizeTypeSelection:!0,sourceTypeSelection:!0,asyncSupport:!0}}}const ee={QR_CODE:"qrCode",BAR_CODE:"barCode",DATA_MATRIX:"datamatrix",PDF417:"pdf417"},vr={onlyFromCamera:!0,scanType:[ee.QR_CODE,ee.BAR_CODE]};function Dr(t={}){const e=g(g({},vr),t);return Array.isArray(e.scanType)||(e.scanType=[e.scanType].filter(Boolean)),e.scanType.length===0&&(e.scanType=[ee.QR_CODE,ee.BAR_CODE]),e.onlyFromCamera=!!e.onlyFromCamera,e}function at(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(u.type)}function ot(t){return l.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!G()){s.info("等待微信配置完成"),B().then(()=>ot(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信扫码",t),window.wx.scanQRCode({needResult:1,scanType:t.scanType,success:r=>{var i;s.info("微信扫码成功",{result:r.resultStr});const n={result:r.resultStr,scanType:Ur(r.resultStr),charSet:"utf-8",errMsg:"scanCode:ok"};(i=t.success)==null||i.call(t,n)},fail:r=>{var n;s.error("微信扫码失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"scanCodeInWeixin",platform:"weixin"})}function Ur(t){return t?t.length>50||/[^\d]/.test(t)?ee.QR_CODE:ee.BAR_CODE:"unknown"}function Wr(t){return l.safeExecute(()=>{s.debug("通过 WebView 桥接调用扫码",t),R("scanCode",y(g({},t),{disableTimeout:!0}),{success:e=>{var r;s.info("UniApp 扫码成功",{result:e==null?void 0:e.result,scanType:e==null?void 0:e.scanType}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 扫码失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"scanCodeInUniApp",platform:"uniapp"})}function $r(t={}){return l.safeExecute(()=>{var r;if(!at()){const n={errMsg:`当前环境 (${u.type}) 不支持扫码功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持扫码",{platform:u.type}),(r=t.fail)==null||r.call(t,n);return}const e=Dr(t);s.info("开始扫码",{platform:u.type,onlyFromCamera:e.onlyFromCamera,scanType:e.scanType}),h()?ot(e):Wr(e)},{context:"scanCode",options:t})}function Fr(){return{supported:at(),environment:u.type,implementation:h()?"weixin":"webview",features:{onlyFromCamera:!0,scanTypeSelection:!0,multipleTypes:!0,asyncSupport:!0}}}const ce={WGS84:"wgs84",GCJ02:"gcj02",BD09:"bd09"},Br={type:ce.WGS84,altitude:!1},kr={scale:18};function zr(t={}){const e=g(g({},Br),t);return Object.values(ce).includes(e.type)||(e.type=ce.WGS84),e.altitude=!!e.altitude,e}function Kr(t={}){const e=g({},t);return Object.values(ce).includes(e.type)||(e.type=ce.WGS84),e.needFullAccuracy=!!e.needFullAccuracy,e}function Gr(t={}){const e=g(g({},kr),t);if(e.latitude===void 0||e.latitude===null)throw{errMsg:"缺少必需参数:latitude(纬度)",code:"PARAM_MISSING"};if(typeof e.latitude!="number")throw{errMsg:`latitude 参数类型错误:期望 number,实际 ${typeof e.latitude}`,code:"PARAM_TYPE_ERROR",details:{param:"latitude",expected:"number",actual:typeof e.latitude,value:e.latitude}};if(e.latitude<-90||e.latitude>90)throw{errMsg:`latitude 超出范围:有效范围 -90 ~ 90,实际值 ${e.latitude}`,code:"PARAM_INVALID",details:{param:"latitude",value:e.latitude,validRange:"-90 ~ 90"}};if(e.longitude===void 0||e.longitude===null)throw{errMsg:"缺少必需参数:longitude(经度)",code:"PARAM_MISSING"};if(typeof e.longitude!="number")throw{errMsg:`longitude 参数类型错误:期望 number,实际 ${typeof e.longitude}`,code:"PARAM_TYPE_ERROR",details:{param:"longitude",expected:"number",actual:typeof e.longitude,value:e.longitude}};if(e.longitude<-180||e.longitude>180)throw{errMsg:`longitude 超出范围:有效范围 -180 ~ 180,实际值 ${e.longitude}`,code:"PARAM_INVALID",details:{param:"longitude",value:e.longitude,validRange:"-180 ~ 180"}};if(e.scale!==void 0&&e.scale!==null){const r=Number(e.scale);isNaN(r)?(s.warn("scale 参数无效,使用默认值 18",{scale:e.scale}),e.scale=18):e.scale=Math.max(1,Math.min(28,Math.floor(r)))}return e}function Me(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(u.type)}function ct(t){return l.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!G()){s.info("等待微信配置完成"),B().then(()=>ct(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信定位",t),window.wx.getLocation({type:t.type,success:r=>{var n;s.info("微信定位成功",{latitude:r.latitude,longitude:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信定位失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"getLocationInWeixin",platform:"weixin"})}function ut(t){return l.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!G()){s.info("等待微信配置完成"),B().then(()=>ut(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信查看位置",t),window.wx.openLocation({latitude:t.latitude,longitude:t.longitude,name:t.name||"",address:t.address||"",scale:t.scale||18,infoUrl:t.infoUrl||"",success:r=>{var n;s.info("微信查看位置成功"),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信查看位置失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"openLocationInWeixin",platform:"weixin"})}function Vr(t){return l.safeExecute(()=>{s.debug("通过 WebView 桥接调用获取位置",t),R("getLocation",t,{success:e=>{var r;s.info("UniApp 获取位置成功",{latitude:e==null?void 0:e.latitude,longitude:e==null?void 0:e.longitude}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 获取位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getLocationInUniApp",platform:"uniapp"})}function jr(t){return l.safeExecute(()=>{s.debug("通过 WebView 桥接调用查看位置",t),R("openLocation",t,{success:e=>{var r;s.info("UniApp 查看位置成功"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 查看位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"openLocationInUniApp",platform:"uniapp"})}function qr(t={}){return l.safeExecute(()=>{var r;if(!Me()){const n={errMsg:`当前环境 (${u.type}) 不支持定位功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持定位",{platform:u.type}),(r=t.fail)==null||r.call(t,n);return}const e=zr(t);s.info("开始获取位置",{platform:u.type,type:e.type,altitude:e.altitude}),h()?ct(e):Vr(e)},{context:"getLocation",options:t})}function Jr(t={}){return l.safeExecute(()=>{var r,n,i;if(!Me()){const a={errMsg:`当前环境 (${u.type}) 不支持查看位置功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持查看位置",{platform:u.type}),(r=t.fail)==null||r.call(t,a);return}let e;try{e=Gr(t)}catch(a){s.error("参数验证失败",a),(n=t.fail)==null||n.call(t,a),(i=t.complete)==null||i.call(t);return}s.info("开始查看位置",{platform:u.type,latitude:e.latitude,longitude:e.longitude,name:e.name}),h()?ut(e):jr(e)},{context:"openLocation",options:t})}function Hr(){const t=h();return{supported:Me(),environment:u.type,implementation:t?"weixin":"webview",features:{getLocation:!0,openLocation:!0,coordinateTypes:!0,altitudeSupport:!0,asyncSupport:!0,onLocationChange:!t}}}const j=new Set,q=new Set;function lt(t,e,r){t.forEach(n=>{if(typeof n=="function"){l.safeExecute(()=>n(e),{context:r});return}s.warn("监听回调不是函数,已跳过",{type:typeof n})})}function Yr(t={}){return l.safeExecute(()=>{var r,n;if(h()){const i={errMsg:`当前环境 (${u.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};s.error("当前环境不支持此接口",{platform:u.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=Kr(t);s.info("正在开启定位监听"),R("startLocationUpdate",{type:e.type,needFullAccuracy:e.needFullAccuracy},{success:i=>{var a;s.info("定位监听已启动"),(a=t.success)==null||a.call(t,i)},fail:i=>{var a;return(a=t.fail)==null?void 0:a.call(t,i)},complete:t.complete})},{context:"startLocationUpdate"})}function Xr(t={}){return l.safeExecute(()=>{var e,r;if(h()){const n={errMsg:`当前环境 (${u.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};s.error("当前环境不支持此接口",{platform:u.type}),(e=t.fail)==null||e.call(t,n),(r=t.complete)==null||r.call(t,n);return}s.info("正在停止定位监听"),R("stopLocationUpdate",t,{success:n=>{var i;s.info("定位监听已停止"),(i=t.success)==null||i.call(t,n)},fail:n=>{var i;return(i=t.fail)==null?void 0:i.call(t,n)},complete:t.complete})},{context:"stopLocationUpdate"})}function Zr(t){return l.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:u.type});return}if(typeof t!="function")throw s.error("onLocationChange 回调不是函数",{type:typeof t}),{errMsg:"onLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};const e=j.size>0;j.add(t),e||(s.debug("注册实时位置变化监听器"),R("onLocationChange",{isPersistent:!0},{success:r=>{s.debug("收到实时位置推送",r),lt(j,r,"onLocationChange")},fail:r=>{s.warn("位置变化监听出错,请通过 onLocationChangeError 监听错误",r),j.delete(t),j.size===0&&oe("onLocationChange")}}))},{context:"onLocationChange"})}function Qr(t){return l.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:u.type});return}if(t&&typeof t!="function")throw s.error("offLocationChange 回调不是函数",{type:typeof t}),{errMsg:"offLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};t?j.delete(t):j.clear(),!(j.size>0)&&(s.info("移除位置变化监听器"),R("offLocationChange",{},{success:()=>{s.info("位置变化监听已移除"),oe("onLocationChange")},fail:e=>{s.error("移除位置变化监听失败",e),oe("onLocationChange")}}))},{context:"offLocationChange"})}function en(t){return l.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:u.type});return}if(typeof t!="function")throw s.error("onLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"onLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};const e=q.size>0;q.add(t),e||(s.debug("注册位置更新错误监听器"),R("onLocationChangeError",{isPersistent:!0},{success:r=>{s.warn("持续定位发生异常",r),lt(q,r,"onLocationChangeError")},fail:r=>{s.warn("位置更新错误监听注册失败",r),q.delete(t),q.size===0&&oe("onLocationChangeError")}}))},{context:"onLocationChangeError"})}function tn(t){return l.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:u.type});return}if(t&&typeof t!="function")throw s.error("offLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"offLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};t?q.delete(t):q.clear(),!(q.size>0)&&(s.info("移除定位错误监听器"),R("offLocationChangeError",{},{success:()=>{s.info("定位错误监听已移除"),oe("onLocationChangeError")},fail:e=>{s.error("移除定位错误监听失败",e),oe("onLocationChangeError")}}))},{context:"offLocationChangeError"})}const rn={latitude:null,longitude:null};function nn(t={}){const e=g(g({},rn),t);return e.latitude!==null&&e.latitude!==void 0&&(typeof e.latitude!="number"?(s.warn("latitude 参数类型错误,已忽略",{latitude:e.latitude}),e.latitude=null):(e.latitude<-90||e.latitude>90)&&(s.warn("latitude 超出范围,已忽略",{latitude:e.latitude}),e.latitude=null)),e.longitude!==null&&e.longitude!==void 0&&(typeof e.longitude!="number"?(s.warn("longitude 参数类型错误,已忽略",{longitude:e.longitude}),e.longitude=null):(e.longitude<-180||e.longitude>180)&&(s.warn("longitude 超出范围,已忽略",{longitude:e.longitude}),e.longitude=null)),e}function ft(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(u.type)}function dt(t){return l.safeExecute(()=>{var n;if(!window.wx){const i={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(n=t.fail)==null||n.call(t,i);return}if(!G()){s.info("等待微信配置完成"),B().then(()=>dt(t)).catch(i=>{var a;s.error("微信配置失败",i),(a=t.fail)==null||a.call(t,{errMsg:`微信配置失败: ${i.message}`})});return}s.debug("调用微信位置选择",t);const e={success:i=>{var o;s.info("微信位置选择成功",{name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude});const a={name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude,errMsg:"chooseLocation:ok"};(o=t.success)==null||o.call(t,a)},fail:i=>{var a;s.error("微信位置选择失败",i),(a=t.fail)==null||a.call(t,i)},complete:t.complete},r={};t.latitude!==null&&t.latitude!==void 0&&(r.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(r.longitude=t.longitude),window.wx.chooseLocation(y(g({},r),{success:e.success,fail:e.fail,complete:e.complete}))},{context:"chooseLocationInWeixin",platform:"weixin"})}function sn(t){return l.safeExecute(()=>{s.debug("通过 WebView 桥接调用位置选择",t);const e={disableTimeout:!0,success:r=>{var n;s.info("UniApp 位置选择成功",{name:r==null?void 0:r.name,address:r==null?void 0:r.address,latitude:r==null?void 0:r.latitude,longitude:r==null?void 0:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("UniApp 位置选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete};t.latitude!==null&&t.latitude!==void 0&&(e.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(e.longitude=t.longitude),R("chooseLocation",e,{success:r=>{e.success(r)},fail:r=>{e.fail(r)},complete:e.complete})},{context:"chooseLocationInUniApp",platform:"uniapp"})}function an(t={}){return l.safeExecute(()=>{var r;if(!ft()){const n={errMsg:`当前环境 (${u.type}) 不支持位置选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持位置选择",{platform:u.type}),(r=t.fail)==null||r.call(t,n);return}const e=nn(t);s.info("开始选择位置",{platform:u.type,latitude:e.latitude,longitude:e.longitude}),h()?dt(e):sn(e)},{context:"chooseLocation",options:t})}function on(){return{supported:ft(),environment:u.type,implementation:h()?"weixin":"webview",features:{chooseLocation:!0,centerPoint:!0,asyncSupport:!0}}}const gt=new Map;function cn(t,e={}){gt.set(t,e)}function ht(t,e){const r=gt.get(t);if(r)return r[e]||r.default}const un={0:"WXSceneSession",1:"WXSceneTimeline"},ln={0:"图文/网页",1:"纯文字",2:"纯图片",3:"音乐",4:"视频",5:"小程序"};function pt(t={}){return l.safeExecute(()=>{var r;if(typeof window=="undefined"||!window.wx){const n={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};return(r=t.fail)==null||r.call(t,n),Promise.reject(n)}if(!G())return s.info("等待微信配置完成"),B().then(()=>pt(t));const e=g({},t);return s.debug("调用微信分享",e),t!=null&&t.isCallBack?new Promise((n,i)=>{R("toShareData",t,{success:a=>{var o;(o=t.success)==null||o.call(t,a),n(a)},fail:a=>{var o;s.error("UniApp 微信分享失败",a),(o=t.fail)==null||o.call(t,a),i(a)},complete:t.complete})}):new Promise((n,i)=>{window.wx[e.scene](y(g({},e),{success:()=>{var o;const a={errMsg:"weixinShare:ok"};(o=t.success)==null||o.call(t,a),n(a)},fail:a=>{var d;const o={errMsg:(a==null?void 0:a.errMsg)||"weixinShare:fail",details:a};s.error("微信分享失败",o),(d=t.fail)==null||d.call(t,o),i(o)},complete:t.complete}))})},{context:"toShareInWeixin",platform:"weixin"})}function mt(t={},e){const r=g({},t),n={scene:r.scene===1?"updateTimelineShareData":"updateAppMessageShareData"};return s.info("格式化微信参数",r),Object.prototype.hasOwnProperty.call(r,"title")?Object.prototype.hasOwnProperty.call(r,"imageUrl")?Object.prototype.hasOwnProperty.call(r,"path")?Object.prototype.hasOwnProperty.call(r,"summary")?(n.title=r.title,n.imgUrl=r.imageUrl,n.link=r.path,n.desc=r.summary,{params:n,success:!0}):{message:"参数字段summary值缺少!",success:!1}:{message:"参数字段path值缺少!",success:!1}:{message:"参数字段imageUrl值缺少!9999",success:!1}:{message:"参数字段title值缺少!",success:!1}}function ue(t={}){return l.safeExecute(()=>(s.debug("通过 WebView 桥接调用微信分享",t),console.log("桥接调用微信分享桥接调用微信分享:",JSON.stringify(be(t),null,2)),new Promise((e,r)=>{R("toShareData",t,{success:n=>{var i;(i=t.success)==null||i.call(t,n),e(n)},fail:n=>{var i;s.error("UniApp 微信分享失败",n),(i=t.fail)==null||i.call(t,n),r(n)},complete:t.complete})})),{context:"toShareInUniApp",platform:"uniapp"})}function wt(t={}){const e=g({},t),r={provider:"weixin",scene:"WXSceneSession"};if(s.info("格式化 UniApp 参数",e),[0,1].some(n=>parseInt(n)===parseInt(e.scene))?r.scene=un[e.scene]:r.scene="WXSceneSession",Object.prototype.hasOwnProperty.call(e,"type")){const n=Number(e.type);if(Object.keys(ln).some(a=>parseInt(a)===n)){if(r.type=n,[0].includes(n))if(Object.prototype.hasOwnProperty.call(e,"path"))r.href=e.path;else return{message:"参数字段path值缺少!",success:!1};if([0,1].includes(n))if(Object.prototype.hasOwnProperty.call(e,"summary"))r.summary=e.summary;else return{message:"参数字段summary值缺少!",success:!1};if([0,2,5].includes(n))if(Object.prototype.hasOwnProperty.call(e,"imageUrl"))r.imageUrl=e.imageUrl;else return{message:"参数字段imageUrl值缺少!",success:!1};[5].includes(n)&&Object.prototype.hasOwnProperty.call(e,"miniProgram")&&g({},e.miniProgram),Object.prototype.hasOwnProperty.call(e,"title")&&(r.title=e.title),Object.prototype.hasOwnProperty.call(e,"success")&&(r.success=e.success),Object.prototype.hasOwnProperty.call(e,"fail")&&(r.fail=e.fail),Object.prototype.hasOwnProperty.call(e,"complete")&&(r.complete=e.complete)}else return{message:"参数字段type值有误!",success:!1}}else return{message:"参数字段type缺少!",success:!1};return{params:r,success:!0}}const Le="share.toShare";cn(Le,{weixin:pt,webview:ue,plus:ue,nvue:ue,uvue:ue,UniApp:ue,h5:ue,default:void 0});function be(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function Et(t={}){return l.safeExecute(()=>{var a,o;const e=fe(),r=ht(Le,e.type);if(typeof r!="function"){const d={errMsg:`当前环境 (${e.type}) 不支持微信分享功能`,code:"PLATFORM_NOT_SUPPORTED"};return s.error("平台不支持微信分享",{platform:e.type}),(a=t.fail)==null||a.call(t,d),Promise.reject(d)}const n=h()?mt(t):wt(t);if(!n.success){const d={errMsg:n.message||"参数校验失败",code:"INVALID_PARAMS"};return(o=t.fail)==null||o.call(t,d),Promise.reject(d)}const i=n.params;return s.info("开始微信分享",{platform:e.type,type:i==null?void 0:i.type}),r(i)},{context:"toShare",options:t})}function fn(t={}){return new Promise((e,r)=>{Et(y(g({},t),{success:e,fail:r}))})}function yt(t={}){return l.safeExecute(()=>{var a,o;const e=fe(),r=ht(Le,e.type);if(typeof r!="function"){const d={errMsg:`当前环境 (${e.type}) 不支持微信分享功能`,code:"PLATFORM_NOT_SUPPORTED"};return s.error("平台不支持微信分享",{platform:e.type}),(a=t.fail)==null||a.call(t,d),Promise.reject(d)}const n=h()?mt(t):wt(t);if(console.log("normalizednormalizednormalized:",JSON.stringify(be(n),null,2)),!n.success){const d={errMsg:n.message||"参数校验失败",code:"INVALID_PARAMS"};return(o=t.fail)==null||o.call(t,d),console.log("你是什么东西啊:",JSON.stringify(be(d),null,2)),Promise.reject(d)}const i=n.params;return s.info("开始微信分享",{platform:e.type,type:i==null?void 0:i.type}),r(y(g({},i),{isCallBack:!0}))},{context:"toShare",options:t})}function dn(t={}){return new Promise((e,r)=>{yt(y(g({},t),{success:e,fail:r}))})}const gn={OFF:"off",ON:"on",UNAVAILABLE:"unavailable",UNAUTHORIZED:"unauthorized"},hn={allowDuplicatesKey:!1,services:[]};function Ce(t={}){return g(g({},hn),t)}function Ee(){return["weixin","webview","UniApp","plus","nvue","uvue"].includes(u.type)}function pn(t){return l.safeExecute(()=>w(null,null,function*(){var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}G()||(s.info("等待微信配置完成"),yield B()),wx.openBluetoothAdapter({success:()=>{s.info("微信蓝牙适配器已打开"),It(t)},fail:r=>{var n;s.error("蓝牙适配器打开失败",r),(n=t.fail)==null||n.call(t,r)}})}),{context:"openBluetoothAdapterInWeixin"})}function mn(t){return l.safeExecute(()=>{s.debug("通过 WebView 桥接调用蓝牙功能",t),R("bluetooth",t,{success:e=>{var r;s.info("UniApp 蓝牙调用成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 蓝牙调用失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"bluetoothInUniApp"})}function wn(t){return l.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙设备搜索功能",t),R("bluetoothDevicesDiscovery",{action:"startBluetoothDevicesDiscovery",params:{services:t.services||[],allowDuplicatesKey:(e=t.allowDuplicatesKey)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 设备开启搜索成功:",r),s.info("UniApp 蓝牙设备开启搜索成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 设备开启搜索失败:",r),s.error("UniApp 蓝牙设备开启搜索失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"startBluetoothDevicesDiscoveryInUniApp"})}const _e=new Set;function En(t,e={}){return l.safeExecute(()=>{var r;return _e.add(t),_e.size===1&&R("onBluetoothDeviceFound",{action:"onBluetoothDeviceFound",isPersistent:!0,params:{services:e.services||[],allowDuplicatesKey:(r=e.allowDuplicatesKey)!=null?r:!1}},{success:n=>{_e.forEach(i=>{typeof i=="function"?l.safeExecute(()=>i(n),{context:"BluetoothDeviceCallback"}):console.warn("[BluetoothDeviceCallback] 不是函数:",i)})},fail:n=>{var i;console.error("[Bluetooth] 搜索失败:",n),(i=e.fail)==null||i.call(e,n)},complete:e.complete}),()=>_e.delete(t)},{context:"qsh_onBluetoothDeviceFound"})}function yn(t){return l.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙连接功能",t),R("bluetoothConnection",{action:"createBLEConnection",params:{deviceId:t.deviceId,name:t.name,autoConnect:(e=t.autoConnect)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 蓝牙连接成功:",r),s.info("UniApp 蓝牙连接成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 蓝牙连接失败:",r),s.error("UniApp 蓝牙连接失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"createBLEConnectionInUniApp"})}function In(t={}){return l.safeExecute(()=>{var r;if(!Ee()){const n={errMsg:`当前环境 (${u.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:u.type}),(r=t.fail)==null||r.call(t,n);return}const e=Ce(t);s.info("开始蓝牙操作",{platform:u.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),h()?pn(e):mn(e)},{context:"openBluetoothAdapter",options:t})}function An(t={}){return l.safeExecute(()=>{var r,n;if(!Ee()){const i={errMsg:`当前环境 (${u.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:u.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=Ce(t);s.info("开始搜索蓝牙设备",{platform:u.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),h()?startBluetoothDevicesDiscoveryInWeixin(e):wn(e)},{context:"startBluetoothDevicesDiscovery",options:t})}function It(t,e={}){return l.safeExecute(()=>{var n,i;if(!Ee()){const a={errMsg:`当前环境 (${u.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:u.type}),(n=e.fail)==null||n.call(e,a),(i=e.complete)==null||i.call(e,a);return}const r=Ce(e);s.info("注册蓝牙设备发现监听",{platform:u.type}),h()?onBluetoothDeviceFoundInWeixin(r):En(t,r)},{context:"onBluetoothDeviceFound",options:e})}function On(t={}){return l.safeExecute(()=>{var a,o,d,p;if(!Ee()){const P={errMsg:`当前环境 (${u.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙连接",{platform:u.type}),(a=t.fail)==null||a.call(t,P),(o=t.complete)==null||o.call(t,P);return}const e=Ce(t),{name:r,deviceId:n,autoConnect:i=!1}=e;if(!n){const P={errMsg:"缺少 deviceId 参数",code:"INVALID_PARAMS"};(d=t.fail)==null||d.call(t,P),(p=t.complete)==null||p.call(t,P);return}s.info("创建蓝牙连接",{deviceId:n,autoConnect:i,platform:u.type}),h()?uni.createBLEConnection({deviceId:n,autoConnect:i,success:t.success,fail:t.fail,complete:t.complete}):yn(e)},{context:"createBLEConnection",options:t})}function Cn(){return{supported:Ee(),environment:u.type,implementation:h()?"weixin":"webview",features:{discovery:!0,connect:!0,readWrite:!0,notify:!0,asyncSupport:!0}}}const _n={};function Pn(t={}){return g(g({},_n),t)}function At(){return["webview","UniApp","plus","nvue","uvue"].includes(u.type)}function Rn(t){return l.safeExecute(()=>{s.debug("通过 WebView 桥接调用打印PDF",t),R("printPdf",y(g({},t),{isPersistent:!0}),{success:e=>{var r;s.info("UniApp 打印PDF成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 打印PDF失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"printPdfInUniApp",platform:"uniapp"})}function Sn(t={}){return l.safeExecute(()=>{var r;if(!At()){const n={errMsg:`当前环境 (${u.type}) 不支持打印PDF功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持打印PDF",{platform:u.type}),(r=t.fail)==null||r.call(t,n);return}const e=Pn(t);s.info("开始打印PDF",{platform:u.type}),Rn(e)},{context:"printPdf",options:t})}function Nn(){return{supported:At(),environment:u.type,implementation:"uniapp",features:{asyncSupport:!0}}}const xe="/pages/face/index";function Tn(t={}){const e=g({},t);if(!e.name||typeof e.name!="string"||!e.name.trim())throw{errMsg:"缺少必需参数:name(姓名)",code:"PARAM_MISSING"};if(e.name=e.name.trim(),!e.idCardNumber||typeof e.idCardNumber!="string"||!e.idCardNumber.trim())throw{errMsg:"缺少必需参数:idCardNumber(身份证号)",code:"PARAM_MISSING"};return e.idCardNumber=e.idCardNumber.trim(),e}function Ot(){return h()}function Mn(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram&&typeof window.wx.miniProgram.navigateTo=="function"}function Ln(t){const e=y(g({},t),{title:document.title||"",url:window.location.href||""}),r=Object.entries(e).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`).join("&");return r?`${xe}?${r}`:xe}function bn(t){return l.safeExecute(()=>{if(!Mn()){s.error("微信小程序导航API不可用");return}const e=Ln(t);s.debug("跳转宿主人脸识别页面",{name:t.name,targetUrl:e}),window.wx.miniProgram.navigateTo({url:e,success:()=>{s.info("已跳转到宿主人脸识别页面",{targetUrl:e})},fail:r=>{s.error("跳转宿主人脸识别页面失败",r)}})},{context:"faceVerifyInWeixin",platform:"weixin"})}function xn(t={}){return l.safeExecute(()=>{if(!Ot()){s.error("平台不支持人脸识别",{platform:u.type});return}let e;try{e=Tn(t)}catch(r){s.error("人脸识别参数校验失败",r);return}s.info("开始人脸识别",{platform:u.type,name:e.name,pagePath:xe}),bn(e)},{context:"faceVerify",options:t})}function vn(){return{supported:Ot(),environment:u.type,implementation:"weixin",features:{asyncSupport:!0,hostPageNavigation:!0}}}const Ct=fe();function Dn(){if(typeof window=="undefined"||!fe(!0).isWeixinMiniProgram)return!1;const e=Ne().getRuntimeConfig();return typeof e.clientId=="string"&&e.clientId.length>0}function Un(){return w(this,null,function*(){yield jt(),Dn()&&(yield B())})}X.useResponse(Ye.response,{priority:1e3});let _t=!1;function Pt(){if(_t)return;_t=!0,gr([{name:"load-weixin-sdk",run:Ge,timeoutMs:8e3},{name:"init-bridge",run:ze,timeoutMs:8e3}],{onError:(e,r)=>{console.error(`[QSH-SDK] 初始化失败(${(r==null?void 0:r.name)||"unknown"}):`,e)}})}typeof window!="undefined"&&(document.readyState==="complete"||document.readyState==="interactive"?setTimeout(Pt,0):document.addEventListener("DOMContentLoaded",Pt));function E(t,{apiName:e}={}){return function(r={},...n){const i=r&&typeof r=="object"&&(typeof r.success=="function"||typeof r.fail=="function"||typeof r.complete=="function"),a=r&&typeof r=="object"?r:{},o=()=>i?t(a,...n):new Promise((p,P)=>{const v=y(g({},a),{success:L=>{typeof a.success=="function"&&a.success(L),p(L)},fail:L=>{typeof a.fail=="function"&&a.fail(L),P(L)},complete:a.complete});t(v,...n)});return(typeof window=="undefined"?Promise.resolve():ke()).then(()=>o()).catch(p=>{throw console.error(`[QSH-SDK] ${e||"API"} call failed:`,p),p})}}function Pe(t){return typeof t=="function"?{success:t}:t&&typeof t=="object"?t:{}}const Rt=E(yr),St=E(Ir),Nt=E(Ar),Tt=E(Or),Mt=E(Cr),Lt=E(_r);function bt(t){const e=()=>Pr(t);return(typeof window=="undefined"?Promise.resolve():ke()).then(()=>e())}const ve=E(br);function Wn(t={}){return new Promise((e,r)=>{ve(y(g({},t),{success:e,fail:r}))})}const xt=E(Sn);function $n(t={}){return new Promise((e,r)=>{xt(y(g({},t),{success:e,fail:r}))})}const De=E($r),Fn=E(xn);function Bn(t={}){return new Promise((e,r)=>{De(y(g({},t),{success:e,fail:r}))})}const kn=E(Et),zn=E(fn),Kn=E(yt),Gn=E(dn),Ue=E(qr);function Vn(t={}){return new Promise((e,r)=>{Ue(y(g({},t),{success:e,fail:r}))})}const We=E(Jr);function jn(t={}){return new Promise((e,r)=>{We(y(g({},t),{success:e,fail:r}))})}const $e=E(an);function qn(t={}){return new Promise((e,r)=>{$e(y(g({},t),{success:e,fail:r}))})}const vt=E(In);function Jn(t={}){return new Promise((e,r)=>{vt(y(g({},t),{success:e,fail:r}))})}const Dt=E(An);function Hn(t={}){return new Promise((e,r)=>{Dt(y(g({},t),{success:e,fail:r}))})}const Ut=E(It);function Yn(t={}){return new Promise((e,r)=>{Ut(y(g({},t),{success:e,fail:r}))})}const Wt=E(On);function Xn(t={}){return new Promise((e,r)=>{Wt(y(g({},t),{success:e,fail:r}))})}const te={navigateTo:Rt,navigateBack:St,switchTab:Nt,reLaunch:Tt,redirectTo:Mt,postMessage:Lt,getEnv:bt,chooseImage:ve,chooseImageAsync:Wn,scanCode:De,scanCodeAsync:Bn,getLocation:Ue,getLocationAsync:Vn,openLocation:We,openLocationAsync:jn,chooseLocation:$e,chooseLocationAsync:qn,onLocationChange:t=>E((e={})=>Zr(e.success),{apiName:"onLocationChange"})(Pe(t)),offLocationChange:t=>E((e={})=>Qr(e.success),{apiName:"offLocationChange"})(Pe(t)),onLocationChangeError:t=>E((e={})=>en(e.success),{apiName:"onLocationChangeError"})(Pe(t)),offLocationChangeError:t=>E((e={})=>tn(e.success),{apiName:"offLocationChangeError"})(Pe(t)),startLocationUpdate:E(Yr,{apiName:"startLocationUpdate"}),stopLocationUpdate:E(Xr,{apiName:"stopLocationUpdate"}),environment:Ct,ready:Un,init:ze,isReady:kt,getState:zt,config:Ve,weixin:{config:Ve,waitForConfig:B,isConfigReady:G,getConfigState:Xt,retryConfig:Zt},webView:null,ImageSourceTypes:Ae,ImageSizeTypes:Oe,getImageCapabilities:xr,ScanTypes:ee,getScanCapabilities:Fr,CoordinateTypes:ce,getLocationCapabilities:Hr,getChooseLocationCapabilities:on,openBluetoothAdapter:vt,openBluetoothAdapterAsync:Jn,startBluetoothDevicesDiscovery:Dt,startBluetoothDevicesDiscoveryAsync:Hn,onBluetoothDeviceFound:Ut,onBluetoothDeviceFoundAsync:Yn,createBLEConnection:Wt,createBLEConnectionAsync:Xn,BluetoothStates:gn,toShare:kn,toShareAsync:zn,toShareCallBack:Kn,toShareCallBackAsync:Gn,getBluetoothCapabilities:Cn,printPdf:xt,printPdfAsync:$n,getPrintCapabilities:Nn,faceVerify:Fn,getFaceCapabilities:vn,plugins:{manager:he,register:t=>he.register(t),install:t=>he.install(t,te),list:()=>he.getPluginList()},interceptors:{chain:X,useRequest:(t,e)=>X.useRequest(t,e),useResponse:(t,e)=>X.useResponse(t,e),builtin:{logging:tr,performance:V,createRetry:rr,createValidation:nr,errorNormalizer:Ye}},metrics:{getPerformanceReport:()=>V.getReport(),clearPerformanceMetrics:()=>V.clearMetrics()},errors:{codes:c,messages:Te,categories:$,normalize:He,create:lr,isStandard:fr},store:{instance:k,get:t=>k.get(t),set:(t,e)=>k.set(t,e),subscribe:(t,e)=>k.subscribe(t,e),getSnapshot:()=>k.getSnapshot()},debug:{logger:M,setLogReporter:t=>M.setReporter(t),errorHandler:l,stateManager:Y,enableDevMode:()=>M.enableDevMode(),getLogs:t=>M.getHistory(t),getStats:()=>({logger:M.getStats(),state:Y.getStats(),weixinConfig:Ne().getStats(),plugins:he.getStats(),interceptors:X.getStats(),store:k.getStats()}),getWeixinConfigManager:Ne,exportDebugInfo:()=>M.exportToJSON()}};Ct.isWeixinMiniProgram?te.webView=window.wx&&window.wx.miniProgram:te.webView={navigateTo:Rt,navigateBack:St,switchTab:Nt,reLaunch:Tt,redirectTo:Mt,postMessage:Lt,getEnv:bt,chooseImage:ve,scanCode:De,getLocation:Ue,openLocation:We,chooseLocation:$e};const $t=typeof window.uni!="undefined"?window.uni:{};return Object.keys($t).forEach(t=>{te.hasOwnProperty(t)||(te[t]=$t[t])}),typeof window!="undefined"&&(window.qsh=te),te});
1
+ (function(C,A){typeof exports=="object"&&typeof module!="undefined"?module.exports=A():typeof define=="function"&&define.amd?define(A):(C=typeof globalThis!="undefined"?globalThis:C||self,C.qsh=A())})(this,function(){"use strict";var ci=Object.defineProperty,ui=Object.defineProperties;var li=Object.getOwnPropertyDescriptors;var kt=Object.getOwnPropertySymbols;var fi=Object.prototype.hasOwnProperty,di=Object.prototype.propertyIsEnumerable;var ke=(C,A,h)=>A in C?ci(C,A,{enumerable:!0,configurable:!0,writable:!0,value:h}):C[A]=h,d=(C,A)=>{for(var h in A||(A={}))fi.call(A,h)&&ke(C,h,A[h]);if(kt)for(var h of kt(A))di.call(A,h)&&ke(C,h,A[h]);return C},m=(C,A)=>ui(C,li(A));var G=(C,A,h)=>ke(C,typeof A!="symbol"?A+"":A,h);var I=(C,A,h)=>new Promise((ie,H)=>{var se=U=>{try{Y(h.next(U))}catch(v){H(v)}},ae=U=>{try{Y(h.throw(U))}catch(v){H(v)}},Y=U=>U.done?ie(U.value):Promise.resolve(U.value).then(se,ae);Y((h=h.apply(C,A)).next())});function C(){return typeof window!="undefined"?window:void 0}function A(){return typeof navigator=="undefined"?"":navigator.userAgent||""}function h(){const t=C();if(!t)return!1;if(t.__wxjs_environment==="miniprogram"||t.wx&&t.wx.miniProgram)return!0;const e=A();return!!(e&&/micromessenger/i.test(e)&&/miniProgram/i.test(e))}function ie(){const t=C();return!!(t&&t.plus)}function H(){const t=C();return!!(t&&(t.__dcloud_weex_postMessage||t.__dcloud_weex_))}function se(){const t=C();return!!(t&&(t.__uniapp_x_postMessage||t.__uniapp_x_))}function ae(){const t=A();return/uni-app/i.test(t)}function Y(){const t=A();return/Html5Plus/i.test(t)}function U(){return ae()||Y()}function v(){const t=C();if(!t)return!1;if(t.__offline_bridge_postMessage)return!0;try{const e=t.location&&t.location.hostname;if(e&&/\.?offline\.?/i.test(e))return!0}catch(e){}return!1}function zt(){return se()?"uvue":H()?"nvue":h()?"weixin":v()?"offline":ie()?"plus":U()?"webview":ae()?"UniApp":"h5"}let ye=null;function oe(t=!1){return ye&&!t||(ye={isWeixinMiniProgram:h(),isAppPlus:ie(),isNvue:H(),isUvue:se(),isUniApp:ae(),isHtml5Plus:Y(),isUniAppWebView:U(),isOfflineWebview:v(),type:zt()}),ye}const l=oe(),b={PLATFORM_NOT_SUPPORTED:"PLATFORM_NOT_SUPPORTED",API_CALL_FAILED:"API_CALL_FAILED",BRIDGE_NOT_READY:"BRIDGE_NOT_READY",INVALID_PARAMETERS:"INVALID_PARAMETERS",NETWORK_ERROR:"NETWORK_ERROR"};class N extends Error{constructor(e,r,n={},i=null){super(r),this.name="QshError",this.type=e,this.context=n,this.originalError=i,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,N)}toJSON(){return{name:this.name,type:this.type,message:this.message,context:this.context,timestamp:this.timestamp,stack:this.stack}}}const _=class _{static setDebugMode(e){_.isDebugMode=e}static addErrorCallback(e){typeof e=="function"&&_.errorCallbacks.push(e)}static removeErrorCallback(e){const r=_.errorCallbacks.indexOf(e);r>-1&&_.errorCallbacks.splice(r,1)}static handleApiError(e,r={}){let n;return e instanceof N?n=e:e instanceof Error?n=new N(b.API_CALL_FAILED,e.message,r,e):n=new N(b.API_CALL_FAILED,String(e),r),_.logError(n),_.notifyCallbacks(n),n}static handlePlatformNotSupported(e,r){const n=new N(b.PLATFORM_NOT_SUPPORTED,`API "${r}" is not supported on platform "${e}"`,{platformType:e,apiName:r});return _.logError(n),_.notifyCallbacks(n),n}static handleBridgeNotReady(e){const r=new N(b.BRIDGE_NOT_READY,`Bridge is not ready when calling "${e}"`,{apiName:e});return _.logError(r),_.notifyCallbacks(r),r}static handleInvalidParameters(e,r,n,i){const a=new N(b.INVALID_PARAMETERS,`Invalid parameter "${r}" in "${e}": expected ${n}, got ${typeof i}`,{apiName:e,paramName:r,expectedType:n,actualValue:i});return _.logError(a),_.notifyCallbacks(a),a}static safeExecute(e,r={}){try{return e()}catch(n){return _.handleApiError(n,r)}}static safeExecuteAsync(n){return I(this,arguments,function*(e,r={}){try{return yield e()}catch(i){return _.handleApiError(i,r)}})}static logError(e){if(typeof console!="undefined"){const r=`[QSH-SDK Error] ${e.type}: ${e.message}`;_.isDebugMode?console.error(r,{context:e.context,originalError:e.originalError,stack:e.stack,timestamp:e.timestamp}):console.error(r)}}static notifyCallbacks(e){_.errorCallbacks.forEach(r=>{try{r(e)}catch(n){typeof console!="undefined"&&console.error("[QSH-SDK] Error in error callback:",n)}})}static createErrorDecorator(e={}){return function(r,n,i){const a=i.value;return i.value=function(...c){return _.safeExecute(()=>a.apply(this,c),m(d({},e),{method:n,target:r.constructor.name}))},i}}};G(_,"isDebugMode",!1),G(_,"errorCallbacks",[]);let u=_;const x={UNINITIALIZED:"uninitialized",INITIALIZING:"initializing",READY:"ready",ERROR:"error"};class Kt{constructor(){this.state=x.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null,this.handleBridgeReady=this.handleBridgeReady.bind(this),this.handleInitializationError=this.handleInitializationError.bind(this)}getState(){return this.state}isReady(){return this.state===x.READY}isInitializing(){return this.state===x.INITIALIZING}hasError(){return this.state===x.ERROR}getInitializationError(){return this.initializationError}waitForReady(){return this.isReady()?Promise.resolve():this.hasError()?Promise.reject(this.initializationError):(this.readyPromise||(this.readyPromise=new Promise((e,r)=>{this.isReady()?e():this.hasError()?r(this.initializationError):(this.readyCallbacks.push(e),this.errorCallbacks.push(r))})),this.readyPromise)}startInitialization(e){return I(this,null,function*(){if(this.state!==x.UNINITIALIZED)return this.waitForReady();this.state=x.INITIALIZING;try{yield e(),this.handleBridgeReady()}catch(r){throw this.handleInitializationError(r),r}return this.waitForReady()})}handleBridgeReady(){this.state===x.INITIALIZING&&(this.state=x.READY,this.readyCallbacks.forEach(e=>{try{e()}catch(r){u.handleApiError(r,{context:"StateManager.handleBridgeReady"})}}),this.readyCallbacks=[],this.errorCallbacks=[])}handleInitializationError(e){this.state=x.ERROR,this.initializationError=e,this.errorCallbacks.forEach(r=>{try{r(e)}catch(n){u.handleApiError(n,{context:"StateManager.handleInitializationError"})}}),this.readyCallbacks=[],this.errorCallbacks=[]}reset(){this.state=x.UNINITIALIZED,this.readyPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.initializationError=null}onStateChange(e,r){if(this.state===e)return setTimeout(()=>r(this.state),0),()=>{};const n=()=>{this.state===e&&r(this.state)};return e===x.READY?this.readyCallbacks.push(n):e===x.ERROR&&this.errorCallbacks.push(n),()=>{const i=this.readyCallbacks.indexOf(n);i>-1&&this.readyCallbacks.splice(i,1);const a=this.errorCallbacks.indexOf(n);a>-1&&this.errorCallbacks.splice(a,1)}}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasReadyPromise:!!this.readyPromise,hasInitializationError:!!this.initializationError}}}const X=new Kt,ze=()=>X.waitForReady(),Gt=()=>X.isReady(),Vt=()=>X.getState(),O={ERROR:0,WARN:1,INFO:2,DEBUG:3,TRACE:4},de={[O.ERROR]:"ERROR",[O.WARN]:"WARN",[O.INFO]:"INFO",[O.DEBUG]:"DEBUG",[O.TRACE]:"TRACE"},f=class f{static setLevel(e){e>=O.ERROR&&e<=O.TRACE&&(f.currentLevel=e,f.log(O.INFO,"Logger",`日志级别设置为: ${de[e]}`))}static enableDevMode(){f.setLevel(O.DEBUG),f.log(O.INFO,"Logger","开发模式已启用")}static enableProdMode(){f.setLevel(O.WARN),f.log(O.INFO,"Logger","生产模式已启用")}static enableModule(e){f.enabledModules.add(e),f.log(O.INFO,"Logger",`模块日志已启用: ${e}`)}static disableModule(e){f.enabledModules.delete(e),f.log(O.INFO,"Logger",`模块日志已禁用: ${e}`)}static shouldLog(e,r){return e>f.currentLevel?!1:r&&f.enabledModules.size>0?f.enabledModules.has(r):!0}static log(e,r,n,...i){if(!f.shouldLog(e,r))return;const a=new Date().toISOString(),c=de[e],g=r?`[${r}]`:"",p=`${f.prefix} ${g} ${n}`,R={timestamp:a,level:e,levelName:c,module:r,message:n,args:i};if(f.addToHistory(R),typeof f.reporter=="function")try{f.reporter(R)}catch(D){}f.outputToConsole(e,p,...i)}static addToHistory(e){f.logHistory.push(e),f.logHistory.length>f.maxHistorySize&&f.logHistory.shift()}static outputToConsole(e,r,...n){if(typeof console=="undefined")return;const i=n&&n.length>0;switch(e){case O.ERROR:i?console.error(r,...n):console.error(r);break;case O.WARN:i?console.warn(r,...n):console.warn(r);break;case O.INFO:i?console.info(r,...n):console.info(r);break;case O.DEBUG:case O.TRACE:i?console.log(r,...n):console.log(r);break}}static error(e,r,...n){f.log(O.ERROR,e,r,...n)}static warn(e,r,...n){f.log(O.WARN,e,r,...n)}static info(e,r,...n){f.log(O.INFO,e,r,...n)}static debug(e,r,...n){f.log(O.DEBUG,e,r,...n)}static trace(e,r,...n){f.log(O.TRACE,e,r,...n)}static getHistory(e){return e&&e>0?f.logHistory.slice(-e):[...f.logHistory]}static clearHistory(){f.logHistory=[],f.log(O.INFO,"Logger","日志历史已清空")}static getStats(){const e={currentLevel:f.currentLevel,currentLevelName:de[f.currentLevel],enabledModules:Array.from(f.enabledModules),historySize:f.logHistory.length,maxHistorySize:f.maxHistorySize},r={};for(const n of Object.keys(de))r[de[n]]=0;return f.logHistory.forEach(n=>{r[n.levelName]++}),e.levelCounts=r,e}static exportToJSON(e){const r=f.getHistory(e),n=f.getStats();return JSON.stringify({exportTime:new Date().toISOString(),stats:n,logs:r},null,2)}static createModuleLogger(e){return{error:(r,...n)=>f.error(e,r,...n),warn:(r,...n)=>f.warn(e,r,...n),info:(r,...n)=>f.info(e,r,...n),debug:(r,...n)=>f.debug(e,r,...n),trace:(r,...n)=>f.trace(e,r,...n)}}static setReporter(e){f.reporter=typeof e=="function"?e:null}};G(f,"currentLevel",O.ERROR),G(f,"enabledModules",new Set),G(f,"logHistory",[]),G(f,"maxHistorySize",1e3),G(f,"prefix","[QSH-SDK]"),G(f,"reporter",null);let M=f;if(typeof window!="undefined"){const t=window.location&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"||window.location.hostname.includes("192.168.")),e=window.location&&(window.location.search.includes("debug=true")||window.location.search.includes("qsh_debug=1"));let r=!1;try{r=localStorage&&localStorage.getItem("qsh_debug")==="true"}catch(n){}(t||e||r)&&M.enableDevMode()}const w=M.createModuleLogger("Bridge"),E=M.createModuleLogger("Platform"),s=M.createModuleLogger("API"),W=M.createModuleLogger("State"),Ie=/complete|loaded|interactive/;function jt(t){if(!v())return!1;w.debug("检测到离线包环境,开始初始化");const e=()=>{t()};if(Ie.test(document.readyState))w.debug("离线包环境 DOM 已就绪,立即初始化"),setTimeout(e,0);else{w.debug("离线包环境,等待 DOMContentLoaded");let r=!1;const n=()=>{r||(r=!0,e())};document.addEventListener("DOMContentLoaded",n),setTimeout(n,500)}return!0}function qt(t){return ae()||Y()?(w.debug("检测到 APP 环境,开始初始化"),window.__uniapp_x_postMessage||window.__uniapp_x_||window.__dcloud_weex_postMessage||window.__dcloud_weex_?(w.debug("NVUE/UVUE 环境,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)):window.plus&&Ie.test(document.readyState)?(w.debug("Plus 环境已就绪,立即初始化"),setTimeout(t,0)):window.plus?(w.debug("Plus 环境,等待 plusready 事件"),document.addEventListener("plusready",t)):Ie.test(document.readyState)?setTimeout(t,0):document.addEventListener("DOMContentLoaded",t,{once:!0}),!0):!1}function Jt(t){return window.wx&&window.wx.miniProgram?(w.debug("检测到微信小程序环境,开始初始化"),window.WeixinJSBridge&&window.WeixinJSBridge.invoke?(w.debug("微信 JSBridge 已就绪,立即初始化"),setTimeout(t,0)):(w.debug("微信 JSBridge 未就绪,等待 WeixinJSBridgeReady 事件"),document.addEventListener("WeixinJSBridgeReady",t)),!0):!1}function Ht(t){return w.info("开始初始化 JSBridge"),jt(t)?(w.info("使用离线包环境初始化"),!0):qt(t)?(w.info("使用 APP 环境初始化"),!0):Jt(t)?(w.info("使用微信小程序环境初始化"),!0):(w.debug("使用默认 H5 环境初始化"),Ie.test(document.readyState)?(w.debug("DOM 已就绪,立即初始化"),setTimeout(t,0)):(w.debug("DOM 未就绪,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)),!0)}function Yt(){return X.waitForReady()}function Ke(){return X.startInitialization(()=>I(null,null,function*(){return new Promise((t,e)=>{const r=()=>{t()},n=i=>{const a=u.handleApiError(i,{context:"bridge initialization"});e(a)};try{Ht(()=>{r()})}catch(i){n(i)}})}))}const S={UNINITIALIZED:"uninitialized",CONFIGURING:"configuring",CONFIGURED:"configured",ERROR:"error"};function B(){return typeof window=="undefined"||!window.wx?!1:typeof window.wx.config=="function"&&typeof window.wx.ready=="function"&&typeof window.wx.error=="function"}class Xt{constructor(){this.state=S.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,this.runtimeConfig={clientId:null,isProd:!1},this.CONFIG_API_URL=this.getConfigApiUrl(this.runtimeConfig.isProd),this.DEFAULT_JS_API_LIST=["chooseImage","uploadImage","previewImage","downloadImage","getLocalImgData","scanQRCode","getLocation","openLocation","updateAppMessageShareData","updateTimelineShareData"],this.DEFAULT_OPEN_TAG_LIST=["wx-open-launch-weapp","wx-open-launch-app"],this.handleConfigSuccess=this.handleConfigSuccess.bind(this),this.handleConfigError=this.handleConfigError.bind(this)}configure(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new N(b.INVALID_PARAMETERS,"config参数异常",{config:e});if(!Object.prototype.hasOwnProperty.call(e,"clientId"))throw this.createMissingClientIdError();if(typeof e.clientId!="string"||!e.clientId.trim())throw new N(b.INVALID_PARAMETERS,"clientId参数异常",{clientId:e.clientId});if(Object.prototype.hasOwnProperty.call(e,"isProd")&&typeof e.isProd!="boolean")throw new N(b.INVALID_PARAMETERS,"isProd参数异常",{isProd:e.isProd});const r=e.clientId.trim(),n=e.isProd===!0,i=r!==this.runtimeConfig.clientId||n!==this.runtimeConfig.isProd;return this.runtimeConfig=m(d({},this.runtimeConfig),{clientId:r,isProd:n}),this.CONFIG_API_URL=this.getConfigApiUrl(n),(this.state===S.ERROR||i&&(this.state===S.CONFIGURING||this.state===S.CONFIGURED))&&this.reset(),E.info("Updated Weixin runtime config",{clientId:this.runtimeConfig.clientId,isProd:this.runtimeConfig.isProd,configApiUrl:this.CONFIG_API_URL}),this.getRuntimeConfig()}getRuntimeConfig(){return d({},this.runtimeConfig)}hasClientId(){return typeof this.runtimeConfig.clientId=="string"&&this.runtimeConfig.clientId.length>0}hasRequiredConfig(){return this.isTestMode()||this.hasClientId()}createMissingClientIdError(){return new N(b.INVALID_PARAMETERS,"clientId错误",{field:"clientId"})}getConfigApiUrl(e=!1){return e?"https://tyck-service.xj-agri.gov.cn/api/wechat/mp/jssdk-sign":"https://unified-platform-service.xjy2.cn/api/wechat/mp/jssdk-sign"}getCurrentPageUrl(){if(typeof window=="undefined"||!window.location)throw new Error("无法获取当前页面URL");const e=window.location.href,r=e.indexOf("#");return r!==-1?e.substring(0,r):e}fetchWeixinConfig(){return I(this,null,function*(){const e=this.getCurrentPageUrl();if(this.isTestMode())return E.info("使用测试模式,返回模拟配置"),this.getMockConfig();if(!this.hasClientId())throw this.createMissingClientIdError();const r=this.getConfigApiUrl(this.runtimeConfig.isProd);this.CONFIG_API_URL=r;const n=`${r}?clientId=${this.runtimeConfig.clientId}&url=${encodeURIComponent(e)}`;E.debug("请求微信配置",{url:n});try{const i=yield fetch(n);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);const a=yield i.json();if(E.debug("微信配置响应",a),!a.success||a.code!==200)throw new Error(`配置获取失败: ${a.message||"未知错误"}`);const{data:c}=a;if(!c||!c.appId||!c.timestamp||!c.nonceStr||!c.signature)throw new Error("配置数据格式不正确,缺少必需字段");return c}catch(i){if(E.error("获取微信配置失败",i),this.shouldUseTestMode(i))return E.warn("网络请求失败,降级到测试模式"),this.getMockConfig();throw new N(b.NETWORK_ERROR,`获取微信配置失败: ${i.message}`,{url:n,originalError:i})}})}isTestMode(){if(typeof window=="undefined")return!1;if(new URLSearchParams(window.location.search).get("qsh_test")==="true")return!0;try{if(localStorage.getItem("qsh_test")==="true")return!0}catch(r){}return!1}shouldUseTestMode(e){if(typeof window=="undefined")return!1;const r=window.location.hostname==="localhost"||window.location.hostname.includes("natappfree.cc"),n=!window.wx||!window.wx.miniProgram,i=e.message.includes("CORS")||e.message.includes("Failed to fetch");return r&&n&&i}getMockConfig(){return{appId:"wx_test_app_id",timestamp:Math.floor(Date.now()/1e3).toString(),nonceStr:Math.random().toString(36).substring(2,15),signature:"test_signature_"+Math.random().toString(36).substring(2,10)}}executeWeixinConfig(e){if(this.isTestMode()||e.appId==="wx_test_app_id"){E.info("测试模式:模拟微信配置成功"),setTimeout(()=>{this.handleConfigSuccess()},100);return}if(!B())throw new Error("微信JS-SDK未加载");const r={debug:!1,appId:e.appId,timestamp:parseInt(e.timestamp),nonceStr:e.nonceStr,signature:e.signature,jsApiList:this.DEFAULT_JS_API_LIST,openTagList:this.DEFAULT_OPEN_TAG_LIST};E.info("执行微信配置",r),window.wx.ready(this.handleConfigSuccess),window.wx.error(this.handleConfigError),window.wx.config(r)}handleConfigSuccess(){E.info("微信配置成功"),this.state=S.CONFIGURED,this.lastError=null,this.configPromise=null;const e=[...this.readyCallbacks];this.readyCallbacks=[],this.errorCallbacks=[],e.forEach(r=>{try{r()}catch(n){u.handleApiError(n,{context:"WeixinConfigManager.handleConfigSuccess"})}})}handleConfigError(e){const r=`微信配置验证失败: ${JSON.stringify(e)}`;E.error(r,e);const n=new N(b.API_CALL_FAILED,r,{weixinErrorResponse:e});this.state=S.ERROR,this.lastError=n,this.configPromise=null;const i=[...this.errorCallbacks];this.readyCallbacks=[],this.errorCallbacks=[],i.forEach(a=>{try{a(n)}catch(c){u.handleApiError(c,{context:"WeixinConfigManager.handleConfigError"})}})}autoConfig(){return I(this,null,function*(){return this.hasRequiredConfig()?this.state===S.CONFIGURED?Promise.resolve():this.state===S.ERROR?Promise.reject(this.lastError):this.configPromise?this.configPromise:(this.state=S.CONFIGURING,this.configPromise=this.performAutoConfig(),this.configPromise):(E.warn("clientId为空,等待qsh.config({ clientId })"),Promise.resolve())})}performAutoConfig(){return I(this,null,function*(){try{if(typeof window=="undefined")throw new Error("非浏览器环境无法执行微信配置");if(!B())throw new Error("微信JS-SDK未加载,无法执行配置");const e=yield this.fetchWeixinConfig();return this.executeWeixinConfig(e),yield new Promise((r,n)=>{if(this.state===S.CONFIGURED){r();return}if(this.state===S.ERROR){n(this.lastError);return}this.readyCallbacks.push(r),this.errorCallbacks.push(n)})}catch(e){const r=e instanceof N?e:u.handleApiError(e,{context:"WeixinConfigManager.performAutoConfig"});this.state=S.ERROR,this.lastError=r,this.configPromise=null;const n=[...this.errorCallbacks];throw this.readyCallbacks=[],this.errorCallbacks=[],n.forEach(i=>{try{i(r)}catch(a){u.handleApiError(a,{context:"WeixinConfigManager.performAutoConfig.errorCallback"})}}),r}})}waitForReady(){return this.state===S.CONFIGURED?Promise.resolve():this.state===S.ERROR?Promise.reject(this.lastError):this.hasRequiredConfig()?this.state===S.UNINITIALIZED?this.autoConfig():new Promise((e,r)=>{this.readyCallbacks.push(e),this.errorCallbacks.push(r)}):Promise.reject(this.createMissingClientIdError())}isReady(){return this.state===S.CONFIGURED}getState(){return this.state}getLastError(){return this.lastError}reset(){this.state=S.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,E.debug("微信配置管理器已重置")}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasConfigPromise:!!this.configPromise,hasLastError:!!this.lastError,configApiUrl:this.CONFIG_API_URL,clientId:this.runtimeConfig.clientId,isProd:this.runtimeConfig.isProd,jsApiList:this.DEFAULT_JS_API_LIST,openTagList:this.DEFAULT_OPEN_TAG_LIST}}}const T=new Xt;let ce=!1,ge=!1,$=null,Ae=!1;function Zt(t){return new Promise(e=>{let r=!1,n=null;const i=g=>I(null,null,function*(){if(!r){if(r=!0,n&&clearTimeout(n),ce=!1,ge=g,g)try{yield Ge()}catch(p){E.error("微信配置失败,将使用消息桥作为后备",p)}e()}}),a=()=>i(B()),c=()=>{E.warn("已存在的微信 JS-SDK 脚本加载失败,SDK 将使用消息桥作为后备"),i(!1)};t.addEventListener("load",a,{once:!0}),t.addEventListener("error",c,{once:!0}),setTimeout(()=>{B()&&a()},0),n=setTimeout(()=>{i(B())},3e3)})}function Se(){return I(this,arguments,function*(t={}){const{force:e=!1,recoverFromError:r=!1}=t;if(yield Ve({force:e}),!B())throw new Error("微信 JS-SDK 未正确加载,无法执行配置");r&&er()})}function Qt(t=!1){if(typeof window=="undefined")return!1;if(B())return ge=!0,!1;if(ge||v())return!1;if(t)return!0;const e=navigator.userAgent||"",r=/micromessenger/i.test(e),n=/miniProgram/i.test(e),i=typeof window.__wxjs_environment!="undefined"&&window.__wxjs_environment==="miniprogram",a=!!(window.wx&&window.wx.miniProgram);return r&&(n||i||a)}function er(){T.getState()==="error"&&(T.reset(),Ae=!1)}function Ge(){return I(this,null,function*(){if(Ae)return T.waitForReady();Ae=!0,E.info("开始自动配置微信JS-SDK");try{yield T.autoConfig(),E.info("微信JS-SDK自动配置完成")}catch(t){E.error("微信JS-SDK自动配置失败",t)}})}function Ve(t={}){const{force:e=!1}=t;if(typeof window=="undefined")return Promise.resolve();if(B())return ge=!0,Promise.resolve();const r=document.getElementById("weixin-jssdk");return r?$||(ce=!0,$=Zt(r).finally(()=>{$=null}),$):Qt(e)?$||($=new Promise(n=>{ce=!0;try{const i=document.createElement("script");i.id="weixin-jssdk",i.type="text/javascript",i.async=!0,i.src="https://res.wx.qq.com/open/js/jweixin-1.6.2.js",i.onload=function(){return I(this,null,function*(){ge=!0,ce=!1,E.info("微信 JS-SDK 已自动加载");try{yield Ge()}catch(c){E.error("微信配置失败,将使用消息桥作为后备",c)}n()})},i.onerror=function(){ce=!1,E.warn("微信 JS-SDK 加载失败,SDK 将使用消息桥作为后备"),n()},(document.getElementsByTagName("head")[0]||document.documentElement).appendChild(i)}catch(i){ce=!1,E.error("注入微信 JS-SDK 失败",i),n()}}).finally(()=>{$=null}),$):Promise.resolve()}function k(){return Se({force:!0,recoverFromError:!0}).then(()=>T.waitForReady())}function je(t={}){const e=T.configure(t);return typeof window=="undefined"||Se({force:!0,recoverFromError:T.getState()==="error"}).then(()=>{if(!T.isReady())return T.waitForReady().catch(r=>{E.error("Failed to auto-configure Weixin after qsh.config()",r)});window.wx&&!B()&&E.warn("window.wx 已存在,但微信 JS-SDK 尚未就绪,跳过自动配置")}).catch(r=>{E.error("Failed to preload Weixin JS-SDK",r)}),e}function V(){return T.isReady()}function tr(){return T.getState()}function Ne(){return T}function rr(){return I(this,null,function*(){return E.info("手动重试微信配置"),T.reset(),Ae=!1,yield Se({force:!0}),T.waitForReady()})}class nr{constructor(){this.plugins=new Map,this.installed=new Set,this.installOrder=[],s.debug("插件管理器已初始化")}register(e){return u.safeExecute(()=>{this.validatePlugin(e);const{name:r,version:n}=e;if(this.plugins.has(r)){const i=this.plugins.get(r);s.warn(`插件 ${r} 已注册(版本 ${i.version}),将被覆盖为版本 ${n}`)}return this.plugins.set(r,e),s.info(`插件已注册: ${r}@${n}`),this},{context:"PluginManager.register",pluginName:e==null?void 0:e.name})}validatePlugin(e){if(!e||typeof e!="object")throw new Error("插件必须是一个对象");if(!e.name||typeof e.name!="string")throw new Error("插件必须有 name 属性(字符串)");if(!e.version||typeof e.version!="string")throw new Error(`插件 ${e.name} 必须有 version 属性(字符串)`);if(!e.install||typeof e.install!="function")throw new Error(`插件 ${e.name} 必须实现 install 方法`);if(e.dependencies&&!Array.isArray(e.dependencies))throw new Error(`插件 ${e.name} 的 dependencies 必须是数组`)}install(e,r){return I(this,null,function*(){return u.safeExecute(()=>I(this,null,function*(){if(!this.plugins.has(e))throw new Error(`插件 ${e} 未注册`);if(this.installed.has(e)){s.debug(`插件 ${e} 已安装,跳过`);return}const n=this.plugins.get(e);if(n.dependencies&&n.dependencies.length>0){s.debug(`安装插件 ${e} 的依赖:`,n.dependencies);for(const i of n.dependencies)yield this.install(i,r)}s.info(`开始安装插件: ${e}@${n.version}`),yield n.install(r),this.installed.add(e),this.installOrder.push(e),s.info(`插件安装成功: ${e}@${n.version}`)}),{context:"PluginManager.install",pluginName:e})})}uninstall(e,r){return I(this,null,function*(){return u.safeExecute(()=>I(this,null,function*(){if(!this.installed.has(e)){s.debug(`插件 ${e} 未安装,跳过卸载`);return}const n=this.plugins.get(e);n.uninstall&&typeof n.uninstall=="function"&&(s.info(`开始卸载插件: ${e}`),yield n.uninstall(r)),this.installed.delete(e);const i=this.installOrder.indexOf(e);i>-1&&this.installOrder.splice(i,1),s.info(`插件已卸载: ${e}`)}),{context:"PluginManager.uninstall",pluginName:e})})}uninstallAll(e){return I(this,null,function*(){const r=[...this.installOrder].reverse();for(const n of r)yield this.uninstall(n,e)})}registerAll(e){if(!Array.isArray(e))throw new Error("plugins 必须是数组");return e.forEach(r=>this.register(r)),this}installAll(e,r){return I(this,null,function*(){if(!Array.isArray(e))throw new Error("names 必须是数组");for(const n of e)yield this.install(n,r)})}isRegistered(e){return this.plugins.has(e)}isInstalled(e){return this.installed.has(e)}getPlugin(e){return this.plugins.get(e)}getPluginList(){return Array.from(this.plugins.entries()).map(([e,r])=>({name:e,version:r.version,installed:this.installed.has(e),dependencies:r.dependencies||[]}))}getStats(){return{registered:this.plugins.size,installed:this.installed.size,plugins:this.getPluginList()}}clear(){this.plugins.clear(),this.installed.clear(),this.installOrder=[]}}const he=new nr;class ir{constructor(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("拦截器链已初始化")}useRequest(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.requestInterceptors.push({fn:e,priority:n}),this.requestInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("请求拦截器已注册",{priority:n}),()=>{const i=this.requestInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.requestInterceptors.splice(i,1),s.debug("请求拦截器已移除"))}}useResponse(e,r={}){if(typeof e!="function")throw new Error("拦截器必须是函数");const{priority:n=0}=r;return this.responseInterceptors.push({fn:e,priority:n}),this.responseInterceptors.sort((i,a)=>a.priority-i.priority),s.debug("响应拦截器已注册",{priority:n}),()=>{const i=this.responseInterceptors.findIndex(a=>a.fn===e);i>-1&&(this.responseInterceptors.splice(i,1),s.debug("响应拦截器已移除"))}}runRequest(e){return I(this,null,function*(){let r=d({},e);for(const{fn:n}of this.requestInterceptors){if(r.abort){s.debug("请求被中止",{apiName:r.apiName});break}try{const i=yield n(r);i&&(r=i)}catch(i){s.error("请求拦截器执行失败",i),r.abort=!0,r.error=i;break}}return r})}runResponse(e,r){return I(this,null,function*(){let n=e;for(const{fn:i}of this.responseInterceptors)try{const a=yield i(n,r);a!==void 0&&(n=a)}catch(a){s.error("响应拦截器执行失败",a)}return n})}clear(){this.requestInterceptors=[],this.responseInterceptors=[],s.debug("所有拦截器已清空")}getStats(){return{requestInterceptors:this.requestInterceptors.length,responseInterceptors:this.responseInterceptors.length}}}const Z=new ir,sr={request:t=>(t.startTime=Date.now(),s.debug(`[API 调用] ${t.apiName}`,{params:t.params}),t),response:(t,e)=>{const r=Date.now()-e.startTime;return s.debug(`[API 完成] ${e.apiName}`,{duration:`${r}ms`,success:t==null?void 0:t.success}),t}},j={metrics:new Map,request:t=>(t.perfStartTime=performance.now(),t),response:(t,e)=>{const r=performance.now()-e.perfStartTime;j.metrics.has(e.apiName)||j.metrics.set(e.apiName,{count:0,totalTime:0,minTime:1/0,maxTime:0,avgTime:0});const n=j.metrics.get(e.apiName);return n.count++,n.totalTime+=r,n.minTime=Math.min(n.minTime,r),n.maxTime=Math.max(n.maxTime,r),n.avgTime=n.totalTime/n.count,t},getReport:()=>{const t={};return j.metrics.forEach((e,r)=>{t[r]=d({},e)}),t},clearMetrics:()=>{j.metrics.clear()}};function ar(t={}){const{maxRetries:e=3,retryDelay:r=1e3,shouldRetry:n=i=>!i.success}=t;return{response:(i,a)=>I(null,null,function*(){return a.retryCount||(a.retryCount=0),n(i)&&a.retryCount<e&&(a.retryCount++,s.warn(`API 调用失败,第 ${a.retryCount} 次重试: ${a.apiName}`),yield new Promise(c=>setTimeout(c,r)),i.shouldRetry=!0,i.retryContext=a),i})}}function or(t={}){return{request:e=>{const r=t[e.apiName];if(r&&typeof r=="function"){const n=r(e.params);n&&(s.error(`参数验证失败: ${e.apiName}`,n),e.abort=!0,e.validationError=n)}return e}}}class cr{constructor(){this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:{type:l.type,isWeixinMiniProgram:l.isWeixinMiniProgram,isAppPlus:l.isAppPlus,isNvue:l.isNvue,isUvue:l.isUvue,isOfflineWebview:l.isOfflineWebview,features:{}},weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},this.listeners=new Map,this.wildcardListeners=new Set,this.initNetworkListener(),W.debug("状态仓库已初始化")}get(e){return e.split(".").reduce((n,i)=>n!=null?n[i]:void 0,this.state)}set(e,r){const n=e.split("."),i=n.pop(),a=n.reduce((g,p)=>((!g[p]||typeof g[p]!="object")&&(g[p]={}),g[p]),this.state),c=a[i];c!==r&&(a[i]=r,W.debug(`状态已更新: ${e}`,{oldValue:c,newValue:r}),this.notify(e,r,c))}batchUpdate(e){Object.entries(e).forEach(([r,n])=>{this.set(r,n)})}subscribe(e,r){if(typeof r!="function")throw new Error("listener 必须是函数");return e==="*"?(this.wildcardListeners.add(r),W.debug("添加通配符订阅者"),()=>{this.wildcardListeners.delete(r),W.debug("移除通配符订阅者")}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),W.debug(`添加订阅者: ${e}`),()=>{const n=this.listeners.get(e);n&&(n.delete(r),n.size===0&&this.listeners.delete(e),W.debug(`移除订阅者: ${e}`))})}subscribeOnce(e,r){const n=this.subscribe(e,(i,a,c)=>{r(i,a,c),n()});return n}notify(e,r,n){const i=this.listeners.get(e);i&&i.forEach(c=>{try{c(r,n,e)}catch(g){W.error("订阅者执行失败",g)}});const a=e.split(".");for(let c=1;c<a.length;c++){const g=a.slice(0,c).join("."),p=this.listeners.get(g);if(p){const R=this.get(g);p.forEach(D=>{try{D(R,void 0,g)}catch(L){W.error("父路径订阅者执行失败",L)}})}}this.wildcardListeners.forEach(c=>{try{c(r,n,e)}catch(g){W.error("通配符订阅者执行失败",g)}})}initNetworkListener(){if(typeof window!="undefined"&&(window.addEventListener("online",()=>{this.set("network.online",!0)}),window.addEventListener("offline",()=>{this.set("network.online",!1)}),navigator.connection)){const e=navigator.connection,r=()=>{this.set("network.type",e.effectiveType||"unknown")};e.addEventListener("change",r),r()}}setApiLoading(e,r=!0){const n=`api.${e}`,i=this.get(n)||{};this.set(n,m(d({},i),{loading:r,lastCall:r?Date.now():i.lastCall}))}setApiResult(e,r){const n=`api.${e}`,i=this.get(n)||{};this.set(n,m(d({},i),{loading:!1,lastResult:r,lastCallEnd:Date.now()}))}getSnapshot(){return JSON.parse(JSON.stringify(this.state))}reset(){const{platform:e}=this.state;this.state={sdk:{status:"uninitialized",version:"2.0.5",error:null},platform:e,weixin:{configStatus:"pending",jsApiList:[],configError:null},network:{online:typeof navigator!="undefined"?navigator.onLine:!0,type:"unknown"},permissions:{camera:"prompt",location:"prompt",album:"prompt"},api:{}},W.debug("状态已重置")}getStats(){return{listeners:this.listeners.size,wildcardListeners:this.wildcardListeners.size,apiStates:Object.keys(this.state.api).length}}}const z=new cr,o={SDK_NOT_READY:"E_SDK_001",SDK_INIT_FAILED:"E_SDK_002",SDK_CONFIG_FAILED:"E_SDK_003",PLATFORM_NOT_SUPPORTED:"E_SDK_004",NETWORK_ERROR:"E_NET_001",NETWORK_TIMEOUT:"E_NET_002",NETWORK_OFFLINE:"E_NET_003",IMAGE_CANCELLED:"E_IMG_001",IMAGE_NO_PERMISSION:"E_IMG_002",IMAGE_SIZE_EXCEED:"E_IMG_003",IMAGE_COUNT_EXCEED:"E_IMG_004",IMAGE_FORMAT_ERROR:"E_IMG_005",IMAGE_CONFIG_NOT_READY:"E_IMG_006",LOCATION_CANCELLED:"E_LOC_001",LOCATION_NO_PERMISSION:"E_LOC_002",LOCATION_UNAVAILABLE:"E_LOC_003",LOCATION_TIMEOUT:"E_LOC_004",SCAN_CANCELLED:"E_SCAN_001",SCAN_NO_PERMISSION:"E_SCAN_002",SCAN_INVALID_CODE:"E_SCAN_003",SCAN_CONFIG_NOT_READY:"E_SCAN_004",PERMISSION_DENIED:"E_PERM_001",PERMISSION_CAMERA:"E_PERM_002",PERMISSION_LOCATION:"E_PERM_003",PERMISSION_ALBUM:"E_PERM_004",PERMISSION_MICROPHONE:"E_PERM_005",PARAM_INVALID:"E_PARAM_001",PARAM_MISSING:"E_PARAM_002",PARAM_TYPE_ERROR:"E_PARAM_003",API_TIMEOUT:"E_TIMEOUT_001",UNKNOWN_ERROR:"E_UNKNOWN_999"},Te={[o.SDK_NOT_READY]:"SDK 未就绪",[o.SDK_INIT_FAILED]:"SDK 初始化失败",[o.SDK_CONFIG_FAILED]:"SDK 配置失败",[o.PLATFORM_NOT_SUPPORTED]:"当前平台不支持此功能",[o.NETWORK_ERROR]:"网络错误",[o.NETWORK_TIMEOUT]:"网络超时",[o.NETWORK_OFFLINE]:"网络已断开",[o.IMAGE_CANCELLED]:"用户取消选择图片",[o.IMAGE_NO_PERMISSION]:"无相机/相册权限",[o.IMAGE_SIZE_EXCEED]:"图片大小超出限制",[o.IMAGE_COUNT_EXCEED]:"图片数量超出限制",[o.IMAGE_FORMAT_ERROR]:"图片格式不支持",[o.IMAGE_CONFIG_NOT_READY]:"微信配置未完成",[o.LOCATION_CANCELLED]:"用户取消定位",[o.LOCATION_NO_PERMISSION]:"无定位权限",[o.LOCATION_UNAVAILABLE]:"定位服务不可用",[o.LOCATION_TIMEOUT]:"定位超时",[o.SCAN_CANCELLED]:"用户取消扫码",[o.SCAN_NO_PERMISSION]:"无相机权限",[o.SCAN_INVALID_CODE]:"无效的二维码/条形码",[o.SCAN_CONFIG_NOT_READY]:"微信配置未完成",[o.PERMISSION_DENIED]:"权限被拒绝",[o.PERMISSION_CAMERA]:"无相机权限",[o.PERMISSION_LOCATION]:"无定位权限",[o.PERMISSION_ALBUM]:"无相册权限",[o.PERMISSION_MICROPHONE]:"无麦克风权限",[o.PARAM_INVALID]:"参数无效",[o.PARAM_MISSING]:"缺少必需参数",[o.PARAM_TYPE_ERROR]:"参数类型错误",[o.API_TIMEOUT]:"API 调用超时",[o.UNKNOWN_ERROR]:"未知错误"},F={USER_CANCEL:"user_cancel",PERMISSION:"permission",NETWORK:"network",PARAM:"param",SYSTEM:"system",CONFIG:"config",UNKNOWN:"unknown"},ur={"IMAGE/USER_CANCEL":o.IMAGE_CANCELLED,"IMAGE/PERMISSION_DENIED":o.IMAGE_NO_PERMISSION,"COMMON/UNKNOWN":o.UNKNOWN_ERROR,"COMMON/CONFIG_NOT_READY":o.IMAGE_CONFIG_NOT_READY,"COMMON/PLATFORM_NOT_SUPPORTED":o.PLATFORM_NOT_SUPPORTED},qe={weixin:{patterns:[{pattern:/cancel/i,code:o.IMAGE_CANCELLED},{pattern:/permission|auth\s*deny/i,code:o.IMAGE_NO_PERMISSION},{pattern:/config/i,code:o.IMAGE_CONFIG_NOT_READY},{pattern:/timeout/i,code:o.API_TIMEOUT},{pattern:/network/i,code:o.NETWORK_ERROR}],default:o.UNKNOWN_ERROR},uniapp:{patterns:[{pattern:/cancel/i,code:o.IMAGE_CANCELLED},{pattern:/permission|denied/i,code:o.IMAGE_NO_PERMISSION},{pattern:/timeout/i,code:o.API_TIMEOUT},{pattern:/network/i,code:o.NETWORK_ERROR},{pattern:/not_in_container/i,code:o.PLATFORM_NOT_SUPPORTED}],default:o.UNKNOWN_ERROR},offline:{patterns:[{pattern:/cancel/i,code:o.IMAGE_CANCELLED},{pattern:/permission|denied/i,code:o.IMAGE_NO_PERMISSION},{pattern:/timeout/i,code:o.API_TIMEOUT},{pattern:/network/i,code:o.NETWORK_ERROR},{pattern:/not_in_container/i,code:o.PLATFORM_NOT_SUPPORTED}],default:o.UNKNOWN_ERROR}},Je={chooseImage:{"fail cancel":o.IMAGE_CANCELLED,"fail auth deny":o.IMAGE_NO_PERMISSION,"fail No Permission":o.IMAGE_NO_PERMISSION,NOT_IN_CONTAINER:o.PLATFORM_NOT_SUPPORTED},scanCode:{"fail cancel":o.SCAN_CANCELLED,"fail auth deny":o.SCAN_NO_PERMISSION,"fail No Permission":o.SCAN_NO_PERMISSION,NOT_IN_CONTAINER:o.PLATFORM_NOT_SUPPORTED}};function He(t){return t?t.includes("CANCEL")?F.USER_CANCEL:t.includes("PERM")||t.includes("PERMISSION")?F.PERMISSION:t.includes("NET")||t.includes("NETWORK")?F.NETWORK:t.includes("PARAM")?F.PARAM:t.includes("CONFIG")?F.CONFIG:t.includes("SDK")||t.includes("PLATFORM")?F.SYSTEM:F.UNKNOWN:F.UNKNOWN}function lr(t){return t.includes("NET_")||t.includes("TIMEOUT")||t===o.NETWORK_ERROR||t===o.NETWORK_TIMEOUT||t===o.API_TIMEOUT}function fr(t){return t.includes("CANCEL")||He(t)===F.USER_CANCEL}function ue(t){return Te[t]||Te[o.UNKNOWN_ERROR]}class K extends Error{constructor(e,r,n={}){super(r),this.name="StandardError",this.code=e,this.message=r||ue(e),this.platform=n.platform||l.type,this.apiName=n.apiName,this.category=n.category||He(e),this.retriable=n.retriable!==void 0?n.retriable:lr(e),this.originalError=n.originalError,this.details=n.details||{},this.timestamp=Date.now()}isRetriable(){return this.retriable}isUserAction(){return fr(this.code)}toJSON(){return d({code:this.code,message:this.message,platform:this.platform,apiName:this.apiName,category:this.category,retriable:this.retriable,timestamp:this.timestamp,details:this.details},process.env.NODE_ENV!=="production"&&this.originalError?{originalError:this.originalError}:{})}}function Ye(t,e={}){if(t instanceof K)return t;const{apiName:r,platform:n=l.type}=e;return t&&typeof t.code=="string"&&t.code.includes("/")?dr(t,{apiName:r,platform:n}):t&&(t.errMsg||t.message)?gr(t,{apiName:r,platform:n}):typeof t=="string"?new K(o.UNKNOWN_ERROR,t,{apiName:r,platform:n,originalError:t}):new K(o.UNKNOWN_ERROR,"未知错误",{apiName:r,platform:n,originalError:t,details:{errorType:typeof t}})}function dr(t,e){const{apiName:r,platform:n}=e,i=t.code,a=ur[i]||o.UNKNOWN_ERROR;return s.debug("转换旧版错误码",{legacy:i,new:a}),new K(a,t.message||ue(a),{apiName:r,platform:t.platform||n,originalError:t,details:d({legacyCode:i,legacyVersion:t.version},t.details)})}function gr(t,e){const{apiName:r,platform:n}=e,i=(t.errMsg||t.message||"").toLowerCase();if(r&&Je[r]){const g=Je[r];for(const[p,R]of Object.entries(g))if(i.includes(p.toLowerCase()))return new K(R,ue(R),{apiName:r,platform:n,originalError:t})}const a=qe[n]||qe.uniapp;for(const{pattern:g,code:p}of a.patterns)if(g.test(i))return new K(p,ue(p),{apiName:r,platform:n,originalError:t});const c=a.default||o.UNKNOWN_ERROR;return new K(c,t.errMsg||t.message||ue(c),{apiName:r,platform:n,originalError:t})}const Xe={response:(t,e)=>{if(!t.success&&t.error){const r=Ye(t.error,{apiName:e.apiName,platform:l.type});t.error=r.toJSON(),t.errorCode=r.code,t.errorCategory=r.category,t.retriable=r.isRetriable(),s.debug("错误已标准化",{api:e.apiName,code:r.code,category:r.category})}return t}};function hr(t,e={}){return new K(t,ue(t),e)}function pr(t){return t instanceof K}function mr(t,e,r){return e?Promise.race([t(),new Promise((n,i)=>setTimeout(()=>i(new Error(`Init task timeout: ${r}`)),e))]):t()}function wr(){return I(this,arguments,function*(t=[],e={}){for(const r of t){const n=(r==null?void 0:r.name)||"anonymous-task",i=(r==null?void 0:r.run)||r;if(typeof i=="function")try{yield mr(()=>Promise.resolve().then(()=>i()),r.timeoutMs,n),typeof r.onSuccess=="function"&&r.onSuccess()}catch(a){if(typeof r.onError=="function"&&r.onError(a),typeof e.onError=="function")e.onError(a,r);else throw a}}})}class Ze{constructor(e){this.name=e}processNavigationOptions(e={}){const{url:r,delta:n=1}=e,i=r&&encodeURI(r),a=parseInt(n)||1;return m(d({},e),{url:i,delta:a})}processMessageOptions(e={}){const{data:r={}}=e;return{data:r}}navigateTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("navigateTo",r)}navigateBack(e={}){const r=this.processNavigationOptions(e);return this.performNavigation("navigateBack",r)}switchTab(e){const r=this.processNavigationOptions(e);return this.performNavigation("switchTab",r)}reLaunch(e){const r=this.processNavigationOptions(e);return this.performNavigation("reLaunch",r)}redirectTo(e){const r=this.processNavigationOptions(e);return this.performNavigation("redirectTo",r)}postMessage(e={}){const r=this.processMessageOptions(e);return this.performPostMessage(r)}getEnv(e){return this.performGetEnv(e)}performNavigation(e,r){throw new Error(`${this.name} platform must implement performNavigation method`)}performPostMessage(e){throw new Error(`${this.name} platform must implement performPostMessage method`)}performGetEnv(e){throw new Error(`${this.name} platform must implement performGetEnv method`)}}let pe=[];function Er(){if(pe.length===0&&window.plus){const t=plus.webview.currentWebview();if(!t)throw new Error("plus.webview.currentWebview() is undefined");const e=t.parent(),r=e?e.id:t.id;pe.push(r)}return pe}function yr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:e};return window.__uniapp_x_postMessage?window.__uniapp_x_postMessage(i):window.__uniapp_x_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:pe}};window.__uniapp_x_postMessage?window.__uniapp_x_postMessageToService(n):window.__uniapp_x_.postMessageToService(JSON.stringify(n))}function Ir(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"){const i={data:[e]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(i):window.__dcloud_weex_.postMessage(JSON.stringify(i))}const n={type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:pe}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(n):window.__dcloud_weex_.postMessageToService(JSON.stringify(n))}function Ar(t,e){const r={options:{timestamp:+new Date},name:t,arg:e},n=Er();if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:r,webviewIds:n}},"__uniapp__service");else{const i=JSON.stringify(r),a=JSON.stringify(n);plus.webview.getLaunchWebview().evalJS(`UniPlusBridge.subscribeHandler("WEB_INVOKE_APPSERVICE",${i},${a});`)}}function Or(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""},"*")}function Cr(t){return!!(t&&typeof t=="object"&&t.type==="qsh_api_call"&&typeof t.api=="string"&&typeof t.callbackId=="string")}function _r(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"&&Cr(e))return window.__offline_bridge_postMessage(e);window.__offline_bridge_postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""})}function me(t,e){se()?yr(t,e):H()?Ir(t,e):v()?_r(t,e):ie()?Ar(t,e):Or(t,e)}class Qe extends Ze{constructor(){super("weixin")}isWeixinApiAvailable(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;if(E.debug(`微信平台执行导航操作: ${e}`,r),this.isWeixinApiAvailable()){const c=window.wx.miniProgram[e];if(typeof c=="function"){E.debug(`使用微信原生 API: wx.miniProgram.${e}`);const g=e==="navigateBack"?{delta:i}:{url:n};return c.call(window.wx.miniProgram,g)}}E.debug(`使用消息桥接执行: ${e}`),me(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return u.safeExecute(()=>{const{data:r}=e;if(this.isWeixinApiAvailable())return window.wx.miniProgram.postMessage({data:r});me("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return u.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");if(this.isWeixinApiAvailable()&&window.wx.miniProgram.getEnv)return window.wx.miniProgram.getEnv(e);e({miniprogram:!0,weixin:!0})},{platform:this.name,method:"performGetEnv"})}}const Q=new Qe;var et=Object.freeze({__proto__:null,WeixinPlatform:Qe,getEnv:t=>Q.getEnv(t),navigateBack:t=>Q.navigateBack(t),navigateTo:t=>Q.navigateTo(t),postMessage:t=>Q.postMessage(t),reLaunch:t=>Q.reLaunch(t),redirectTo:t=>Q.redirectTo(t),switchTab:t=>Q.switchTab(t)});class tt extends Ze{constructor(){super("app")}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;me(e,e==="navigateBack"?{delta:i}:{url:n})},{platform:this.name,method:"performNavigation",navigationType:e,options:r})}performPostMessage(e){return u.safeExecute(()=>{const{data:r}=e;me("postMessage",r)},{platform:this.name,method:"performPostMessage",options:e})}performGetEnv(e){return u.safeExecute(()=>{if(!e||typeof e!="function")throw new Error("Callback function is required for getEnv");const r={};let n=!1;se()?(r.uvue=!0,n=!0):H()?(r.nvue=!0,n=!0):ie()?(r.plus=!0,n=!0):v()&&(r.offline=!0,n=!0),n?r.app=!0:r.h5=!0,e(r)},{platform:this.name,method:"performGetEnv"})}}const ee=new tt;var rt=Object.freeze({__proto__:null,AppPlatform:tt,getEnv:t=>ee.getEnv(t),navigateBack:t=>ee.navigateBack(t),navigateTo:t=>ee.navigateTo(t),postMessage:t=>ee.postMessage(t),reLaunch:t=>ee.reLaunch(t),redirectTo:t=>ee.redirectTo(t),switchTab:t=>ee.switchTab(t)});function we(){return h()?et:rt}function Pr(t){return we().navigateTo(t)}function Rr(t){return we().navigateBack(t)}function Sr(t){return we().switchTab(t)}function Nr(t){return we().reLaunch(t)}function Tr(t){return we().redirectTo(t)}function nt(){return h()?et:rt}function Mr(t={}){return nt().postMessage(t)}function Lr(t){return nt().getEnv(t)}function br(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function xr(){return"qsh_callback_"+Date.now()+"_"+Math.random().toString(36).substring(2,9)}class vr{constructor(){this.callbacks=new Map,this.timeouts=new Map,this.persistentCallbacksByApi=new Map,this.defaultTimeout=3e4,typeof window!="undefined"&&(window.qshWebviewCallbacks||(window.qshWebviewCallbacks={})),w.debug("WebView 桥接器已初始化")}callApi(i){return I(this,arguments,function*(e,r={},n={}){return u.safeExecute(()=>I(this,null,function*(){var R;if(typeof window!="undefined"&&window===window.parent&&!window.plus&&!window.__uniapp_x_postMessage&&!window.__uniapp_x_&&!window.__dcloud_weex_postMessage&&!window.__dcloud_weex_&&!v()){const D=new N(b.PLATFORM_NOT_SUPPORTED,"当前不在宿主 WebView 容器中,无法发送消息");n&&typeof n.fail=="function"&&n.fail({errMsg:D.message,code:"NOT_IN_CONTAINER"}),n&&typeof n.complete=="function"&&n.complete({success:!1,error:{errMsg:D.message}});return}const c={apiName:e,params:r,callbacks:n,timestamp:Date.now(),abort:!1,metadata:{}};z.setApiLoading(e,!0);const g=yield Z.runRequest(c);if(g.abort){w.warn("API 调用被拦截器中止",{api:e}),z.setApiLoading(e,!1),n.fail&&n.fail({errMsg:((R=g.error)==null?void 0:R.message)||"API 调用被中止",code:"INTERCEPTED"}),n.complete&&n.complete({success:!1});return}const p=xr();if(n.success||n.fail||n.complete){if(this.callbacks.set(p,m(d({},n),{context:g})),window.qshWebviewCallbacks[p]=Be=>{this.handleCallback(p,Be)},r.isPersistent&&(this.persistentCallbacksByApi.has(e)||this.persistentCallbacksByApi.set(e,new Set),this.persistentCallbacksByApi.get(e).add(p)),r.isPersistent||r.disableTimeout)w.info(`API ${e} 禁用超时清理,将等待回调返回后清理`,{callbackId:p,isPersistent:r.isPersistent,disableTimeout:r.disableTimeout});else{const Be=setTimeout(()=>{w.warn("API 调用超时,自动清理回调",{api:e,callbackId:p}),n.fail&&n.fail({errMsg:`API ${e} 调用超时`,code:"TIMEOUT"}),this.cleanupCallback(p)},r.timeout||this.defaultTimeout);this.timeouts.set(p,Be)}const L={type:"qsh_api_call",api:e,params:g.params,callbackId:p,timestamp:Date.now()};w.info("发送 API 调用消息",{api:e,callbackId:p,hasSuccess:!!n.success,hasFail:!!n.fail}),console.log("message:",JSON.stringify(br(L),null,2)),me("postMessage",L)}}),{context:"WebViewBridge.callApi",api:e})})}handleCallback(e,r){return I(this,null,function*(){return u.safeExecute(()=>I(this,null,function*(){var D,L;const n=this.callbacks.get(e);if(!n){w.warn("未找到回调函数",{callbackId:e});return}const{success:i,fail:a,complete:c,context:g}=n;w.debug("处理回调",{callbackId:e,result:r});const p=yield Z.runResponse(r,g);g&&z.setApiResult(g.apiName,p),p.success&&i?i(p.data):!p.success&&a&&a(p.error||{errMsg:"操作失败"}),c&&c(p),((L=(D=n.context)==null?void 0:D.params)==null?void 0:L.isPersistent)?w.debug("持久监听API:保留回调",{callbackId:e}):(this.cleanupCallback(e),w.debug("回调执行完成,已清理",{callbackId:e}))}),{context:"WebViewBridge.handleCallback",callbackId:e})})}cleanupCallback(e){const r=this.timeouts.get(e);if(r&&(clearTimeout(r),this.timeouts.delete(e)),this.callbacks.delete(e),typeof window!="undefined"&&window.qshWebviewCallbacks&&delete window.qshWebviewCallbacks[e],this.persistentCallbacksByApi&&this.persistentCallbacksByApi.size>0){const n=[];this.persistentCallbacksByApi.forEach((i,a)=>{i.has(e)&&(i.delete(e),i.size===0&&n.push(a))}),n.forEach(i=>this.persistentCallbacksByApi.delete(i))}}clearCallbacks(){w.debug("清理所有回调",{count:this.callbacks.size}),this.timeouts.forEach(e=>clearTimeout(e)),this.timeouts.clear(),this.callbacks.clear(),this.persistentCallbacksByApi&&this.persistentCallbacksByApi.clear(),typeof window!="undefined"&&window.qshWebviewCallbacks&&Object.keys(window.qshWebviewCallbacks).forEach(e=>{e.startsWith("qsh_callback_")&&delete window.qshWebviewCallbacks[e]})}cleanupPersistentCallbacksByApi(e){const r=this.persistentCallbacksByApi.get(e);if(!r||r.size===0)return 0;const n=Array.from(r);return n.forEach(i=>this.cleanupCallback(i)),this.persistentCallbacksByApi.delete(e),w.info("已清理持久回调",{api:e,count:n.length}),n.length}getStatus(){return{isSupported:typeof window!="undefined"&&window.uni&&typeof window.uni.postMessage=="function",activeCallbacks:this.callbacks.size,globalCallbacksCount:typeof window!="undefined"&&window.qshWebviewCallbacks?Object.keys(window.qshWebviewCallbacks).length:0}}}const it=new vr,P=(t,e,r)=>it.callApi(t,e,r),le=t=>it.cleanupPersistentCallbacksByApi(t);function st(){return oe(!0)}function Dr(t){return t==="offline"}function Ur(t={}){return u.safeExecute(()=>{s.debug("Call getCode through offline webview bridge",{clientId:t.clientId}),P("getCode",{clientId:t.clientId},{success:e=>{var r;s.info("Get code success"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("Get code failed",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getCodeInHost",platform:st().type})}function Wr(t={}){return u.safeExecute(()=>{var n,i;const e=st(),r=String((t==null?void 0:t.clientId)||"").trim();if(!r){const a={errMsg:"clientId is required",code:"APP_KEY_MISSING"};s.error("Get code missing clientId"),(n=t.fail)==null||n.call(t,a);return}if(!Dr(e.type)){const a={errMsg:`Current environment (${e.type}) does not support getCode`,code:"PLATFORM_NOT_SUPPORTED"};s.error("Platform does not support getCode",{platform:e.type}),(i=t.fail)==null||i.call(t,a);return}Ur(m(d({},t),{clientId:r}))},{context:"getCode",options:t})}const Oe={ALBUM:"album",CAMERA:"camera"},Ce={ORIGINAL:"original",COMPRESSED:"compressed"},$r={count:9,sizeType:[Ce.ORIGINAL,Ce.COMPRESSED],sourceType:[Oe.ALBUM,Oe.CAMERA]};function Fr(t={}){const e=d(d({},$r),t);return Array.isArray(e.sizeType)||(e.sizeType=[e.sizeType].filter(Boolean)),Array.isArray(e.sourceType)||(e.sourceType=[e.sourceType].filter(Boolean)),e.count=Math.max(1,Math.min(9,parseInt(e.count)||1)),e.sizeType.length===0&&(e.sizeType=[Ce.COMPRESSED]),e.sourceType.length===0&&(e.sourceType=[Oe.ALBUM]),e}function at(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function ot(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!V()){s.info("等待微信配置完成"),k().then(()=>ot(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信图片选择",t),window.wx.chooseImage({count:t.count,sizeType:t.sizeType,sourceType:t.sourceType,success:r=>{var n,i;s.info("微信图片选择成功",{count:((n=r.localIds)==null?void 0:n.length)||0}),(i=t.success)==null||i.call(t,r)},fail:r=>{var n;s.error("微信图片选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"chooseImageInWeixin",platform:"weixin"})}function Br(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用图片选择",t),P("chooseImage",m(d({},t),{disableTimeout:!0}),{success:e=>{var r,n;s.info("UniApp 图片选择成功",{count:((r=e==null?void 0:e.tempFilePaths)==null?void 0:r.length)||0}),(n=t.success)==null||n.call(t,e)},fail:e=>{var r;s.error("UniApp 图片选择失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"chooseImageInUniApp",platform:"uniapp"})}function kr(t={}){return u.safeExecute(()=>{var r;if(!at()){const n={errMsg:`当前环境 (${l.type}) 不支持图片选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持图片选择",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Fr(t);s.info("开始选择图片",{platform:l.type,count:e.count,sizeType:e.sizeType,sourceType:e.sourceType}),h()?ot(e):Br(e)},{context:"chooseImage",options:t})}function zr(){return{supported:at(),environment:l.type,implementation:h()?"weixin":"webview",features:{multipleSelection:!0,sizeTypeSelection:!0,sourceTypeSelection:!0,asyncSupport:!0}}}const te={QR_CODE:"qrCode",BAR_CODE:"barCode",DATA_MATRIX:"datamatrix",PDF417:"pdf417"},Kr={onlyFromCamera:!0,scanType:[te.QR_CODE,te.BAR_CODE]};function Gr(t={}){const e=d(d({},Kr),t);return Array.isArray(e.scanType)||(e.scanType=[e.scanType].filter(Boolean)),e.scanType.length===0&&(e.scanType=[te.QR_CODE,te.BAR_CODE]),e.onlyFromCamera=!!e.onlyFromCamera,e}function ct(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function ut(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!V()){s.info("等待微信配置完成"),k().then(()=>ut(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信扫码",t),window.wx.scanQRCode({needResult:1,scanType:t.scanType,success:r=>{var i;s.info("微信扫码成功",{result:r.resultStr});const n={result:r.resultStr,scanType:Vr(r.resultStr),charSet:"utf-8",errMsg:"scanCode:ok"};(i=t.success)==null||i.call(t,n)},fail:r=>{var n;s.error("微信扫码失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"scanCodeInWeixin",platform:"weixin"})}function Vr(t){return t?t.length>50||/[^\d]/.test(t)?te.QR_CODE:te.BAR_CODE:"unknown"}function jr(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用扫码",t),P("scanCode",m(d({},t),{disableTimeout:!0}),{success:e=>{var r;s.info("UniApp 扫码成功",{result:e==null?void 0:e.result,scanType:e==null?void 0:e.scanType}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 扫码失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"scanCodeInUniApp",platform:"uniapp"})}function qr(t={}){return u.safeExecute(()=>{var r;if(!ct()){const n={errMsg:`当前环境 (${l.type}) 不支持扫码功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持扫码",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Gr(t);s.info("开始扫码",{platform:l.type,onlyFromCamera:e.onlyFromCamera,scanType:e.scanType}),h()?ut(e):jr(e)},{context:"scanCode",options:t})}function Jr(){return{supported:ct(),environment:l.type,implementation:h()?"weixin":"webview",features:{onlyFromCamera:!0,scanTypeSelection:!0,multipleTypes:!0,asyncSupport:!0}}}const fe={WGS84:"wgs84",GCJ02:"gcj02",BD09:"bd09"},Hr={type:fe.WGS84,altitude:!1},Yr={scale:18};function Xr(t={}){const e=d(d({},Hr),t);return Object.values(fe).includes(e.type)||(e.type=fe.WGS84),e.altitude=!!e.altitude,e}function Zr(t={}){const e=d({},t);return Object.values(fe).includes(e.type)||(e.type=fe.WGS84),e.needFullAccuracy=!!e.needFullAccuracy,e}function Qr(t={}){const e=d(d({},Yr),t);if(e.latitude===void 0||e.latitude===null)throw{errMsg:"缺少必需参数:latitude(纬度)",code:"PARAM_MISSING"};if(typeof e.latitude!="number")throw{errMsg:`latitude 参数类型错误:期望 number,实际 ${typeof e.latitude}`,code:"PARAM_TYPE_ERROR",details:{param:"latitude",expected:"number",actual:typeof e.latitude,value:e.latitude}};if(e.latitude<-90||e.latitude>90)throw{errMsg:`latitude 超出范围:有效范围 -90 ~ 90,实际值 ${e.latitude}`,code:"PARAM_INVALID",details:{param:"latitude",value:e.latitude,validRange:"-90 ~ 90"}};if(e.longitude===void 0||e.longitude===null)throw{errMsg:"缺少必需参数:longitude(经度)",code:"PARAM_MISSING"};if(typeof e.longitude!="number")throw{errMsg:`longitude 参数类型错误:期望 number,实际 ${typeof e.longitude}`,code:"PARAM_TYPE_ERROR",details:{param:"longitude",expected:"number",actual:typeof e.longitude,value:e.longitude}};if(e.longitude<-180||e.longitude>180)throw{errMsg:`longitude 超出范围:有效范围 -180 ~ 180,实际值 ${e.longitude}`,code:"PARAM_INVALID",details:{param:"longitude",value:e.longitude,validRange:"-180 ~ 180"}};if(e.scale!==void 0&&e.scale!==null){const r=Number(e.scale);isNaN(r)?(s.warn("scale 参数无效,使用默认值 18",{scale:e.scale}),e.scale=18):e.scale=Math.max(1,Math.min(28,Math.floor(r)))}return e}function Me(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function lt(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!V()){s.info("等待微信配置完成"),k().then(()=>lt(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信定位",t),window.wx.getLocation({type:t.type,success:r=>{var n;s.info("微信定位成功",{latitude:r.latitude,longitude:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信定位失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"getLocationInWeixin",platform:"weixin"})}function ft(t){return u.safeExecute(()=>{var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}if(!V()){s.info("等待微信配置完成"),k().then(()=>ft(t)).catch(r=>{var n;s.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}s.debug("调用微信查看位置",t),window.wx.openLocation({latitude:t.latitude,longitude:t.longitude,name:t.name||"",address:t.address||"",scale:t.scale||18,infoUrl:t.infoUrl||"",success:r=>{var n;s.info("微信查看位置成功"),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("微信查看位置失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"openLocationInWeixin",platform:"weixin"})}function en(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用获取位置",t),P("getLocation",t,{success:e=>{var r;s.info("UniApp 获取位置成功",{latitude:e==null?void 0:e.latitude,longitude:e==null?void 0:e.longitude}),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 获取位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getLocationInUniApp",platform:"uniapp"})}function tn(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用查看位置",t),P("openLocation",t,{success:e=>{var r;s.info("UniApp 查看位置成功"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 查看位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"openLocationInUniApp",platform:"uniapp"})}function rn(t={}){return u.safeExecute(()=>{var r;if(!Me()){const n={errMsg:`当前环境 (${l.type}) 不支持定位功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持定位",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Xr(t);s.info("开始获取位置",{platform:l.type,type:e.type,altitude:e.altitude}),h()?lt(e):en(e)},{context:"getLocation",options:t})}function nn(t={}){return u.safeExecute(()=>{var r,n,i;if(!Me()){const a={errMsg:`当前环境 (${l.type}) 不支持查看位置功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持查看位置",{platform:l.type}),(r=t.fail)==null||r.call(t,a);return}let e;try{e=Qr(t)}catch(a){s.error("参数验证失败",a),(n=t.fail)==null||n.call(t,a),(i=t.complete)==null||i.call(t);return}s.info("开始查看位置",{platform:l.type,latitude:e.latitude,longitude:e.longitude,name:e.name}),h()?ft(e):tn(e)},{context:"openLocation",options:t})}function sn(){const t=h();return{supported:Me(),environment:l.type,implementation:t?"weixin":"webview",features:{getLocation:!0,openLocation:!0,coordinateTypes:!0,altitudeSupport:!0,asyncSupport:!0,onLocationChange:!t}}}const q=new Set,J=new Set;function dt(t,e,r){t.forEach(n=>{if(typeof n=="function"){u.safeExecute(()=>n(e),{context:r});return}s.warn("监听回调不是函数,已跳过",{type:typeof n})})}function an(t={}){return u.safeExecute(()=>{var r,n;if(h()){const i={errMsg:`当前环境 (${l.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};s.error("当前环境不支持此接口",{platform:l.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=Zr(t);s.info("正在开启定位监听"),P("startLocationUpdate",{type:e.type,needFullAccuracy:e.needFullAccuracy},{success:i=>{var a;s.info("定位监听已启动"),(a=t.success)==null||a.call(t,i)},fail:i=>{var a;return(a=t.fail)==null?void 0:a.call(t,i)},complete:t.complete})},{context:"startLocationUpdate"})}function on(t={}){return u.safeExecute(()=>{var e,r;if(h()){const n={errMsg:`当前环境 (${l.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};s.error("当前环境不支持此接口",{platform:l.type}),(e=t.fail)==null||e.call(t,n),(r=t.complete)==null||r.call(t,n);return}s.info("正在停止定位监听"),P("stopLocationUpdate",t,{success:n=>{var i;s.info("定位监听已停止"),(i=t.success)==null||i.call(t,n)},fail:n=>{var i;return(i=t.fail)==null?void 0:i.call(t,n)},complete:t.complete})},{context:"stopLocationUpdate"})}function cn(t){return u.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:l.type});return}if(typeof t!="function")throw s.error("onLocationChange 回调不是函数",{type:typeof t}),{errMsg:"onLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};const e=q.size>0;q.add(t),e||(s.debug("注册实时位置变化监听器"),P("onLocationChange",{isPersistent:!0},{success:r=>{s.debug("收到实时位置推送",r),dt(q,r,"onLocationChange")},fail:r=>{s.warn("位置变化监听出错,请通过 onLocationChangeError 监听错误",r),q.delete(t),q.size===0&&le("onLocationChange")}}))},{context:"onLocationChange"})}function un(t){return u.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:l.type});return}if(t&&typeof t!="function")throw s.error("offLocationChange 回调不是函数",{type:typeof t}),{errMsg:"offLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};t?q.delete(t):q.clear(),!(q.size>0)&&(s.info("移除位置变化监听器"),P("offLocationChange",{},{success:()=>{s.info("位置变化监听已移除"),le("onLocationChange")},fail:e=>{s.error("移除位置变化监听失败",e),le("onLocationChange")}}))},{context:"offLocationChange"})}function ln(t){return u.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:l.type});return}if(typeof t!="function")throw s.error("onLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"onLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};const e=J.size>0;J.add(t),e||(s.debug("注册位置更新错误监听器"),P("onLocationChangeError",{isPersistent:!0},{success:r=>{s.warn("持续定位发生异常",r),dt(J,r,"onLocationChangeError")},fail:r=>{s.warn("位置更新错误监听注册失败",r),J.delete(t),J.size===0&&le("onLocationChangeError")}}))},{context:"onLocationChangeError"})}function fn(t){return u.safeExecute(()=>{if(h()){s.warn("当前环境不支持此接口",{platform:l.type});return}if(t&&typeof t!="function")throw s.error("offLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"offLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};t?J.delete(t):J.clear(),!(J.size>0)&&(s.info("移除定位错误监听器"),P("offLocationChangeError",{},{success:()=>{s.info("定位错误监听已移除"),le("onLocationChangeError")},fail:e=>{s.error("移除定位错误监听失败",e),le("onLocationChangeError")}}))},{context:"offLocationChangeError"})}const dn={latitude:null,longitude:null};function gn(t={}){const e=d(d({},dn),t);return e.latitude!==null&&e.latitude!==void 0&&(typeof e.latitude!="number"?(s.warn("latitude 参数类型错误,已忽略",{latitude:e.latitude}),e.latitude=null):(e.latitude<-90||e.latitude>90)&&(s.warn("latitude 超出范围,已忽略",{latitude:e.latitude}),e.latitude=null)),e.longitude!==null&&e.longitude!==void 0&&(typeof e.longitude!="number"?(s.warn("longitude 参数类型错误,已忽略",{longitude:e.longitude}),e.longitude=null):(e.longitude<-180||e.longitude>180)&&(s.warn("longitude 超出范围,已忽略",{longitude:e.longitude}),e.longitude=null)),e}function gt(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function ht(t){return u.safeExecute(()=>{var n;if(!window.wx){const i={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(n=t.fail)==null||n.call(t,i);return}if(!V()){s.info("等待微信配置完成"),k().then(()=>ht(t)).catch(i=>{var a;s.error("微信配置失败",i),(a=t.fail)==null||a.call(t,{errMsg:`微信配置失败: ${i.message}`})});return}s.debug("调用微信位置选择",t);const e={success:i=>{var c;s.info("微信位置选择成功",{name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude});const a={name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude,errMsg:"chooseLocation:ok"};(c=t.success)==null||c.call(t,a)},fail:i=>{var a;s.error("微信位置选择失败",i),(a=t.fail)==null||a.call(t,i)},complete:t.complete},r={};t.latitude!==null&&t.latitude!==void 0&&(r.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(r.longitude=t.longitude),window.wx.chooseLocation(m(d({},r),{success:e.success,fail:e.fail,complete:e.complete}))},{context:"chooseLocationInWeixin",platform:"weixin"})}function hn(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用位置选择",t);const e={disableTimeout:!0,success:r=>{var n;s.info("UniApp 位置选择成功",{name:r==null?void 0:r.name,address:r==null?void 0:r.address,latitude:r==null?void 0:r.latitude,longitude:r==null?void 0:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;s.error("UniApp 位置选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete};t.latitude!==null&&t.latitude!==void 0&&(e.latitude=t.latitude),t.longitude!==null&&t.longitude!==void 0&&(e.longitude=t.longitude),P("chooseLocation",e,{success:r=>{e.success(r)},fail:r=>{e.fail(r)},complete:e.complete})},{context:"chooseLocationInUniApp",platform:"uniapp"})}function pn(t={}){return u.safeExecute(()=>{var r;if(!gt()){const n={errMsg:`当前环境 (${l.type}) 不支持位置选择功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持位置选择",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=gn(t);s.info("开始选择位置",{platform:l.type,latitude:e.latitude,longitude:e.longitude}),h()?ht(e):hn(e)},{context:"chooseLocation",options:t})}function mn(){return{supported:gt(),environment:l.type,implementation:h()?"weixin":"webview",features:{chooseLocation:!0,centerPoint:!0,asyncSupport:!0}}}const pt=new Map;function wn(t,e={}){pt.set(t,e)}function mt(t,e){const r=pt.get(t);if(r)return r[e]||r.default}const En={0:"WXSceneSession",1:"WXSceneTimeline"},yn={0:"图文/网页",1:"纯文字",2:"纯图片",3:"音乐",4:"视频",5:"小程序"};function wt(t={}){return u.safeExecute(()=>{var r;if(typeof window=="undefined"||!window.wx){const n={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};return(r=t.fail)==null||r.call(t,n),Promise.reject(n)}if(!V())return s.info("等待微信配置完成"),k().then(()=>wt(t));const e=d({},t);return s.debug("调用微信分享",e),t!=null&&t.isCallBack?new Promise((n,i)=>{P("toShareData",t,{success:a=>{var c;(c=t.success)==null||c.call(t,a),n(a)},fail:a=>{var c;s.error("UniApp 微信分享失败",a),(c=t.fail)==null||c.call(t,a),i(a)},complete:t.complete})}):new Promise((n,i)=>{window.wx[e.scene](m(d({},e),{success:()=>{var c;const a={errMsg:"weixinShare:ok"};(c=t.success)==null||c.call(t,a),n(a)},fail:a=>{var g;const c={errMsg:(a==null?void 0:a.errMsg)||"weixinShare:fail",details:a};s.error("微信分享失败",c),(g=t.fail)==null||g.call(t,c),i(c)},complete:t.complete}))})},{context:"toShareInWeixin",platform:"weixin"})}function Et(t={},e){const r=d({},t),n={scene:r.scene===1?"updateTimelineShareData":"updateAppMessageShareData"};return s.info("格式化微信参数",r),Object.prototype.hasOwnProperty.call(r,"title")?Object.prototype.hasOwnProperty.call(r,"imageUrl")?Object.prototype.hasOwnProperty.call(r,"path")?Object.prototype.hasOwnProperty.call(r,"summary")?(n.title=r.title,n.imgUrl=r.imageUrl,n.link=r.path,n.desc=r.summary,{params:n,success:!0}):{message:"参数字段summary值缺少!",success:!1}:{message:"参数字段path值缺少!",success:!1}:{message:"参数字段imageUrl值缺少!9999",success:!1}:{message:"参数字段title值缺少!",success:!1}}function re(t={}){return u.safeExecute(()=>(s.debug("通过 WebView 桥接调用微信分享",t),console.log("桥接调用微信分享桥接调用微信分享:",JSON.stringify(be(t),null,2)),new Promise((e,r)=>{P("toShareData",t,{success:n=>{var i;(i=t.success)==null||i.call(t,n),e(n)},fail:n=>{var i;s.error("UniApp 微信分享失败",n),(i=t.fail)==null||i.call(t,n),r(n)},complete:t.complete})})),{context:"toShareInUniApp",platform:"uniapp"})}function yt(t={}){const e=d({},t),r={provider:"weixin",scene:"WXSceneSession"};if(s.info("格式化 UniApp 参数",e),[0,1].some(n=>parseInt(n)===parseInt(e.scene))?r.scene=En[e.scene]:r.scene="WXSceneSession",Object.prototype.hasOwnProperty.call(e,"type")){const n=Number(e.type);if(Object.keys(yn).some(a=>parseInt(a)===n)){if(r.type=n,[0].includes(n))if(Object.prototype.hasOwnProperty.call(e,"path"))r.href=e.path;else return{message:"参数字段path值缺少!",success:!1};if([0,1].includes(n))if(Object.prototype.hasOwnProperty.call(e,"summary"))r.summary=e.summary;else return{message:"参数字段summary值缺少!",success:!1};if([0,2,5].includes(n))if(Object.prototype.hasOwnProperty.call(e,"imageUrl"))r.imageUrl=e.imageUrl;else return{message:"参数字段imageUrl值缺少!",success:!1};[5].includes(n)&&Object.prototype.hasOwnProperty.call(e,"miniProgram")&&d({},e.miniProgram),Object.prototype.hasOwnProperty.call(e,"title")&&(r.title=e.title),Object.prototype.hasOwnProperty.call(e,"success")&&(r.success=e.success),Object.prototype.hasOwnProperty.call(e,"fail")&&(r.fail=e.fail),Object.prototype.hasOwnProperty.call(e,"complete")&&(r.complete=e.complete)}else return{message:"参数字段type值有误!",success:!1}}else return{message:"参数字段type缺少!",success:!1};return{params:r,success:!0}}const Le="share.toShare";wn(Le,{weixin:wt,webview:re,plus:re,nvue:re,uvue:re,UniApp:re,offline:re,h5:re,default:void 0});function be(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function It(t={}){return u.safeExecute(()=>{var a,c;const e=oe(),r=mt(Le,e.type);if(typeof r!="function"){const g={errMsg:`当前环境 (${e.type}) 不支持微信分享功能`,code:"PLATFORM_NOT_SUPPORTED"};return s.error("平台不支持微信分享",{platform:e.type}),(a=t.fail)==null||a.call(t,g),Promise.reject(g)}const n=h()?Et(t):yt(t);if(!n.success){const g={errMsg:n.message||"参数校验失败",code:"INVALID_PARAMS"};return(c=t.fail)==null||c.call(t,g),Promise.reject(g)}const i=n.params;return s.info("开始微信分享",{platform:e.type,type:i==null?void 0:i.type}),r(i)},{context:"toShare",options:t})}function In(t={}){return new Promise((e,r)=>{It(m(d({},t),{success:e,fail:r}))})}function At(t={}){return u.safeExecute(()=>{var a,c;const e=oe(),r=mt(Le,e.type);if(typeof r!="function"){const g={errMsg:`当前环境 (${e.type}) 不支持微信分享功能`,code:"PLATFORM_NOT_SUPPORTED"};return s.error("平台不支持微信分享",{platform:e.type}),(a=t.fail)==null||a.call(t,g),Promise.reject(g)}const n=h()?Et(t):yt(t);if(console.log("normalizednormalizednormalized:",JSON.stringify(be(n),null,2)),!n.success){const g={errMsg:n.message||"参数校验失败",code:"INVALID_PARAMS"};return(c=t.fail)==null||c.call(t,g),console.log("你是什么东西啊:",JSON.stringify(be(g),null,2)),Promise.reject(g)}const i=n.params;return s.info("开始微信分享",{platform:e.type,type:i==null?void 0:i.type}),r(m(d({},i),{isCallBack:!0}))},{context:"toShare",options:t})}function An(t={}){return new Promise((e,r)=>{At(m(d({},t),{success:e,fail:r}))})}const On={OFF:"off",ON:"on",UNAVAILABLE:"unavailable",UNAUTHORIZED:"unauthorized"},Cn={allowDuplicatesKey:!1,services:[]};function _e(t={}){return d(d({},Cn),t)}function Ee(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function _n(t){return u.safeExecute(()=>I(null,null,function*(){var e;if(!window.wx){const r={errMsg:"微信JS-SDK未加载",code:"WEIXIN_SDK_NOT_LOADED"};(e=t.fail)==null||e.call(t,r);return}V()||(s.info("等待微信配置完成"),yield k()),wx.openBluetoothAdapter({success:()=>{s.info("微信蓝牙适配器已打开"),Ot(t)},fail:r=>{var n;s.error("蓝牙适配器打开失败",r),(n=t.fail)==null||n.call(t,r)}})}),{context:"openBluetoothAdapterInWeixin"})}function Pn(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用蓝牙功能",t),P("bluetooth",t,{success:e=>{var r;s.info("UniApp 蓝牙调用成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 蓝牙调用失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"bluetoothInUniApp"})}function Rn(t){return u.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙设备搜索功能",t),P("bluetoothDevicesDiscovery",{action:"startBluetoothDevicesDiscovery",params:{services:t.services||[],allowDuplicatesKey:(e=t.allowDuplicatesKey)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 设备开启搜索成功:",r),s.info("UniApp 蓝牙设备开启搜索成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 设备开启搜索失败:",r),s.error("UniApp 蓝牙设备开启搜索失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"startBluetoothDevicesDiscoveryInUniApp"})}const Pe=new Set;function Sn(t,e={}){return u.safeExecute(()=>{var r;return Pe.add(t),Pe.size===1&&P("onBluetoothDeviceFound",{action:"onBluetoothDeviceFound",isPersistent:!0,params:{services:e.services||[],allowDuplicatesKey:(r=e.allowDuplicatesKey)!=null?r:!1}},{success:n=>{Pe.forEach(i=>{typeof i=="function"?u.safeExecute(()=>i(n),{context:"BluetoothDeviceCallback"}):console.warn("[BluetoothDeviceCallback] 不是函数:",i)})},fail:n=>{var i;console.error("[Bluetooth] 搜索失败:",n),(i=e.fail)==null||i.call(e,n)},complete:e.complete}),()=>Pe.delete(t)},{context:"qsh_onBluetoothDeviceFound"})}function Nn(t){return u.safeExecute(()=>{var e;s.debug("通过 WebView 桥接调用蓝牙连接功能",t),P("bluetoothConnection",{action:"createBLEConnection",params:{deviceId:t.deviceId,name:t.name,autoConnect:(e=t.autoConnect)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 蓝牙连接成功:",r),s.info("UniApp 蓝牙连接成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 蓝牙连接失败:",r),s.error("UniApp 蓝牙连接失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"createBLEConnectionInUniApp"})}function Tn(t={}){return u.safeExecute(()=>{var r;if(!Ee()){const n={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=_e(t);s.info("开始蓝牙操作",{platform:l.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),h()?_n(e):Pn(e)},{context:"openBluetoothAdapter",options:t})}function Mn(t={}){return u.safeExecute(()=>{var r,n;if(!Ee()){const i={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:l.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=_e(t);s.info("开始搜索蓝牙设备",{platform:l.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),h()?startBluetoothDevicesDiscoveryInWeixin(e):Rn(e)},{context:"startBluetoothDevicesDiscovery",options:t})}function Ot(t,e={}){return u.safeExecute(()=>{var n,i;if(!Ee()){const a={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙",{platform:l.type}),(n=e.fail)==null||n.call(e,a),(i=e.complete)==null||i.call(e,a);return}const r=_e(e);s.info("注册蓝牙设备发现监听",{platform:l.type}),h()?onBluetoothDeviceFoundInWeixin(r):Sn(t,r)},{context:"onBluetoothDeviceFound",options:e})}function Ln(t={}){return u.safeExecute(()=>{var a,c,g,p;if(!Ee()){const R={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持蓝牙连接",{platform:l.type}),(a=t.fail)==null||a.call(t,R),(c=t.complete)==null||c.call(t,R);return}const e=_e(t),{name:r,deviceId:n,autoConnect:i=!1}=e;if(!n){const R={errMsg:"缺少 deviceId 参数",code:"INVALID_PARAMS"};(g=t.fail)==null||g.call(t,R),(p=t.complete)==null||p.call(t,R);return}s.info("创建蓝牙连接",{deviceId:n,autoConnect:i,platform:l.type}),h()?uni.createBLEConnection({deviceId:n,autoConnect:i,success:t.success,fail:t.fail,complete:t.complete}):Nn(e)},{context:"createBLEConnection",options:t})}function bn(){return{supported:Ee(),environment:l.type,implementation:h()?"weixin":"webview",features:{discovery:!0,connect:!0,readWrite:!0,notify:!0,asyncSupport:!0}}}const xn={};function vn(t={}){return d(d({},xn),t)}function Ct(){return["webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function Dn(t){return u.safeExecute(()=>{s.debug("通过 WebView 桥接调用打印PDF",t),P("printPdf",m(d({},t),{isPersistent:!0}),{success:e=>{var r;s.info("UniApp 打印PDF成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;s.error("UniApp 打印PDF失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"printPdfInUniApp",platform:"uniapp"})}function Un(t={}){return u.safeExecute(()=>{var r;if(!Ct()){const n={errMsg:`当前环境 (${l.type}) 不支持打印PDF功能`,code:"PLATFORM_NOT_SUPPORTED"};s.error("平台不支持打印PDF",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=vn(t);s.info("开始打印PDF",{platform:l.type}),Dn(e)},{context:"printPdf",options:t})}function Wn(){return{supported:Ct(),environment:l.type,implementation:"uniapp",features:{asyncSupport:!0}}}const xe="/pages/face/index";function $n(t={}){const e=d({},t);if(!e.name||typeof e.name!="string"||!e.name.trim())throw{errMsg:"缺少必需参数:name(姓名)",code:"PARAM_MISSING"};if(e.name=e.name.trim(),!e.idCardNumber||typeof e.idCardNumber!="string"||!e.idCardNumber.trim())throw{errMsg:"缺少必需参数:idCardNumber(身份证号)",code:"PARAM_MISSING"};return e.idCardNumber=e.idCardNumber.trim(),e}function _t(){return h()}function Fn(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram&&typeof window.wx.miniProgram.navigateTo=="function"}function Bn(t){const e=m(d({},t),{title:document.title||"",url:window.location.href||""}),r=Object.entries(e).filter(([,n])=>n!=null&&n!=="").map(([n,i])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`).join("&");return r?`${xe}?${r}`:xe}function kn(t){return u.safeExecute(()=>{if(!Fn()){s.error("微信小程序导航API不可用");return}const e=Bn(t);s.debug("跳转宿主人脸识别页面",{name:t.name,targetUrl:e}),window.wx.miniProgram.navigateTo({url:e,success:()=>{s.info("已跳转到宿主人脸识别页面",{targetUrl:e})},fail:r=>{s.error("跳转宿主人脸识别页面失败",r)}})},{context:"faceVerifyInWeixin",platform:"weixin"})}function zn(t={}){return u.safeExecute(()=>{if(!_t()){s.error("平台不支持人脸识别",{platform:l.type});return}let e;try{e=$n(t)}catch(r){s.error("人脸识别参数校验失败",r);return}s.info("开始人脸识别",{platform:l.type,name:e.name,pagePath:xe}),kn(e)},{context:"faceVerify",options:t})}function Kn(){return{supported:_t(),environment:l.type,implementation:"weixin",features:{asyncSupport:!0,hostPageNavigation:!0}}}const Pt=oe();function Gn(){if(typeof window=="undefined"||!oe(!0).isWeixinMiniProgram)return!1;const e=Ne().getRuntimeConfig();return typeof e.clientId=="string"&&e.clientId.length>0}function Vn(){return I(this,null,function*(){yield Yt(),Gn()&&(yield k())})}Z.useResponse(Xe.response,{priority:1e3});let Rt=!1;function St(){if(Rt)return;Rt=!0,wr([{name:"load-weixin-sdk",run:Ve,timeoutMs:8e3},{name:"init-bridge",run:Ke,timeoutMs:8e3}],{onError:(e,r)=>{console.error(`[QSH-SDK] 初始化失败(${(r==null?void 0:r.name)||"unknown"}):`,e)}})}typeof window!="undefined"&&(document.readyState==="complete"||document.readyState==="interactive"?setTimeout(St,0):document.addEventListener("DOMContentLoaded",St));function y(t,{apiName:e}={}){return function(r={},...n){const i=r&&typeof r=="object"&&(typeof r.success=="function"||typeof r.fail=="function"||typeof r.complete=="function"),a=r&&typeof r=="object"?r:{},c=()=>i?t(a,...n):new Promise((p,R)=>{const D=m(d({},a),{success:L=>{typeof a.success=="function"&&a.success(L),p(L)},fail:L=>{typeof a.fail=="function"&&a.fail(L),R(L)},complete:a.complete});t(D,...n)});return(typeof window=="undefined"?Promise.resolve():ze()).then(()=>c()).catch(p=>{throw console.error(`[QSH-SDK] ${e||"API"} call failed:`,p),p})}}function Re(t){return typeof t=="function"?{success:t}:t&&typeof t=="object"?t:{}}const Nt=y(Pr),Tt=y(Rr),Mt=y(Sr),Lt=y(Nr),bt=y(Tr),xt=y(Mr);function vt(t){const e=()=>Lr(t);return(typeof window=="undefined"?Promise.resolve():ze()).then(()=>e())}const ve=y(Wr,{apiName:"getCode"});function jn(t={}){return new Promise((e,r)=>{ve(m(d({},t),{success:e,fail:r}))})}const De=y(kr);function qn(t={}){return new Promise((e,r)=>{De(m(d({},t),{success:e,fail:r}))})}const Dt=y(Un);function Jn(t={}){return new Promise((e,r)=>{Dt(m(d({},t),{success:e,fail:r}))})}const Ue=y(qr),Hn=y(zn);function Yn(t={}){return new Promise((e,r)=>{Ue(m(d({},t),{success:e,fail:r}))})}const Xn=y(It),Zn=y(In),Qn=y(At),ei=y(An),We=y(rn);function ti(t={}){return new Promise((e,r)=>{We(m(d({},t),{success:e,fail:r}))})}const $e=y(nn);function ri(t={}){return new Promise((e,r)=>{$e(m(d({},t),{success:e,fail:r}))})}const Fe=y(pn);function ni(t={}){return new Promise((e,r)=>{Fe(m(d({},t),{success:e,fail:r}))})}const Ut=y(Tn);function ii(t={}){return new Promise((e,r)=>{Ut(m(d({},t),{success:e,fail:r}))})}const Wt=y(Mn);function si(t={}){return new Promise((e,r)=>{Wt(m(d({},t),{success:e,fail:r}))})}const $t=y(Ot);function ai(t={}){return new Promise((e,r)=>{$t(m(d({},t),{success:e,fail:r}))})}const Ft=y(Ln);function oi(t={}){return new Promise((e,r)=>{Ft(m(d({},t),{success:e,fail:r}))})}const ne={navigateTo:Nt,navigateBack:Tt,switchTab:Mt,reLaunch:Lt,redirectTo:bt,postMessage:xt,getEnv:vt,getCode:ve,getCodeAsync:jn,chooseImage:De,chooseImageAsync:qn,scanCode:Ue,scanCodeAsync:Yn,getLocation:We,getLocationAsync:ti,openLocation:$e,openLocationAsync:ri,chooseLocation:Fe,chooseLocationAsync:ni,onLocationChange:t=>y((e={})=>cn(e.success),{apiName:"onLocationChange"})(Re(t)),offLocationChange:t=>y((e={})=>un(e.success),{apiName:"offLocationChange"})(Re(t)),onLocationChangeError:t=>y((e={})=>ln(e.success),{apiName:"onLocationChangeError"})(Re(t)),offLocationChangeError:t=>y((e={})=>fn(e.success),{apiName:"offLocationChangeError"})(Re(t)),startLocationUpdate:y(an,{apiName:"startLocationUpdate"}),stopLocationUpdate:y(on,{apiName:"stopLocationUpdate"}),environment:Pt,ready:Vn,init:Ke,isReady:Gt,getState:Vt,config:je,weixin:{config:je,waitForConfig:k,isConfigReady:V,getConfigState:tr,retryConfig:rr},webView:null,ImageSourceTypes:Oe,ImageSizeTypes:Ce,getImageCapabilities:zr,ScanTypes:te,getScanCapabilities:Jr,CoordinateTypes:fe,getLocationCapabilities:sn,getChooseLocationCapabilities:mn,openBluetoothAdapter:Ut,openBluetoothAdapterAsync:ii,startBluetoothDevicesDiscovery:Wt,startBluetoothDevicesDiscoveryAsync:si,onBluetoothDeviceFound:$t,onBluetoothDeviceFoundAsync:ai,createBLEConnection:Ft,createBLEConnectionAsync:oi,BluetoothStates:On,toShare:Xn,toShareAsync:Zn,toShareCallBack:Qn,toShareCallBackAsync:ei,getBluetoothCapabilities:bn,printPdf:Dt,printPdfAsync:Jn,getPrintCapabilities:Wn,faceVerify:Hn,getFaceCapabilities:Kn,plugins:{manager:he,register:t=>he.register(t),install:t=>he.install(t,ne),list:()=>he.getPluginList()},interceptors:{chain:Z,useRequest:(t,e)=>Z.useRequest(t,e),useResponse:(t,e)=>Z.useResponse(t,e),builtin:{logging:sr,performance:j,createRetry:ar,createValidation:or,errorNormalizer:Xe}},metrics:{getPerformanceReport:()=>j.getReport(),clearPerformanceMetrics:()=>j.clearMetrics()},errors:{codes:o,messages:Te,categories:F,normalize:Ye,create:hr,isStandard:pr},store:{instance:z,get:t=>z.get(t),set:(t,e)=>z.set(t,e),subscribe:(t,e)=>z.subscribe(t,e),getSnapshot:()=>z.getSnapshot()},debug:{logger:M,setLogReporter:t=>M.setReporter(t),errorHandler:u,stateManager:X,enableDevMode:()=>M.enableDevMode(),getLogs:t=>M.getHistory(t),getStats:()=>({logger:M.getStats(),state:X.getStats(),weixinConfig:Ne().getStats(),plugins:he.getStats(),interceptors:Z.getStats(),store:z.getStats()}),getWeixinConfigManager:Ne,exportDebugInfo:()=>M.exportToJSON()}};Pt.isWeixinMiniProgram?ne.webView=window.wx&&window.wx.miniProgram:ne.webView={navigateTo:Nt,navigateBack:Tt,switchTab:Mt,reLaunch:Lt,redirectTo:bt,postMessage:xt,getEnv:vt,getCode:ve,chooseImage:De,scanCode:Ue,getLocation:We,openLocation:$e,chooseLocation:Fe};const Bt=typeof window.uni!="undefined"?window.uni:{};return Object.keys(Bt).forEach(t=>{ne.hasOwnProperty(t)||(ne[t]=Bt[t])}),typeof window!="undefined"&&(window.qsh=ne),ne});
2
2
  //# sourceMappingURL=qsh-webview-sdk.umd.js.map