qsh-webview-sdk 2.3.3 → 2.3.4

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(O,A){typeof exports=="object"&&typeof module!="undefined"?module.exports=A():typeof define=="function"&&define.amd?define(A):(O=typeof globalThis!="undefined"?globalThis:O||self,O.qsh=A())})(this,function(){"use strict";var ai=Object.defineProperty,si=Object.defineProperties;var oi=Object.getOwnPropertyDescriptors;var Dt=Object.getOwnPropertySymbols;var ci=Object.prototype.hasOwnProperty,ui=Object.prototype.propertyIsEnumerable;var Fe=(O,A,m)=>A in O?ai(O,A,{enumerable:!0,configurable:!0,writable:!0,value:m}):O[A]=m,g=(O,A)=>{for(var m in A||(A={}))ci.call(A,m)&&Fe(O,m,A[m]);if(Dt)for(var m of Dt(A))ui.call(A,m)&&Fe(O,m,A[m]);return O},p=(O,A)=>si(O,oi(A));var G=(O,A,m)=>Fe(O,typeof A!="symbol"?A+"":A,m);var y=(O,A,m)=>new Promise((ne,j)=>{var ie=U=>{try{H(m.next(U))}catch(D){j(D)}},ae=U=>{try{H(m.throw(U))}catch(D){j(D)}},H=U=>U.done?ne(U.value):Promise.resolve(U.value).then(ie,ae);H((m=m.apply(O,A)).next())});function O(){return typeof window!="undefined"?window:void 0}function A(){return typeof navigator=="undefined"?"":navigator.userAgent||""}function m(){const t=O();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 ne(){const t=O();return!!(t&&t.plus)}function j(){const t=O();return!!(t&&(t.__dcloud_weex_postMessage||t.__dcloud_weex_))}function ie(){const t=O();return!!(t&&(t.__uniapp_x_postMessage||t.__uniapp_x_))}function ae(){const t=A();return/uni-app/i.test(t)}function H(){const t=A();return/Html5Plus/i.test(t)}function U(){return ae()||H()}function D(){const t=O();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 Ut(){return ie()?"uvue":j()?"nvue":m()?"weixin":D()?"offline":ne()?"plus":U()?"webview":ae()?"UniApp":"h5"}let ye=null;function se(t=!1){return ye&&!t||(ye={isWeixinMiniProgram:m(),isAppPlus:ne(),isNvue:j(),isUvue:ie(),isUniApp:ae(),isHtml5Plus:H(),isUniAppWebView:U(),isOfflineWebview:D(),type:Ut()}),ye}const l=se(),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 T 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,T)}toJSON(){return{name:this.name,type:this.type,message:this.message,context:this.context,timestamp:this.timestamp,stack:this.stack}}}const P=class P{static setDebugMode(e){P.isDebugMode=e}static addErrorCallback(e){typeof e=="function"&&P.errorCallbacks.push(e)}static removeErrorCallback(e){const r=P.errorCallbacks.indexOf(e);r>-1&&P.errorCallbacks.splice(r,1)}static handleApiError(e,r={}){let n;return e instanceof T?n=e:e instanceof Error?n=new T(b.API_CALL_FAILED,e.message,r,e):n=new T(b.API_CALL_FAILED,String(e),r),P.logError(n),P.notifyCallbacks(n),n}static handlePlatformNotSupported(e,r){const n=new T(b.PLATFORM_NOT_SUPPORTED,`API "${r}" is not supported on platform "${e}"`,{platformType:e,apiName:r});return P.logError(n),P.notifyCallbacks(n),n}static handleBridgeNotReady(e){const r=new T(b.BRIDGE_NOT_READY,`Bridge is not ready when calling "${e}"`,{apiName:e});return P.logError(r),P.notifyCallbacks(r),r}static handleInvalidParameters(e,r,n,i){const s=new T(b.INVALID_PARAMETERS,`Invalid parameter "${r}" in "${e}": expected ${n}, got ${typeof i}`,{apiName:e,paramName:r,expectedType:n,actualValue:i});return P.logError(s),P.notifyCallbacks(s),s}static safeExecute(e,r={}){try{return e()}catch(n){return P.handleApiError(n,r)}}static safeExecuteAsync(n){return y(this,arguments,function*(e,r={}){try{return yield e()}catch(i){return P.handleApiError(i,r)}})}static logError(e){if(typeof console!="undefined"){const r=`[QSH-SDK Error] ${e.type}: ${e.message}`;P.isDebugMode?console.error(r,{context:e.context,originalError:e.originalError,stack:e.stack,timestamp:e.timestamp}):console.error(r)}}static notifyCallbacks(e){P.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 s=i.value;return i.value=function(...c){return P.safeExecute(()=>s.apply(this,c),p(g({},e),{method:n,target:r.constructor.name}))},i}}};G(P,"isDebugMode",!1),G(P,"errorCallbacks",[]);let u=P;const x={UNINITIALIZED:"uninitialized",INITIALIZING:"initializing",READY:"ready",ERROR:"error"};class Wt{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 y(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 s=this.errorCallbacks.indexOf(n);s>-1&&this.errorCallbacks.splice(s,1)}}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasReadyPromise:!!this.readyPromise,hasInitializationError:!!this.initializationError}}}const Y=new Wt,Be=()=>Y.waitForReady(),$t=()=>Y.isReady(),Ft=()=>Y.getState(),C={ERROR:0,WARN:1,INFO:2,DEBUG:3,TRACE:4},de={[C.ERROR]:"ERROR",[C.WARN]:"WARN",[C.INFO]:"INFO",[C.DEBUG]:"DEBUG",[C.TRACE]:"TRACE"},f=class f{static setLevel(e){e>=C.ERROR&&e<=C.TRACE&&(f.currentLevel=e,f.log(C.INFO,"Logger",`日志级别设置为: ${de[e]}`))}static enableDevMode(){f.setLevel(C.DEBUG),f.log(C.INFO,"Logger","开发模式已启用")}static enableProdMode(){f.setLevel(C.WARN),f.log(C.INFO,"Logger","生产模式已启用")}static enableModule(e){f.enabledModules.add(e),f.log(C.INFO,"Logger",`模块日志已启用: ${e}`)}static disableModule(e){f.enabledModules.delete(e),f.log(C.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 s=new Date().toISOString(),c=de[e],d=r?`[${r}]`:"",h=`${f.prefix} ${d} ${n}`,_={timestamp:s,level:e,levelName:c,module:r,message:n,args:i};if(f.addToHistory(_),typeof f.reporter=="function")try{f.reporter(_)}catch(M){}f.outputToConsole(e,h,...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 C.ERROR:i?console.error(r,...n):console.error(r);break;case C.WARN:i?console.warn(r,...n):console.warn(r);break;case C.INFO:i?console.info(r,...n):console.info(r);break;case C.DEBUG:case C.TRACE:i?console.log(r,...n):console.log(r);break}}static error(e,r,...n){f.log(C.ERROR,e,r,...n)}static warn(e,r,...n){f.log(C.WARN,e,r,...n)}static info(e,r,...n){f.log(C.INFO,e,r,...n)}static debug(e,r,...n){f.log(C.DEBUG,e,r,...n)}static trace(e,r,...n){f.log(C.TRACE,e,r,...n)}static getHistory(e){return e&&e>0?f.logHistory.slice(-e):[...f.logHistory]}static clearHistory(){f.logHistory=[],f.log(C.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",C.ERROR),G(f,"enabledModules",new Set),G(f,"logHistory",[]),G(f,"maxHistorySize",1e3),G(f,"prefix","[QSH-SDK]"),G(f,"reporter",null);let L=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)&&L.enableDevMode()}const w=L.createModuleLogger("Bridge"),E=L.createModuleLogger("Platform"),a=L.createModuleLogger("API"),W=L.createModuleLogger("State"),Ie=/complete|loaded|interactive/;function Bt(t){if(!D())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 kt(t){return ae()||H()?(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 Kt(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 Gt(t){return w.info("开始初始化 JSBridge"),Bt(t)?(w.info("使用离线包环境初始化"),!0):kt(t)?(w.info("使用 APP 环境初始化"),!0):Kt(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 zt(){return Y.waitForReady()}function ke(){return Y.startInitialization(()=>y(null,null,function*(){return new Promise((t,e)=>{const r=()=>{t()},n=i=>{const s=u.handleApiError(i,{context:"bridge initialization"});e(s)};try{Gt(()=>{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 Vt{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 T(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 T(b.INVALID_PARAMETERS,"clientId参数异常",{clientId:e.clientId});if(Object.prototype.hasOwnProperty.call(e,"isProd")&&typeof e.isProd!="boolean")throw new T(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=p(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(),E.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 T(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 y(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 s=yield i.json();if(E.debug("微信配置响应",s),!s.success||s.code!==200)throw new Error(`配置获取失败: ${s.message||"未知错误"}`);const{data:c}=s;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 T(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};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 T(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(s=>{try{s(n)}catch(c){u.handleApiError(c,{context:"WeixinConfigManager.handleConfigError"})}})}autoConfig(){return y(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 y(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 T?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(s){u.handleApiError(s,{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}}}const v=new Vt;let oe=!1,ge=!1,$=null,Ae=!1;function qt(t){return new Promise(e=>{let r=!1,n=null;const i=d=>y(null,null,function*(){if(!r){if(r=!0,n&&clearTimeout(n),oe=!1,ge=d,d)try{yield Ke()}catch(h){E.error("微信配置失败,将使用消息桥作为后备",h)}e()}}),s=()=>i(B()),c=()=>{E.warn("已存在的微信 JS-SDK 脚本加载失败,SDK 将使用消息桥作为后备"),i(!1)};t.addEventListener("load",s,{once:!0}),t.addEventListener("error",c,{once:!0}),setTimeout(()=>{B()&&s()},0),n=setTimeout(()=>{i(B())},3e3)})}function Ne(){return y(this,arguments,function*(t={}){const{force:e=!1,recoverFromError:r=!1}=t;if(yield Ge({force:e}),!B())throw new Error("微信 JS-SDK 未正确加载,无法执行配置");r&&jt()})}function Jt(t=!1){if(typeof window=="undefined")return!1;if(B())return ge=!0,!1;if(ge||D())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",s=!!(window.wx&&window.wx.miniProgram);return r&&(n||i||s)}function jt(){v.getState()==="error"&&(v.reset(),Ae=!1)}function Ke(){return y(this,null,function*(){if(Ae)return v.waitForReady();Ae=!0,E.info("开始自动配置微信JS-SDK");try{yield v.autoConfig(),E.info("微信JS-SDK自动配置完成")}catch(t){E.error("微信JS-SDK自动配置失败",t)}})}function Ge(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?$||(oe=!0,$=qt(r).finally(()=>{$=null}),$):Jt(e)?$||($=new Promise(n=>{oe=!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 y(this,null,function*(){ge=!0,oe=!1,E.info("微信 JS-SDK 已自动加载");try{yield Ke()}catch(c){E.error("微信配置失败,将使用消息桥作为后备",c)}n()})},i.onerror=function(){oe=!1,E.warn("微信 JS-SDK 加载失败,SDK 将使用消息桥作为后备"),n()},(document.getElementsByTagName("head")[0]||document.documentElement).appendChild(i)}catch(i){oe=!1,E.error("注入微信 JS-SDK 失败",i),n()}}).finally(()=>{$=null}),$):Promise.resolve()}function z(){return Ne({force:!0,recoverFromError:!0}).then(()=>v.waitForReady())}function ze(t={}){const e=v.configure(t);return typeof window=="undefined"||Ne({force:!0,recoverFromError:v.getState()==="error"}).then(()=>{if(!v.isReady())return v.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 Z(){return v.isReady()}function Ht(){return v.getState()}function Me(){return v}function Yt(){return y(this,null,function*(){return E.info("手动重试微信配置"),v.reset(),Ae=!1,yield Ne({force:!0}),v.waitForReady()})}class Zt{constructor(){this.plugins=new Map,this.installed=new Set,this.installOrder=[],a.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);a.warn(`插件 ${r} 已注册(版本 ${i.version}),将被覆盖为版本 ${n}`)}return this.plugins.set(r,e),a.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 y(this,null,function*(){return u.safeExecute(()=>y(this,null,function*(){if(!this.plugins.has(e))throw new Error(`插件 ${e} 未注册`);if(this.installed.has(e)){a.debug(`插件 ${e} 已安装,跳过`);return}const n=this.plugins.get(e);if(n.dependencies&&n.dependencies.length>0){a.debug(`安装插件 ${e} 的依赖:`,n.dependencies);for(const i of n.dependencies)yield this.install(i,r)}a.info(`开始安装插件: ${e}@${n.version}`),yield n.install(r),this.installed.add(e),this.installOrder.push(e),a.info(`插件安装成功: ${e}@${n.version}`)}),{context:"PluginManager.install",pluginName:e})})}uninstall(e,r){return y(this,null,function*(){return u.safeExecute(()=>y(this,null,function*(){if(!this.installed.has(e)){a.debug(`插件 ${e} 未安装,跳过卸载`);return}const n=this.plugins.get(e);n.uninstall&&typeof n.uninstall=="function"&&(a.info(`开始卸载插件: ${e}`),yield n.uninstall(r)),this.installed.delete(e);const i=this.installOrder.indexOf(e);i>-1&&this.installOrder.splice(i,1),a.info(`插件已卸载: ${e}`)}),{context:"PluginManager.uninstall",pluginName:e})})}uninstallAll(e){return y(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 y(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 Zt;class Xt{constructor(){this.requestInterceptors=[],this.responseInterceptors=[],a.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,s)=>s.priority-i.priority),a.debug("请求拦截器已注册",{priority:n}),()=>{const i=this.requestInterceptors.findIndex(s=>s.fn===e);i>-1&&(this.requestInterceptors.splice(i,1),a.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,s)=>s.priority-i.priority),a.debug("响应拦截器已注册",{priority:n}),()=>{const i=this.responseInterceptors.findIndex(s=>s.fn===e);i>-1&&(this.responseInterceptors.splice(i,1),a.debug("响应拦截器已移除"))}}runRequest(e){return y(this,null,function*(){let r=g({},e);for(const{fn:n}of this.requestInterceptors){if(r.abort){a.debug("请求被中止",{apiName:r.apiName});break}try{const i=yield n(r);i&&(r=i)}catch(i){a.error("请求拦截器执行失败",i),r.abort=!0,r.error=i;break}}return r})}runResponse(e,r){return y(this,null,function*(){let n=e;for(const{fn:i}of this.responseInterceptors)try{const s=yield i(n,r);s!==void 0&&(n=s)}catch(s){a.error("响应拦截器执行失败",s)}return n})}clear(){this.requestInterceptors=[],this.responseInterceptors=[],a.debug("所有拦截器已清空")}getStats(){return{requestInterceptors:this.requestInterceptors.length,responseInterceptors:this.responseInterceptors.length}}}const X=new Xt,Qt={request:t=>(t.startTime=Date.now(),a.debug(`[API 调用] ${t.apiName}`,{params:t.params}),t),response:(t,e)=>{const r=Date.now()-e.startTime;return a.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 er(t={}){const{maxRetries:e=3,retryDelay:r=1e3,shouldRetry:n=i=>!i.success}=t;return{response:(i,s)=>y(null,null,function*(){return s.retryCount||(s.retryCount=0),n(i)&&s.retryCount<e&&(s.retryCount++,a.warn(`API 调用失败,第 ${s.retryCount} 次重试: ${s.apiName}`),yield new Promise(c=>setTimeout(c,r)),i.shouldRetry=!0,i.retryContext=s),i})}}function tr(t={}){return{request:e=>{const r=t[e.apiName];if(r&&typeof r=="function"){const n=r(e.params);n&&(a.error(`参数验证失败: ${e.apiName}`,n),e.abort=!0,e.validationError=n)}return e}}}class rr{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(),s=n.reduce((d,h)=>((!d[h]||typeof d[h]!="object")&&(d[h]={}),d[h]),this.state),c=s[i];c!==r&&(s[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,s,c)=>{r(i,s,c),n()});return n}notify(e,r,n){const i=this.listeners.get(e);i&&i.forEach(c=>{try{c(r,n,e)}catch(d){W.error("订阅者执行失败",d)}});const s=e.split(".");for(let c=1;c<s.length;c++){const d=s.slice(0,c).join("."),h=this.listeners.get(d);if(h){const _=this.get(d);h.forEach(M=>{try{M(_,void 0,d)}catch(N){W.error("父路径订阅者执行失败",N)}})}}this.wildcardListeners.forEach(c=>{try{c(r,n,e)}catch(d){W.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,p(g({},i),{loading:r,lastCall:r?Date.now():i.lastCall}))}setApiResult(e,r){const n=`api.${e}`,i=this.get(n)||{};this.set(n,p(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:{}},W.debug("状态已重置")}getStats(){return{listeners:this.listeners.size,wildcardListeners:this.wildcardListeners.size,apiStates:Object.keys(this.state.api).length}}}const k=new rr,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"},Se={[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"},nr={"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},Ve={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}},qe={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 Je(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 ir(t){return t.includes("NET_")||t.includes("TIMEOUT")||t===o.NETWORK_ERROR||t===o.NETWORK_TIMEOUT||t===o.API_TIMEOUT}function ar(t){return t.includes("CANCEL")||Je(t)===F.USER_CANCEL}function ce(t){return Se[t]||Se[o.UNKNOWN_ERROR]}class K extends Error{constructor(e,r,n={}){super(r),this.name="StandardError",this.code=e,this.message=r||ce(e),this.platform=n.platform||l.type,this.apiName=n.apiName,this.category=n.category||Je(e),this.retriable=n.retriable!==void 0?n.retriable:ir(e),this.originalError=n.originalError,this.details=n.details||{},this.timestamp=Date.now()}isRetriable(){return this.retriable}isUserAction(){return ar(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 je(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("/")?sr(t,{apiName:r,platform:n}):t&&(t.errMsg||t.message)?or(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 sr(t,e){const{apiName:r,platform:n}=e,i=t.code,s=nr[i]||o.UNKNOWN_ERROR;return a.debug("转换旧版错误码",{legacy:i,new:s}),new K(s,t.message||ce(s),{apiName:r,platform:t.platform||n,originalError:t,details:g({legacyCode:i,legacyVersion:t.version},t.details)})}function or(t,e){const{apiName:r,platform:n}=e,i=(t.errMsg||t.message||"").toLowerCase();if(r&&qe[r]){const d=qe[r];for(const[h,_]of Object.entries(d))if(i.includes(h.toLowerCase()))return new K(_,ce(_),{apiName:r,platform:n,originalError:t})}const s=Ve[n]||Ve.uniapp;for(const{pattern:d,code:h}of s.patterns)if(d.test(i))return new K(h,ce(h),{apiName:r,platform:n,originalError:t});const c=s.default||o.UNKNOWN_ERROR;return new K(c,t.errMsg||t.message||ce(c),{apiName:r,platform:n,originalError:t})}const He={response:(t,e)=>{if(!t.success&&t.error){const r=je(t.error,{apiName:e.apiName,platform:l.type});t.error=r.toJSON(),t.errorCode=r.code,t.errorCategory=r.category,t.retriable=r.isRetriable(),a.debug("错误已标准化",{api:e.apiName,code:r.code,category:r.category})}return t}};function cr(t,e={}){return new K(t,ce(t),e)}function ur(t){return t instanceof K}function lr(t,e,r){return e?Promise.race([t(),new Promise((n,i)=>setTimeout(()=>i(new Error(`Init task timeout: ${r}`)),e))]):t()}function fr(){return y(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 lr(()=>Promise.resolve().then(()=>i()),r.timeoutMs,n),typeof r.onSuccess=="function"&&r.onSuccess()}catch(s){if(typeof r.onError=="function"&&r.onError(s),typeof e.onError=="function")e.onError(s,r);else throw s}}})}class Ye{constructor(e){this.name=e}processNavigationOptions(e={}){const{url:r,delta:n=1}=e,i=r&&encodeURI(r),s=parseInt(n)||1;return p(g({},e),{url:i,delta:s})}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 me=[];function dr(){if(me.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;me.push(r)}return me}function gr(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:me}};window.__uniapp_x_postMessage?window.__uniapp_x_postMessageToService(n):window.__uniapp_x_.postMessageToService(JSON.stringify(n))}function hr(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:me}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(n):window.__dcloud_weex_.postMessageToService(JSON.stringify(n))}function mr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e},n=dr();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),s=JSON.stringify(n);plus.webview.getLaunchWebview().evalJS(`UniPlusBridge.subscribeHandler("WEB_INVOKE_APPSERVICE",${i},${s});`)}}function pr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""},"*")}function wr(t){return!!(t&&typeof t=="object"&&t.type==="qsh_api_call"&&typeof t.api=="string"&&typeof t.callbackId=="string")}function Er(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};if(t==="postMessage"&&wr(e))return window.__offline_bridge_postMessage(e);window.__offline_bridge_postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""})}function pe(t,e){ie()?gr(t,e):j()?hr(t,e):D()?Er(t,e):ne()?mr(t,e):pr(t,e)}class Ze extends Ye{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 d=e==="navigateBack"?{delta:i}:{url:n};return c.call(window.wx.miniProgram,d)}}E.debug(`使用消息桥接执行: ${e}`),pe(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});pe("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 Ze;var Xe=Object.freeze({__proto__:null,WeixinPlatform:Ze,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 Qe extends Ye{constructor(){super("app")}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;pe(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;pe("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;ie()?(r.uvue=!0,n=!0):j()?(r.nvue=!0,n=!0):ne()?(r.plus=!0,n=!0):D()&&(r.offline=!0,n=!0),n?r.app=!0:r.h5=!0,e(r)},{platform:this.name,method:"performGetEnv"})}}const ee=new Qe;var et=Object.freeze({__proto__:null,AppPlatform:Qe,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 m()?Xe:et}function yr(t){return we().navigateTo(t)}function Ir(t){return we().navigateBack(t)}function Ar(t){return we().switchTab(t)}function Cr(t){return we().reLaunch(t)}function _r(t){return we().redirectTo(t)}function tt(){return m()?Xe:et}function Or(t={}){return tt().postMessage(t)}function Pr(t){return tt().getEnv(t)}function Rr(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function Nr(){return"qsh_callback_"+Date.now()+"_"+Math.random().toString(36).substring(2,9)}class Mr{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 y(this,arguments,function*(e,r={},n={}){return u.safeExecute(()=>y(this,null,function*(){var _;if(typeof window!="undefined"&&window===window.parent&&!window.plus&&!window.__uniapp_x_postMessage&&!window.__uniapp_x_&&!window.__dcloud_weex_postMessage&&!window.__dcloud_weex_&&!D()){const M=new T(b.PLATFORM_NOT_SUPPORTED,"当前不在宿主 WebView 容器中,无法发送消息");n&&typeof n.fail=="function"&&n.fail({errMsg:M.message,code:"NOT_IN_CONTAINER"}),n&&typeof n.complete=="function"&&n.complete({success:!1,error:{errMsg:M.message}});return}const c={apiName:e,params:r,callbacks:n,timestamp:Date.now(),abort:!1,metadata:{}};k.setApiLoading(e,!0);const d=yield X.runRequest(c);if(d.abort){w.warn("API 调用被拦截器中止",{api:e}),k.setApiLoading(e,!1),n.fail&&n.fail({errMsg:((_=d.error)==null?void 0:_.message)||"API 调用被中止",code:"INTERCEPTED"}),n.complete&&n.complete({success:!1});return}const h=Nr();if(n.success||n.fail||n.complete){if(this.callbacks.set(h,p(g({},n),{context:d})),window.qshWebviewCallbacks[h]=fe=>{this.handleCallback(h,fe)},r.isPersistent&&(this.persistentCallbacksByApi.has(e)||this.persistentCallbacksByApi.set(e,new Set),this.persistentCallbacksByApi.get(e).add(h)),r.isPersistent||r.disableTimeout)w.info(`API ${e} 禁用超时清理,将等待回调返回后清理`,{callbackId:h,isPersistent:r.isPersistent,disableTimeout:r.disableTimeout});else{const fe=setTimeout(()=>{w.warn("API 调用超时,自动清理回调",{api:e,callbackId:h}),n.fail&&n.fail({errMsg:`API ${e} 调用超时`,code:"TIMEOUT"}),this.cleanupCallback(h)},r.timeout||this.defaultTimeout);this.timeouts.set(h,fe)}const N={type:"qsh_api_call",api:e,params:d.params,callbackId:h,timestamp:Date.now()};w.info("发送 API 调用消息",{api:e,callbackId:h,hasSuccess:!!n.success,hasFail:!!n.fail}),console.log("message:",JSON.stringify(Rr(N),null,2)),pe("postMessage",N)}}),{context:"WebViewBridge.callApi",api:e})})}handleCallback(e,r){return y(this,null,function*(){return u.safeExecute(()=>y(this,null,function*(){var M,N;const n=this.callbacks.get(e);if(!n){w.warn("未找到回调函数",{callbackId:e});return}const{success:i,fail:s,complete:c,context:d}=n;w.debug("处理回调",{callbackId:e,result:r});const h=yield X.runResponse(r,d);d&&k.setApiResult(d.apiName,h),h.success&&i?i(h.data):!h.success&&s&&s(h.error||{errMsg:"操作失败"}),c&&c(h),((N=(M=n.context)==null?void 0:M.params)==null?void 0:N.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,s)=>{i.has(e)&&(i.delete(e),i.size===0&&n.push(s))}),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 rt=new Mr,R=(t,e,r)=>rt.callApi(t,e,r),ue=t=>rt.cleanupPersistentCallbacksByApi(t);function nt(){return se(!0)}function Sr(t){return t==="offline"}function Tr(t={}){return u.safeExecute(()=>{a.debug("Call getCode through offline webview bridge",{clientId:t.clientId}),R("getCode",{clientId:t.clientId},{success:e=>{var r;a.info("Get code success"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("Get code failed",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getCodeInHost",platform:nt().type})}function vr(t={}){return u.safeExecute(()=>{var n,i;const e=nt(),r=String((t==null?void 0:t.clientId)||"").trim();if(!r){const s={errMsg:"clientId is required",code:"APP_KEY_MISSING"};a.error("Get code missing clientId"),(n=t.fail)==null||n.call(t,s);return}if(!Sr(e.type)){const s={errMsg:`Current environment (${e.type}) does not support getCode`,code:"PLATFORM_NOT_SUPPORTED"};a.error("Platform does not support getCode",{platform:e.type}),(i=t.fail)==null||i.call(t,s);return}Tr(p(g({},t),{clientId:r}))},{context:"getCode",options:t})}function it(){return se(!0)}const at=["release","trial","develop"];function Lr(t={}){const e=String((t==null?void 0:t.appid)||"").trim(),r=(t==null?void 0:t.path)==null?"":t.path,n=t==null?void 0:t.env,i=n==null||n===""?void 0:String(n).trim();if(!e)throw{errMsg:"appid is required",code:"PARAM_MISSING"};if(typeof r!="string")throw{errMsg:"path must be a string",code:"PARAM_TYPE_ERROR"};if(i!==void 0&&!at.includes(i))throw{errMsg:`env must be one of ${at.join("/")}`,code:"PARAM_INVALID"};return p(g({},t),{appid:e,path:r.trim(),env:i})}function br(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram&&typeof window.wx.miniProgram.postMessage=="function"&&typeof window.wx.miniProgram.navigateBack=="function"}function xr(t={}){return u.safeExecute(()=>{var r;if(!br()){const n={errMsg:"wx.miniProgram.postMessage or wx.miniProgram.navigateBack is not available",code:"PLATFORM_NOT_SUPPORTED"};a.error("Weixin web-view relay APIs are not available"),(r=t.fail)==null||r.call(t,n);return}const e={type:"qsh_api_call",api:"navigateToMiniProgram",params:{appid:t.appid,path:t.path,env:t.env},timestamp:Date.now()};return a.debug("Relay navigateToMiniProgram through wx.miniProgram.postMessage",{appid:t.appid,path:t.path,env:t.env}),new Promise((n,i)=>{var s;try{window.wx.miniProgram.postMessage({data:e})}catch(c){a.error("Post navigateToMiniProgram message failed",c),(s=t.fail)==null||s.call(t,c),i(c);return}window.wx.miniProgram.navigateBack({delta:1,success:c=>{var h;const d=p(g({},c),{errMsg:(c==null?void 0:c.errMsg)||"navigateToMiniProgram:queued"});a.info("Navigate to mini program request queued in weixin web-view",{appid:t.appid,path:t.path,env:t.env}),(h=t.success)==null||h.call(t,d),n(d)},fail:c=>{var d;a.error("Navigate back after posting mini program message failed",c),(d=t.fail)==null||d.call(t,c),i(c)},complete:t.complete})})},{context:"navigateToMiniProgramInWeixin",platform:"weixin"})}function Dr(t={}){return u.safeExecute(()=>(a.debug("Call navigateToMiniProgram through webview bridge",{appid:t.appid,path:t.path,env:t.env}),new Promise((e,r)=>{R("navigateToMiniProgram",{appid:t.appid,path:t.path,env:t.env},{success:n=>{var i;a.info("Navigate to mini program success"),(i=t.success)==null||i.call(t,n),e(n)},fail:n=>{var i;a.error("Navigate to mini program failed",n),(i=t.fail)==null||i.call(t,n),r(n)},complete:t.complete})})),{context:"navigateToMiniProgramInHost",platform:it().type})}function Ur(t={}){return u.safeExecute(()=>{var n;const e=it();let r;try{r=Lr(t)}catch(i){a.error("Navigate to mini program params validation failed",i),(n=t.fail)==null||n.call(t,i);return}return a.info("Start navigateToMiniProgram",{platform:e.type,appid:r.appid,path:r.path,env:r.env}),e.isWeixinMiniProgram?xr(r):Dr(r)},{context:"navigateToMiniProgram",options:t})}const Ce={ALBUM:"album",CAMERA:"camera"},_e={ORIGINAL:"original",COMPRESSED:"compressed"},Wr={count:9,sizeType:[_e.ORIGINAL,_e.COMPRESSED],sourceType:[Ce.ALBUM,Ce.CAMERA]};function $r(t={}){const e=g(g({},Wr),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=[_e.COMPRESSED]),e.sourceType.length===0&&(e.sourceType=[Ce.ALBUM]),e}function st(){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(!Z()){a.info("等待微信配置完成"),z().then(()=>ot(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.debug("调用微信图片选择",t),window.wx.chooseImage({count:t.count,sizeType:t.sizeType,sourceType:t.sourceType,success:r=>{var n,i;a.info("微信图片选择成功",{count:((n=r.localIds)==null?void 0:n.length)||0}),(i=t.success)==null||i.call(t,r)},fail:r=>{var n;a.error("微信图片选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"chooseImageInWeixin",platform:"weixin"})}function Fr(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用图片选择",t),R("chooseImage",p(g({},t),{disableTimeout:!0}),{success:e=>{var r,n;a.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;a.error("UniApp 图片选择失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"chooseImageInUniApp",platform:"uniapp"})}function Br(t={}){return u.safeExecute(()=>{var r;if(!st()){const n={errMsg:`当前环境 (${l.type}) 不支持图片选择功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持图片选择",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=$r(t);a.info("开始选择图片",{platform:l.type,count:e.count,sizeType:e.sizeType,sourceType:e.sourceType}),m()?ot(e):Fr(e)},{context:"chooseImage",options:t})}function kr(){return{supported:st(),environment:l.type,implementation:m()?"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=g(g({},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(!Z()){a.info("等待微信配置完成"),z().then(()=>ut(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.debug("调用微信扫码",t),window.wx.scanQRCode({needResult:1,scanType:t.scanType,success:r=>{var i;a.info("微信扫码成功",{result:r.resultStr});const n={result:r.resultStr,scanType:zr(r.resultStr),charSet:"utf-8",errMsg:"scanCode:ok"};(i=t.success)==null||i.call(t,n)},fail:r=>{var n;a.error("微信扫码失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"scanCodeInWeixin",platform:"weixin"})}function zr(t){return t?t.length>50||/[^\d]/.test(t)?te.QR_CODE:te.BAR_CODE:"unknown"}function Vr(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用扫码",t),R("scanCode",p(g({},t),{disableTimeout:!0}),{success:e=>{var r;a.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;a.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"};a.error("平台不支持扫码",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Gr(t);a.info("开始扫码",{platform:l.type,onlyFromCamera:e.onlyFromCamera,scanType:e.scanType}),m()?ut(e):Vr(e)},{context:"scanCode",options:t})}function Jr(){return{supported:ct(),environment:l.type,implementation:m()?"weixin":"webview",features:{onlyFromCamera:!0,scanTypeSelection:!0,multipleTypes:!0,asyncSupport:!0}}}const le={WGS84:"wgs84",GCJ02:"gcj02",BD09:"bd09"},jr={type:le.WGS84,altitude:!1},Hr={scale:18};function Yr(t={}){const e=g(g({},jr),t);return Object.values(le).includes(e.type)||(e.type=le.WGS84),e.altitude=!!e.altitude,e}function Zr(t={}){const e=g({},t);return Object.values(le).includes(e.type)||(e.type=le.WGS84),e.needFullAccuracy=!!e.needFullAccuracy,e}function Xr(t={}){const e=g(g({},Hr),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)?(a.warn("scale 参数无效,使用默认值 18",{scale:e.scale}),e.scale=18):e.scale=Math.max(1,Math.min(28,Math.floor(r)))}return e}function Te(){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(!Z()){a.info("等待微信配置完成"),z().then(()=>lt(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.debug("调用微信定位",t),window.wx.getLocation({type:t.type,success:r=>{var n;a.info("微信定位成功",{latitude:r.latitude,longitude:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;a.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(!Z()){a.info("等待微信配置完成"),z().then(()=>ft(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.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;a.info("微信查看位置成功"),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;a.error("微信查看位置失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"openLocationInWeixin",platform:"weixin"})}function Qr(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用获取位置",t),R("getLocation",t,{success:e=>{var r;a.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;a.error("UniApp 获取位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getLocationInUniApp",platform:"uniapp"})}function en(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用查看位置",t),R("openLocation",t,{success:e=>{var r;a.info("UniApp 查看位置成功"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("UniApp 查看位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"openLocationInUniApp",platform:"uniapp"})}function tn(t={}){return u.safeExecute(()=>{var r;if(!Te()){const n={errMsg:`当前环境 (${l.type}) 不支持定位功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持定位",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Yr(t);a.info("开始获取位置",{platform:l.type,type:e.type,altitude:e.altitude}),m()?lt(e):Qr(e)},{context:"getLocation",options:t})}function rn(t={}){return u.safeExecute(()=>{var r,n,i;if(!Te()){const s={errMsg:`当前环境 (${l.type}) 不支持查看位置功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持查看位置",{platform:l.type}),(r=t.fail)==null||r.call(t,s);return}let e;try{e=Xr(t)}catch(s){a.error("参数验证失败",s),(n=t.fail)==null||n.call(t,s),(i=t.complete)==null||i.call(t);return}a.info("开始查看位置",{platform:l.type,latitude:e.latitude,longitude:e.longitude,name:e.name}),m()?ft(e):en(e)},{context:"openLocation",options:t})}function nn(){const t=m();return{supported:Te(),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}a.warn("监听回调不是函数,已跳过",{type:typeof n})})}function an(t={}){return u.safeExecute(()=>{var r,n;if(m()){const i={errMsg:`当前环境 (${l.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};a.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);a.info("正在开启定位监听"),R("startLocationUpdate",{type:e.type,needFullAccuracy:e.needFullAccuracy},{success:i=>{var s;a.info("定位监听已启动"),(s=t.success)==null||s.call(t,i)},fail:i=>{var s;return(s=t.fail)==null?void 0:s.call(t,i)},complete:t.complete})},{context:"startLocationUpdate"})}function sn(t={}){return u.safeExecute(()=>{var e,r;if(m()){const n={errMsg:`当前环境 (${l.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};a.error("当前环境不支持此接口",{platform:l.type}),(e=t.fail)==null||e.call(t,n),(r=t.complete)==null||r.call(t,n);return}a.info("正在停止定位监听"),R("stopLocationUpdate",t,{success:n=>{var i;a.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 on(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(typeof t!="function")throw a.error("onLocationChange 回调不是函数",{type:typeof t}),{errMsg:"onLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};const e=q.size>0;q.add(t),e||(a.debug("注册实时位置变化监听器"),R("onLocationChange",{isPersistent:!0},{success:r=>{a.debug("收到实时位置推送",r),dt(q,r,"onLocationChange")},fail:r=>{a.warn("位置变化监听出错,请通过 onLocationChangeError 监听错误",r),q.delete(t),q.size===0&&ue("onLocationChange")}}))},{context:"onLocationChange"})}function cn(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(t&&typeof t!="function")throw a.error("offLocationChange 回调不是函数",{type:typeof t}),{errMsg:"offLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};t?q.delete(t):q.clear(),!(q.size>0)&&(a.info("移除位置变化监听器"),R("offLocationChange",{},{success:()=>{a.info("位置变化监听已移除"),ue("onLocationChange")},fail:e=>{a.error("移除位置变化监听失败",e),ue("onLocationChange")}}))},{context:"offLocationChange"})}function un(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(typeof t!="function")throw a.error("onLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"onLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};const e=J.size>0;J.add(t),e||(a.debug("注册位置更新错误监听器"),R("onLocationChangeError",{isPersistent:!0},{success:r=>{a.warn("持续定位发生异常",r),dt(J,r,"onLocationChangeError")},fail:r=>{a.warn("位置更新错误监听注册失败",r),J.delete(t),J.size===0&&ue("onLocationChangeError")}}))},{context:"onLocationChangeError"})}function ln(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(t&&typeof t!="function")throw a.error("offLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"offLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};t?J.delete(t):J.clear(),!(J.size>0)&&(a.info("移除定位错误监听器"),R("offLocationChangeError",{},{success:()=>{a.info("定位错误监听已移除"),ue("onLocationChangeError")},fail:e=>{a.error("移除定位错误监听失败",e),ue("onLocationChangeError")}}))},{context:"offLocationChangeError"})}const fn={latitude:null,longitude:null};function dn(t={}){const e=g(g({},fn),t);return e.latitude!==null&&e.latitude!==void 0&&(typeof e.latitude!="number"?(a.warn("latitude 参数类型错误,已忽略",{latitude:e.latitude}),e.latitude=null):(e.latitude<-90||e.latitude>90)&&(a.warn("latitude 超出范围,已忽略",{latitude:e.latitude}),e.latitude=null)),e.longitude!==null&&e.longitude!==void 0&&(typeof e.longitude!="number"?(a.warn("longitude 参数类型错误,已忽略",{longitude:e.longitude}),e.longitude=null):(e.longitude<-180||e.longitude>180)&&(a.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(!Z()){a.info("等待微信配置完成"),z().then(()=>ht(t)).catch(i=>{var s;a.error("微信配置失败",i),(s=t.fail)==null||s.call(t,{errMsg:`微信配置失败: ${i.message}`})});return}a.debug("调用微信位置选择",t);const e={success:i=>{var c;a.info("微信位置选择成功",{name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude});const s={name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude,errMsg:"chooseLocation:ok"};(c=t.success)==null||c.call(t,s)},fail:i=>{var s;a.error("微信位置选择失败",i),(s=t.fail)==null||s.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(p(g({},r),{success:e.success,fail:e.fail,complete:e.complete}))},{context:"chooseLocationInWeixin",platform:"weixin"})}function gn(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用位置选择",t);const e={disableTimeout:!0,success:r=>{var n;a.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;a.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 hn(t={}){return u.safeExecute(()=>{var r;if(!gt()){const n={errMsg:`当前环境 (${l.type}) 不支持位置选择功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持位置选择",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=dn(t);a.info("开始选择位置",{platform:l.type,latitude:e.latitude,longitude:e.longitude}),m()?ht(e):gn(e)},{context:"chooseLocation",options:t})}function mn(){return{supported:gt(),environment:l.type,implementation:m()?"weixin":"webview",features:{chooseLocation:!0,centerPoint:!0,asyncSupport:!0}}}function pn(t){return t==="timeline"||Number(t)===1?1:0}function wn(t={}){if(!t||typeof t!="object")throw{errMsg:"shareDirected 参数必须是对象",code:"PARAM_TYPE_ERROR"};const e=String(t.kind||"").trim(),r=t.payload||{},n=pn(t.scene);if(!["web","image","text"].includes(e))throw{errMsg:'shareDirected: kind 仅支持 "web"|"image"|"text"',code:"PARAM_INVALID"};if(e==="web"){if(!r.path&&!r.href)throw{errMsg:"shareDirected(web): payload.path 或 payload.href 必填",code:"PARAM_MISSING"};if(!r.title||!r.summary||!r.imageUrl)throw{errMsg:"shareDirected(web): title/summary/imageUrl 必填",code:"PARAM_MISSING"}}if(e==="image"&&!r.imageUrl)throw{errMsg:"shareDirected(image): payload.imageUrl 必填",code:"PARAM_MISSING"};if(e==="text"&&!r.text&&!r.summary)throw{errMsg:"shareDirected(text): payload.text 或 payload.summary 必填",code:"PARAM_MISSING"};return{kind:e,scene:n,payload:r,success:t.success,fail:t.fail,complete:t.complete}}function En(t){return t.isWeixinMiniProgram?"已同步分享内容,请点击右上角“···”选择发送给朋友或分享到朋友圈。":"正在拉起微信分享面板,请选择聊天框或朋友圈。"}function mt(t={}){return u.safeExecute(()=>{var i,s,c;let e;try{e=wn(t)}catch(d){return(i=t.fail)==null||i.call(t,d),Promise.reject(d)}const r=se(!0),n=En(r);if(r.type==="h5"&&!r.isUniAppWebView&&!r.isOfflineWebview&&!r.isWeixinMiniProgram){const d={errMsg:"当前页面不在宿主 WebView 中,无法分享。请在 unified-platform-app 内打开该 H5 再重试。",code:"NOT_IN_CONTAINER"};return(s=e.fail)==null||s.call(e,d),(c=e.complete)==null||c.call(e,d),Promise.reject(d)}return new Promise((d,h)=>{R("shareDirected",{kind:e.kind,scene:e.scene,payload:e.payload},{success:_=>{var N,fe;const M=p(g({},_),{hint:n});(N=e.success)==null||N.call(e,M),(fe=e.complete)==null||fe.call(e,M),d(M)},fail:_=>{var M,N;(M=e.fail)==null||M.call(e,_),(N=e.complete)==null||N.call(e,_),h(_)}})})},{context:"shareDirected",options:t})}function yn(t={}){return new Promise((e,r)=>{mt(p(g({},t),{success:e,fail:r}))})}const In={OFF:"off",ON:"on",UNAVAILABLE:"unavailable",UNAUTHORIZED:"unauthorized"},An={allowDuplicatesKey:!1,services:[]};function Oe(t={}){return g(g({},An),t)}function Ee(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function Cn(t){return u.safeExecute(()=>y(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}Z()||(a.info("等待微信配置完成"),yield z()),wx.openBluetoothAdapter({success:()=>{a.info("微信蓝牙适配器已打开"),pt(t)},fail:r=>{var n;a.error("蓝牙适配器打开失败",r),(n=t.fail)==null||n.call(t,r)}})}),{context:"openBluetoothAdapterInWeixin"})}function _n(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用蓝牙功能",t),R("bluetooth",t,{success:e=>{var r;a.info("UniApp 蓝牙调用成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("UniApp 蓝牙调用失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"bluetoothInUniApp"})}function On(t){return u.safeExecute(()=>{var e;a.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),a.info("UniApp 蓝牙设备开启搜索成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 设备开启搜索失败:",r),a.error("UniApp 蓝牙设备开启搜索失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"startBluetoothDevicesDiscoveryInUniApp"})}const Pe=new Set;function Pn(t,e={}){return u.safeExecute(()=>{var r;return Pe.add(t),Pe.size===1&&R("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 Rn(t){return u.safeExecute(()=>{var e;a.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),a.info("UniApp 蓝牙连接成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 蓝牙连接失败:",r),a.error("UniApp 蓝牙连接失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"createBLEConnectionInUniApp"})}function Nn(t={}){return u.safeExecute(()=>{var r;if(!Ee()){const n={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持蓝牙",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Oe(t);a.info("开始蓝牙操作",{platform:l.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),m()?Cn(e):_n(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"};a.error("平台不支持蓝牙",{platform:l.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=Oe(t);a.info("开始搜索蓝牙设备",{platform:l.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),m()?startBluetoothDevicesDiscoveryInWeixin(e):On(e)},{context:"startBluetoothDevicesDiscovery",options:t})}function pt(t,e={}){return u.safeExecute(()=>{var n,i;if(!Ee()){const s={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持蓝牙",{platform:l.type}),(n=e.fail)==null||n.call(e,s),(i=e.complete)==null||i.call(e,s);return}const r=Oe(e);a.info("注册蓝牙设备发现监听",{platform:l.type}),m()?onBluetoothDeviceFoundInWeixin(r):Pn(t,r)},{context:"onBluetoothDeviceFound",options:e})}function Sn(t={}){return u.safeExecute(()=>{var s,c,d,h;if(!Ee()){const _={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持蓝牙连接",{platform:l.type}),(s=t.fail)==null||s.call(t,_),(c=t.complete)==null||c.call(t,_);return}const e=Oe(t),{name:r,deviceId:n,autoConnect:i=!1}=e;if(!n){const _={errMsg:"缺少 deviceId 参数",code:"INVALID_PARAMS"};(d=t.fail)==null||d.call(t,_),(h=t.complete)==null||h.call(t,_);return}a.info("创建蓝牙连接",{deviceId:n,autoConnect:i,platform:l.type}),m()?uni.createBLEConnection({deviceId:n,autoConnect:i,success:t.success,fail:t.fail,complete:t.complete}):Rn(e)},{context:"createBLEConnection",options:t})}function Tn(){return{supported:Ee(),environment:l.type,implementation:m()?"weixin":"webview",features:{discovery:!0,connect:!0,readWrite:!0,notify:!0,asyncSupport:!0}}}const vn={};function Ln(t={}){return g(g({},vn),t)}function wt(){return["webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function bn(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用打印PDF",t),R("printPdf",p(g({},t),{isPersistent:!0}),{success:e=>{var r;a.info("UniApp 打印PDF成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("UniApp 打印PDF失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"printPdfInUniApp",platform:"uniapp"})}function xn(t={}){return u.safeExecute(()=>{var r;if(!wt()){const n={errMsg:`当前环境 (${l.type}) 不支持打印PDF功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持打印PDF",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Ln(t);a.info("开始打印PDF",{platform:l.type}),bn(e)},{context:"printPdf",options:t})}function Dn(){return{supported:wt(),environment:l.type,implementation:"uniapp",features:{asyncSupport:!0}}}const ve="/pages/face/index";function Un(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 Et(){return m()}function Wn(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram&&typeof window.wx.miniProgram.navigateTo=="function"}function $n(t){const e=p(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?`${ve}?${r}`:ve}function Fn(t){return u.safeExecute(()=>{if(!Wn()){a.error("微信小程序导航API不可用");return}const e=$n(t);a.debug("跳转宿主人脸识别页面",{name:t.name,targetUrl:e}),window.wx.miniProgram.navigateTo({url:e,success:()=>{a.info("已跳转到宿主人脸识别页面",{targetUrl:e})},fail:r=>{a.error("跳转宿主人脸识别页面失败",r)}})},{context:"faceVerifyInWeixin",platform:"weixin"})}function Bn(t={}){return u.safeExecute(()=>{if(!Et()){a.error("平台不支持人脸识别",{platform:l.type});return}let e;try{e=Un(t)}catch(r){a.error("人脸识别参数校验失败",r);return}a.info("开始人脸识别",{platform:l.type,name:e.name,pagePath:ve}),Fn(e)},{context:"faceVerify",options:t})}function kn(){return{supported:Et(),environment:l.type,implementation:"weixin",features:{asyncSupport:!0,hostPageNavigation:!0}}}const yt=se();function Kn(){if(typeof window=="undefined"||!se(!0).isWeixinMiniProgram)return!1;const e=Me().getRuntimeConfig();return typeof e.clientId=="string"&&e.clientId.length>0}function Gn(){return y(this,null,function*(){yield zt(),Kn()&&(yield z())})}X.useResponse(He.response,{priority:1e3});let It=!1;function At(){if(It)return;It=!0,fr([{name:"load-weixin-sdk",run:Ge,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(At,0):document.addEventListener("DOMContentLoaded",At));function I(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"),s=r&&typeof r=="object"?r:{},c=()=>i?t(s,...n):new Promise((h,_)=>{const M=p(g({},s),{success:N=>{typeof s.success=="function"&&s.success(N),h(N)},fail:N=>{typeof s.fail=="function"&&s.fail(N),_(N)},complete:s.complete});t(M,...n)});return(typeof window=="undefined"?Promise.resolve():Be()).then(()=>c()).catch(h=>{throw console.error(`[QSH-SDK] ${e||"API"} call failed:`,h),h})}}function Re(t){return typeof t=="function"?{success:t}:t&&typeof t=="object"?t:{}}const Ct=I(yr),_t=I(Ir),Ot=I(Ar),Pt=I(Cr),Rt=I(_r),Nt=I(Or);function Mt(t){const e=()=>Pr(t);return(typeof window=="undefined"?Promise.resolve():Be()).then(()=>e())}const Le=I(vr,{apiName:"getCode"});function zn(t={}){return new Promise((e,r)=>{Le(p(g({},t),{success:e,fail:r}))})}const be=I(Ur,{apiName:"navigateToMiniProgram"});function Vn(t={}){return new Promise((e,r)=>{be(p(g({},t),{success:e,fail:r}))})}const xe=I(Br);function qn(t={}){return new Promise((e,r)=>{xe(p(g({},t),{success:e,fail:r}))})}const St=I(xn);function Jn(t={}){return new Promise((e,r)=>{St(p(g({},t),{success:e,fail:r}))})}const De=I(qr),jn=I(Bn);function Hn(t={}){return new Promise((e,r)=>{De(p(g({},t),{success:e,fail:r}))})}const Yn=I(mt,{apiName:"shareDirected"}),Zn=I(yn,{apiName:"shareDirectedAsync"}),Ue=I(tn);function Xn(t={}){return new Promise((e,r)=>{Ue(p(g({},t),{success:e,fail:r}))})}const We=I(rn);function Qn(t={}){return new Promise((e,r)=>{We(p(g({},t),{success:e,fail:r}))})}const $e=I(hn);function ei(t={}){return new Promise((e,r)=>{$e(p(g({},t),{success:e,fail:r}))})}const Tt=I(Nn);function ti(t={}){return new Promise((e,r)=>{Tt(p(g({},t),{success:e,fail:r}))})}const vt=I(Mn);function ri(t={}){return new Promise((e,r)=>{vt(p(g({},t),{success:e,fail:r}))})}const Lt=I(pt);function ni(t={}){return new Promise((e,r)=>{Lt(p(g({},t),{success:e,fail:r}))})}const bt=I(Sn);function ii(t={}){return new Promise((e,r)=>{bt(p(g({},t),{success:e,fail:r}))})}const re={navigateTo:Ct,navigateBack:_t,switchTab:Ot,reLaunch:Pt,redirectTo:Rt,postMessage:Nt,getEnv:Mt,getCode:Le,getCodeAsync:zn,navigateToMiniProgram:be,navigateToMiniProgramAsync:Vn,chooseImage:xe,chooseImageAsync:qn,scanCode:De,scanCodeAsync:Hn,getLocation:Ue,getLocationAsync:Xn,openLocation:We,openLocationAsync:Qn,chooseLocation:$e,chooseLocationAsync:ei,onLocationChange:t=>I((e={})=>on(e.success),{apiName:"onLocationChange"})(Re(t)),offLocationChange:t=>I((e={})=>cn(e.success),{apiName:"offLocationChange"})(Re(t)),onLocationChangeError:t=>I((e={})=>un(e.success),{apiName:"onLocationChangeError"})(Re(t)),offLocationChangeError:t=>I((e={})=>ln(e.success),{apiName:"offLocationChangeError"})(Re(t)),startLocationUpdate:I(an,{apiName:"startLocationUpdate"}),stopLocationUpdate:I(sn,{apiName:"stopLocationUpdate"}),environment:yt,ready:Gn,init:ke,isReady:$t,getState:Ft,config:ze,weixin:{config:ze,waitForConfig:z,isConfigReady:Z,getConfigState:Ht,retryConfig:Yt},webView:null,ImageSourceTypes:Ce,ImageSizeTypes:_e,getImageCapabilities:kr,ScanTypes:te,getScanCapabilities:Jr,CoordinateTypes:le,getLocationCapabilities:nn,getChooseLocationCapabilities:mn,openBluetoothAdapter:Tt,openBluetoothAdapterAsync:ti,startBluetoothDevicesDiscovery:vt,startBluetoothDevicesDiscoveryAsync:ri,onBluetoothDeviceFound:Lt,onBluetoothDeviceFoundAsync:ni,createBLEConnection:bt,createBLEConnectionAsync:ii,BluetoothStates:In,shareDirected:Yn,shareDirectedAsync:Zn,getBluetoothCapabilities:Tn,printPdf:St,printPdfAsync:Jn,getPrintCapabilities:Dn,faceVerify:jn,getFaceCapabilities:kn,plugins:{manager:he,register:t=>he.register(t),install:t=>he.install(t,re),list:()=>he.getPluginList()},interceptors:{chain:X,useRequest:(t,e)=>X.useRequest(t,e),useResponse:(t,e)=>X.useResponse(t,e),builtin:{logging:Qt,performance:V,createRetry:er,createValidation:tr,errorNormalizer:He}},metrics:{getPerformanceReport:()=>V.getReport(),clearPerformanceMetrics:()=>V.clearMetrics()},errors:{codes:o,messages:Se,categories:F,normalize:je,create:cr,isStandard:ur},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:L,setLogReporter:t=>L.setReporter(t),errorHandler:u,stateManager:Y,enableDevMode:()=>L.enableDevMode(),getLogs:t=>L.getHistory(t),getStats:()=>({logger:L.getStats(),state:Y.getStats(),weixinConfig:Me().getStats(),plugins:he.getStats(),interceptors:X.getStats(),store:k.getStats()}),getWeixinConfigManager:Me,exportDebugInfo:()=>L.exportToJSON()}};yt.isWeixinMiniProgram?re.webView=window.wx&&window.wx.miniProgram:re.webView={navigateTo:Ct,navigateBack:_t,switchTab:Ot,reLaunch:Pt,redirectTo:Rt,postMessage:Nt,getEnv:Mt,getCode:Le,navigateToMiniProgram:be,chooseImage:xe,scanCode:De,getLocation:Ue,openLocation:We,chooseLocation:$e};const xt=typeof window.uni!="undefined"?window.uni:{};return Object.keys(xt).forEach(t=>{re.hasOwnProperty(t)||(re[t]=xt[t])}),typeof window!="undefined"&&(window.qsh=re),re});
1
+ (function(O,_){typeof exports=="object"&&typeof module!="undefined"?module.exports=_():typeof define=="function"&&define.amd?define(_):(O=typeof globalThis!="undefined"?globalThis:O||self,O.qsh=_())})(this,function(){"use strict";var fi=Object.defineProperty,di=Object.defineProperties;var gi=Object.getOwnPropertyDescriptors;var Ft=Object.getOwnPropertySymbols;var hi=Object.prototype.hasOwnProperty,mi=Object.prototype.propertyIsEnumerable;var Ge=(O,_,m)=>_ in O?fi(O,_,{enumerable:!0,configurable:!0,writable:!0,value:m}):O[_]=m,d=(O,_)=>{for(var m in _||(_={}))hi.call(_,m)&&Ge(O,m,_[m]);if(Ft)for(var m of Ft(_))mi.call(_,m)&&Ge(O,m,_[m]);return O},w=(O,_)=>di(O,gi(_));var K=(O,_,m)=>Ge(O,typeof _!="symbol"?_+"":_,m);var I=(O,_,m)=>new Promise((ne,j)=>{var ie=U=>{try{H(m.next(U))}catch(D){j(D)}},ae=U=>{try{H(m.throw(U))}catch(D){j(D)}},H=U=>U.done?ne(U.value):Promise.resolve(U.value).then(ie,ae);H((m=m.apply(O,_)).next())});function O(){return typeof window!="undefined"?window:void 0}function _(){return typeof navigator=="undefined"?"":navigator.userAgent||""}function m(){const t=O();if(!t)return!1;if(t.__wxjs_environment==="miniprogram"||t.wx&&t.wx.miniProgram)return!0;const e=_();return!!(e&&/micromessenger/i.test(e)&&/miniProgram/i.test(e))}function ne(){const t=O();return!!(t&&t.plus)}function j(){const t=O();return!!(t&&(t.__dcloud_weex_postMessage||t.__dcloud_weex_))}function ie(){const t=O();return!!(t&&(t.__uniapp_x_postMessage||t.__uniapp_x_))}function ae(){const t=_();return/uni-app/i.test(t)}function H(){const t=_();return/Html5Plus/i.test(t)}function U(){return ae()||H()}function D(){const t=O();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 Bt(){return ie()?"uvue":j()?"nvue":m()?"weixin":D()?"offline":ne()?"plus":U()?"webview":ae()?"UniApp":"h5"}let _e=null;function se(t=!1){return _e&&!t||(_e={isWeixinMiniProgram:m(),isAppPlus:ne(),isNvue:j(),isUvue:ie(),isUniApp:ae(),isHtml5Plus:H(),isUniAppWebView:U(),isOfflineWebview:D(),type:Bt()}),_e}const l=se(),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 S 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,S)}toJSON(){return{name:this.name,type:this.type,message:this.message,context:this.context,timestamp:this.timestamp,stack:this.stack}}}const R=class R{static setDebugMode(e){R.isDebugMode=e}static addErrorCallback(e){typeof e=="function"&&R.errorCallbacks.push(e)}static removeErrorCallback(e){const r=R.errorCallbacks.indexOf(e);r>-1&&R.errorCallbacks.splice(r,1)}static handleApiError(e,r={}){let n;return e instanceof S?n=e:e instanceof Error?n=new S(b.API_CALL_FAILED,e.message,r,e):n=new S(b.API_CALL_FAILED,String(e),r),R.logError(n),R.notifyCallbacks(n),n}static handlePlatformNotSupported(e,r){const n=new S(b.PLATFORM_NOT_SUPPORTED,`API "${r}" is not supported on platform "${e}"`,{platformType:e,apiName:r});return R.logError(n),R.notifyCallbacks(n),n}static handleBridgeNotReady(e){const r=new S(b.BRIDGE_NOT_READY,`Bridge is not ready when calling "${e}"`,{apiName:e});return R.logError(r),R.notifyCallbacks(r),r}static handleInvalidParameters(e,r,n,i){const s=new S(b.INVALID_PARAMETERS,`Invalid parameter "${r}" in "${e}": expected ${n}, got ${typeof i}`,{apiName:e,paramName:r,expectedType:n,actualValue:i});return R.logError(s),R.notifyCallbacks(s),s}static safeExecute(e,r={}){try{return e()}catch(n){return R.handleApiError(n,r)}}static safeExecuteAsync(n){return I(this,arguments,function*(e,r={}){try{return yield e()}catch(i){return R.handleApiError(i,r)}})}static logError(e){if(typeof console!="undefined"){const r=`[QSH-SDK Error] ${e.type}: ${e.message}`;R.isDebugMode?console.error(r,{context:e.context,originalError:e.originalError,stack:e.stack,timestamp:e.timestamp}):console.error(r)}}static notifyCallbacks(e){R.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 s=i.value;return i.value=function(...c){return R.safeExecute(()=>s.apply(this,c),w(d({},e),{method:n,target:r.constructor.name}))},i}}};K(R,"isDebugMode",!1),K(R,"errorCallbacks",[]);let u=R;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 s=this.errorCallbacks.indexOf(n);s>-1&&this.errorCallbacks.splice(s,1)}}getStats(){return{state:this.state,readyCallbacksCount:this.readyCallbacks.length,errorCallbacksCount:this.errorCallbacks.length,hasReadyPromise:!!this.readyPromise,hasInitializationError:!!this.initializationError}}}const Y=new kt,Ke=()=>Y.waitForReady(),Gt=()=>Y.isReady(),Kt=()=>Y.getState(),C={ERROR:0,WARN:1,INFO:2,DEBUG:3,TRACE:4},de={[C.ERROR]:"ERROR",[C.WARN]:"WARN",[C.INFO]:"INFO",[C.DEBUG]:"DEBUG",[C.TRACE]:"TRACE"},f=class f{static setLevel(e){e>=C.ERROR&&e<=C.TRACE&&(f.currentLevel=e,f.log(C.INFO,"Logger",`日志级别设置为: ${de[e]}`))}static enableDevMode(){f.setLevel(C.DEBUG),f.log(C.INFO,"Logger","开发模式已启用")}static enableProdMode(){f.setLevel(C.WARN),f.log(C.INFO,"Logger","生产模式已启用")}static enableModule(e){f.enabledModules.add(e),f.log(C.INFO,"Logger",`模块日志已启用: ${e}`)}static disableModule(e){f.enabledModules.delete(e),f.log(C.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 s=new Date().toISOString(),c=de[e],h=r?`[${r}]`:"",g=`${f.prefix} ${h} ${n}`,P={timestamp:s,level:e,levelName:c,module:r,message:n,args:i};if(f.addToHistory(P),typeof f.reporter=="function")try{f.reporter(P)}catch(v){}f.outputToConsole(e,g,...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 C.ERROR:i?console.error(r,...n):console.error(r);break;case C.WARN:i?console.warn(r,...n):console.warn(r);break;case C.INFO:i?console.info(r,...n):console.info(r);break;case C.DEBUG:case C.TRACE:i?console.log(r,...n):console.log(r);break}}static error(e,r,...n){f.log(C.ERROR,e,r,...n)}static warn(e,r,...n){f.log(C.WARN,e,r,...n)}static info(e,r,...n){f.log(C.INFO,e,r,...n)}static debug(e,r,...n){f.log(C.DEBUG,e,r,...n)}static trace(e,r,...n){f.log(C.TRACE,e,r,...n)}static getHistory(e){return e&&e>0?f.logHistory.slice(-e):[...f.logHistory]}static clearHistory(){f.logHistory=[],f.log(C.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",C.ERROR),K(f,"enabledModules",new Set),K(f,"logHistory",[]),K(f,"maxHistorySize",1e3),K(f,"prefix","[QSH-SDK]"),K(f,"reporter",null);let L=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)&&L.enableDevMode()}const E=L.createModuleLogger("Bridge"),y=L.createModuleLogger("Platform"),a=L.createModuleLogger("API"),W=L.createModuleLogger("State"),Ce=/complete|loaded|interactive/;function zt(t){if(!D())return!1;E.debug("检测到离线包环境,开始初始化");const e=()=>{t()};if(Ce.test(document.readyState))E.debug("离线包环境 DOM 已就绪,立即初始化"),setTimeout(e,0);else{E.debug("离线包环境,等待 DOMContentLoaded");let r=!1;const n=()=>{r||(r=!0,e())};document.addEventListener("DOMContentLoaded",n),setTimeout(n,500)}return!0}function Vt(t){return ae()||H()?(E.debug("检测到 APP 环境,开始初始化"),window.__uniapp_x_postMessage||window.__uniapp_x_||window.__dcloud_weex_postMessage||window.__dcloud_weex_?(E.debug("NVUE/UVUE 环境,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)):window.plus&&Ce.test(document.readyState)?(E.debug("Plus 环境已就绪,立即初始化"),setTimeout(t,0)):window.plus?(E.debug("Plus 环境,等待 plusready 事件"),document.addEventListener("plusready",t)):Ce.test(document.readyState)?setTimeout(t,0):document.addEventListener("DOMContentLoaded",t,{once:!0}),!0):!1}function qt(t){return window.wx&&window.wx.miniProgram?(E.debug("检测到微信小程序环境,开始初始化"),window.WeixinJSBridge&&window.WeixinJSBridge.invoke?(E.debug("微信 JSBridge 已就绪,立即初始化"),setTimeout(t,0)):(E.debug("微信 JSBridge 未就绪,等待 WeixinJSBridgeReady 事件"),document.addEventListener("WeixinJSBridgeReady",t)),!0):!1}function Jt(t){return E.info("开始初始化 JSBridge"),zt(t)?(E.info("使用离线包环境初始化"),!0):Vt(t)?(E.info("使用 APP 环境初始化"),!0):qt(t)?(E.info("使用微信小程序环境初始化"),!0):(E.debug("使用默认 H5 环境初始化"),Ce.test(document.readyState)?(E.debug("DOM 已就绪,立即初始化"),setTimeout(t,0)):(E.debug("DOM 未就绪,等待 DOMContentLoaded"),document.addEventListener("DOMContentLoaded",t)),!0)}function jt(){return Y.waitForReady()}function ze(){return Y.startInitialization(()=>I(null,null,function*(){return new Promise((t,e)=>{const r=()=>{t()},n=i=>{const s=u.handleApiError(i,{context:"bridge initialization"});e(s)};try{Jt(()=>{r()})}catch(i){n(i)}})}))}const M={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 Ht{constructor(){this.state=M.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 S(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 S(b.INVALID_PARAMETERS,"clientId参数异常",{clientId:e.clientId});if(Object.prototype.hasOwnProperty.call(e,"isProd")&&typeof e.isProd!="boolean")throw new S(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=w(d({},this.runtimeConfig),{clientId:r,isProd:n}),this.CONFIG_API_URL=this.getConfigApiUrl(n),(this.state===M.ERROR||i&&(this.state===M.CONFIGURING||this.state===M.CONFIGURED))&&this.reset(),y.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 S(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 y.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)}`;y.debug("请求微信配置",{url:n});try{const i=yield fetch(n);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);const s=yield i.json();if(y.debug("微信配置响应",s),!s.success||s.code!==200)throw new Error(`配置获取失败: ${s.message||"未知错误"}`);const{data:c}=s;if(!c||!c.appId||!c.timestamp||!c.nonceStr||!c.signature)throw new Error("配置数据格式不正确,缺少必需字段");return c}catch(i){if(y.error("获取微信配置失败",i),this.shouldUseTestMode(i))return y.warn("网络请求失败,降级到测试模式"),this.getMockConfig();throw new S(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"){y.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};y.info("执行微信配置",r),window.wx.ready(this.handleConfigSuccess),window.wx.error(this.handleConfigError),window.wx.config(r)}handleConfigSuccess(){y.info("微信配置成功"),this.state=M.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)}`;y.error(r,e);const n=new S(b.API_CALL_FAILED,r,{weixinErrorResponse:e});this.state=M.ERROR,this.lastError=n,this.configPromise=null;const i=[...this.errorCallbacks];this.readyCallbacks=[],this.errorCallbacks=[],i.forEach(s=>{try{s(n)}catch(c){u.handleApiError(c,{context:"WeixinConfigManager.handleConfigError"})}})}autoConfig(){return I(this,null,function*(){return this.hasRequiredConfig()?this.state===M.CONFIGURED?Promise.resolve():this.state===M.ERROR?Promise.reject(this.lastError):this.configPromise?this.configPromise:(this.state=M.CONFIGURING,this.configPromise=this.performAutoConfig(),this.configPromise):(y.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===M.CONFIGURED){r();return}if(this.state===M.ERROR){n(this.lastError);return}this.readyCallbacks.push(r),this.errorCallbacks.push(n)})}catch(e){const r=e instanceof S?e:u.handleApiError(e,{context:"WeixinConfigManager.performAutoConfig"});this.state=M.ERROR,this.lastError=r,this.configPromise=null;const n=[...this.errorCallbacks];throw this.readyCallbacks=[],this.errorCallbacks=[],n.forEach(i=>{try{i(r)}catch(s){u.handleApiError(s,{context:"WeixinConfigManager.performAutoConfig.errorCallback"})}}),r}})}waitForReady(){return this.state===M.CONFIGURED?Promise.resolve():this.state===M.ERROR?Promise.reject(this.lastError):this.hasRequiredConfig()?this.state===M.UNINITIALIZED?this.autoConfig():new Promise((e,r)=>{this.readyCallbacks.push(e),this.errorCallbacks.push(r)}):Promise.reject(this.createMissingClientIdError())}isReady(){return this.state===M.CONFIGURED}getState(){return this.state}getLastError(){return this.lastError}reset(){this.state=M.UNINITIALIZED,this.configPromise=null,this.readyCallbacks=[],this.errorCallbacks=[],this.lastError=null,y.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 Ht;let oe=!1,ge=!1,$=null,Oe=!1;function Yt(t){return new Promise(e=>{let r=!1,n=null;const i=h=>I(null,null,function*(){if(!r){if(r=!0,n&&clearTimeout(n),oe=!1,ge=h,h)try{yield Ve()}catch(g){y.error("微信配置失败,将使用消息桥作为后备",g)}e()}}),s=()=>i(B()),c=()=>{y.warn("已存在的微信 JS-SDK 脚本加载失败,SDK 将使用消息桥作为后备"),i(!1)};t.addEventListener("load",s,{once:!0}),t.addEventListener("error",c,{once:!0}),setTimeout(()=>{B()&&s()},0),n=setTimeout(()=>{i(B())},3e3)})}function Te(){return I(this,arguments,function*(t={}){const{force:e=!1,recoverFromError:r=!1}=t;if(yield qe({force:e}),!B())throw new Error("微信 JS-SDK 未正确加载,无法执行配置");r&&Xt()})}function Zt(t=!1){if(typeof window=="undefined")return!1;if(B())return ge=!0,!1;if(ge||D())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",s=!!(window.wx&&window.wx.miniProgram);return r&&(n||i||s)}function Xt(){T.getState()==="error"&&(T.reset(),Oe=!1)}function Ve(){return I(this,null,function*(){if(Oe)return T.waitForReady();Oe=!0,y.info("开始自动配置微信JS-SDK");try{yield T.autoConfig(),y.info("微信JS-SDK自动配置完成")}catch(t){y.error("微信JS-SDK自动配置失败",t)}})}function qe(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?$||(oe=!0,$=Yt(r).finally(()=>{$=null}),$):Zt(e)?$||($=new Promise(n=>{oe=!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,oe=!1,y.info("微信 JS-SDK 已自动加载");try{yield Ve()}catch(c){y.error("微信配置失败,将使用消息桥作为后备",c)}n()})},i.onerror=function(){oe=!1,y.warn("微信 JS-SDK 加载失败,SDK 将使用消息桥作为后备"),n()},(document.getElementsByTagName("head")[0]||document.documentElement).appendChild(i)}catch(i){oe=!1,y.error("注入微信 JS-SDK 失败",i),n()}}).finally(()=>{$=null}),$):Promise.resolve()}function z(){return Te({force:!0,recoverFromError:!0}).then(()=>T.waitForReady())}function Je(t={}){const e=T.configure(t);return typeof window=="undefined"||Te({force:!0,recoverFromError:T.getState()==="error"}).then(()=>{if(!T.isReady())return T.waitForReady().catch(r=>{y.error("Failed to auto-configure Weixin after qsh.config()",r)});window.wx&&!B()&&y.warn("window.wx 已存在,但微信 JS-SDK 尚未就绪,跳过自动配置")}).catch(r=>{y.error("Failed to preload Weixin JS-SDK",r)}),e}function Z(){return T.isReady()}function Qt(){return T.getState()}function ve(){return T}function er(){return I(this,null,function*(){return y.info("手动重试微信配置"),T.reset(),Oe=!1,yield Te({force:!0}),T.waitForReady()})}class tr{constructor(){this.plugins=new Map,this.installed=new Set,this.installOrder=[],a.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);a.warn(`插件 ${r} 已注册(版本 ${i.version}),将被覆盖为版本 ${n}`)}return this.plugins.set(r,e),a.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)){a.debug(`插件 ${e} 已安装,跳过`);return}const n=this.plugins.get(e);if(n.dependencies&&n.dependencies.length>0){a.debug(`安装插件 ${e} 的依赖:`,n.dependencies);for(const i of n.dependencies)yield this.install(i,r)}a.info(`开始安装插件: ${e}@${n.version}`),yield n.install(r),this.installed.add(e),this.installOrder.push(e),a.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)){a.debug(`插件 ${e} 未安装,跳过卸载`);return}const n=this.plugins.get(e);n.uninstall&&typeof n.uninstall=="function"&&(a.info(`开始卸载插件: ${e}`),yield n.uninstall(r)),this.installed.delete(e);const i=this.installOrder.indexOf(e);i>-1&&this.installOrder.splice(i,1),a.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 tr;class rr{constructor(){this.requestInterceptors=[],this.responseInterceptors=[],a.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,s)=>s.priority-i.priority),a.debug("请求拦截器已注册",{priority:n}),()=>{const i=this.requestInterceptors.findIndex(s=>s.fn===e);i>-1&&(this.requestInterceptors.splice(i,1),a.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,s)=>s.priority-i.priority),a.debug("响应拦截器已注册",{priority:n}),()=>{const i=this.responseInterceptors.findIndex(s=>s.fn===e);i>-1&&(this.responseInterceptors.splice(i,1),a.debug("响应拦截器已移除"))}}runRequest(e){return I(this,null,function*(){let r=d({},e);for(const{fn:n}of this.requestInterceptors){if(r.abort){a.debug("请求被中止",{apiName:r.apiName});break}try{const i=yield n(r);i&&(r=i)}catch(i){a.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 s=yield i(n,r);s!==void 0&&(n=s)}catch(s){a.error("响应拦截器执行失败",s)}return n})}clear(){this.requestInterceptors=[],this.responseInterceptors=[],a.debug("所有拦截器已清空")}getStats(){return{requestInterceptors:this.requestInterceptors.length,responseInterceptors:this.responseInterceptors.length}}}const X=new rr,nr={request:t=>(t.startTime=Date.now(),a.debug(`[API 调用] ${t.apiName}`,{params:t.params}),t),response:(t,e)=>{const r=Date.now()-e.startTime;return a.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]=d({},e)}),t},clearMetrics:()=>{V.metrics.clear()}};function ir(t={}){const{maxRetries:e=3,retryDelay:r=1e3,shouldRetry:n=i=>!i.success}=t;return{response:(i,s)=>I(null,null,function*(){return s.retryCount||(s.retryCount=0),n(i)&&s.retryCount<e&&(s.retryCount++,a.warn(`API 调用失败,第 ${s.retryCount} 次重试: ${s.apiName}`),yield new Promise(c=>setTimeout(c,r)),i.shouldRetry=!0,i.retryContext=s),i})}}function ar(t={}){return{request:e=>{const r=t[e.apiName];if(r&&typeof r=="function"){const n=r(e.params);n&&(a.error(`参数验证失败: ${e.apiName}`,n),e.abort=!0,e.validationError=n)}return e}}}class sr{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(),s=n.reduce((h,g)=>((!h[g]||typeof h[g]!="object")&&(h[g]={}),h[g]),this.state),c=s[i];c!==r&&(s[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,s,c)=>{r(i,s,c),n()});return n}notify(e,r,n){const i=this.listeners.get(e);i&&i.forEach(c=>{try{c(r,n,e)}catch(h){W.error("订阅者执行失败",h)}});const s=e.split(".");for(let c=1;c<s.length;c++){const h=s.slice(0,c).join("."),g=this.listeners.get(h);if(g){const P=this.get(h);g.forEach(v=>{try{v(P,void 0,h)}catch(p){W.error("父路径订阅者执行失败",p)}})}}this.wildcardListeners.forEach(c=>{try{c(r,n,e)}catch(h){W.error("通配符订阅者执行失败",h)}})}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,w(d({},i),{loading:r,lastCall:r?Date.now():i.lastCall}))}setApiResult(e,r){const n=`api.${e}`,i=this.get(n)||{};this.set(n,w(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 k=new sr,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"},Le={[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"},or={"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},je={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}},He={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 Ye(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 cr(t){return t.includes("NET_")||t.includes("TIMEOUT")||t===o.NETWORK_ERROR||t===o.NETWORK_TIMEOUT||t===o.API_TIMEOUT}function ur(t){return t.includes("CANCEL")||Ye(t)===F.USER_CANCEL}function ce(t){return Le[t]||Le[o.UNKNOWN_ERROR]}class G extends Error{constructor(e,r,n={}){super(r),this.name="StandardError",this.code=e,this.message=r||ce(e),this.platform=n.platform||l.type,this.apiName=n.apiName,this.category=n.category||Ye(e),this.retriable=n.retriable!==void 0?n.retriable:cr(e),this.originalError=n.originalError,this.details=n.details||{},this.timestamp=Date.now()}isRetriable(){return this.retriable}isUserAction(){return ur(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 Ze(t,e={}){if(t instanceof G)return t;const{apiName:r,platform:n=l.type}=e;return t&&typeof t.code=="string"&&t.code.includes("/")?lr(t,{apiName:r,platform:n}):t&&(t.errMsg||t.message)?fr(t,{apiName:r,platform:n}):typeof t=="string"?new G(o.UNKNOWN_ERROR,t,{apiName:r,platform:n,originalError:t}):new G(o.UNKNOWN_ERROR,"未知错误",{apiName:r,platform:n,originalError:t,details:{errorType:typeof t}})}function lr(t,e){const{apiName:r,platform:n}=e,i=t.code,s=or[i]||o.UNKNOWN_ERROR;return a.debug("转换旧版错误码",{legacy:i,new:s}),new G(s,t.message||ce(s),{apiName:r,platform:t.platform||n,originalError:t,details:d({legacyCode:i,legacyVersion:t.version},t.details)})}function fr(t,e){const{apiName:r,platform:n}=e,i=(t.errMsg||t.message||"").toLowerCase();if(r&&He[r]){const h=He[r];for(const[g,P]of Object.entries(h))if(i.includes(g.toLowerCase()))return new G(P,ce(P),{apiName:r,platform:n,originalError:t})}const s=je[n]||je.uniapp;for(const{pattern:h,code:g}of s.patterns)if(h.test(i))return new G(g,ce(g),{apiName:r,platform:n,originalError:t});const c=s.default||o.UNKNOWN_ERROR;return new G(c,t.errMsg||t.message||ce(c),{apiName:r,platform:n,originalError:t})}const Xe={response:(t,e)=>{if(!t.success&&t.error){const r=Ze(t.error,{apiName:e.apiName,platform:l.type});t.error=r.toJSON(),t.errorCode=r.code,t.errorCategory=r.category,t.retriable=r.isRetriable(),a.debug("错误已标准化",{api:e.apiName,code:r.code,category:r.category})}return t}};function dr(t,e={}){return new G(t,ce(t),e)}function gr(t){return t instanceof G}function hr(t,e,r){return e?Promise.race([t(),new Promise((n,i)=>setTimeout(()=>i(new Error(`Init task timeout: ${r}`)),e))]):t()}function mr(){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 hr(()=>Promise.resolve().then(()=>i()),r.timeoutMs,n),typeof r.onSuccess=="function"&&r.onSuccess()}catch(s){if(typeof r.onError=="function"&&r.onError(s),typeof e.onError=="function")e.onError(s,r);else throw s}}})}class Qe{constructor(e){this.name=e}processNavigationOptions(e={}){const{url:r,delta:n=1}=e,i=r&&encodeURI(r),s=parseInt(n)||1;return w(d({},e),{url:i,delta:s})}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 me=[];function pr(){if(me.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;me.push(r)}return me}function wr(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:me}};window.__uniapp_x_postMessage?window.__uniapp_x_postMessageToService(n):window.__uniapp_x_.postMessageToService(JSON.stringify(n))}function Er(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:me}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(n):window.__dcloud_weex_.postMessageToService(JSON.stringify(n))}function yr(t,e){const r={options:{timestamp:+new Date},name:t,arg:e},n=pr();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),s=JSON.stringify(n);plus.webview.getLaunchWebview().evalJS(`UniPlusBridge.subscribeHandler("WEB_INVOKE_APPSERVICE",${i},${s});`)}}function Ir(t,e){const r={options:{timestamp:+new Date},name:t,arg:e};window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""},"*")}function Ar(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"&&Ar(e))return window.__offline_bridge_postMessage(e);window.__offline_bridge_postMessage({type:"WEB_INVOKE_APPSERVICE",data:r,pageId:""})}function pe(t,e){ie()?wr(t,e):j()?Er(t,e):D()?_r(t,e):ne()?yr(t,e):Ir(t,e)}class et extends Qe{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(y.debug(`微信平台执行导航操作: ${e}`,r),this.isWeixinApiAvailable()){const c=window.wx.miniProgram[e];if(typeof c=="function"){y.debug(`使用微信原生 API: wx.miniProgram.${e}`);const h=e==="navigateBack"?{delta:i}:{url:n};return c.call(window.wx.miniProgram,h)}}y.debug(`使用消息桥接执行: ${e}`),pe(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});pe("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 et;var tt=Object.freeze({__proto__:null,WeixinPlatform: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)});class rt extends Qe{constructor(){super("app")}performNavigation(e,r){return u.safeExecute(()=>{const{url:n,delta:i}=r;pe(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;pe("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;ie()?(r.uvue=!0,n=!0):j()?(r.nvue=!0,n=!0):ne()?(r.plus=!0,n=!0):D()&&(r.offline=!0,n=!0),n?r.app=!0:r.h5=!0,e(r)},{platform:this.name,method:"performGetEnv"})}}const ee=new rt;var nt=Object.freeze({__proto__:null,AppPlatform:rt,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 m()?tt:nt}function Cr(t){return we().navigateTo(t)}function Or(t){return we().navigateBack(t)}function Pr(t){return we().switchTab(t)}function Rr(t){return we().reLaunch(t)}function Nr(t){return we().redirectTo(t)}function it(){return m()?tt:nt}function Mr(t={}){return it().postMessage(t)}function Sr(t){return it().getEnv(t)}function Tr(t){return t&&typeof t=="object"&&t.__v_raw?t.__v_raw:t}function vr(){return"qsh_callback_"+Date.now()+"_"+Math.random().toString(36).substring(2,9)}class Lr{constructor(){this.callbacks=new Map,this.timeouts=new Map,this.persistentCallbacksByApi=new Map,this.defaultTimeout=3e4,typeof window!="undefined"&&(window.qshWebviewCallbacks||(window.qshWebviewCallbacks={})),E.debug("WebView 桥接器已初始化")}callApi(i){return I(this,arguments,function*(e,r={},n={}){return u.safeExecute(()=>I(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_&&!D()){const v=new S(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 c={apiName:e,params:r,callbacks:n,timestamp:Date.now(),abort:!1,metadata:{}};k.setApiLoading(e,!0);const h=yield X.runRequest(c);if(h.abort){E.warn("API 调用被拦截器中止",{api:e}),k.setApiLoading(e,!1),n.fail&&n.fail({errMsg:((P=h.error)==null?void 0:P.message)||"API 调用被中止",code:"INTERCEPTED"}),n.complete&&n.complete({success:!1});return}const g=vr();if(n.success||n.fail||n.complete){if(this.callbacks.set(g,w(d({},n),{context:h})),window.qshWebviewCallbacks[g]=ye=>{this.handleCallback(g,ye)},r.isPersistent&&(this.persistentCallbacksByApi.has(e)||this.persistentCallbacksByApi.set(e,new Set),this.persistentCallbacksByApi.get(e).add(g)),r.isPersistent||r.disableTimeout)E.info(`API ${e} 禁用超时清理,将等待回调返回后清理`,{callbackId:g,isPersistent:r.isPersistent,disableTimeout:r.disableTimeout});else{const ye=setTimeout(()=>{E.warn("API 调用超时,自动清理回调",{api:e,callbackId:g}),n.fail&&n.fail({errMsg:`API ${e} 调用超时`,code:"TIMEOUT"}),this.cleanupCallback(g)},r.timeout||this.defaultTimeout);this.timeouts.set(g,ye)}const p={type:"qsh_api_call",api:e,params:h.params,callbackId:g,timestamp:Date.now()};E.info("发送 API 调用消息",{api:e,callbackId:g,hasSuccess:!!n.success,hasFail:!!n.fail}),console.log("message:",JSON.stringify(Tr(p),null,2)),pe("postMessage",p)}}),{context:"WebViewBridge.callApi",api:e})})}handleCallback(e,r){return I(this,null,function*(){return u.safeExecute(()=>I(this,null,function*(){var v,p;const n=this.callbacks.get(e);if(!n){E.warn("未找到回调函数",{callbackId:e});return}const{success:i,fail:s,complete:c,context:h}=n;E.debug("处理回调",{callbackId:e,result:r});const g=yield X.runResponse(r,h);h&&k.setApiResult(h.apiName,g),g.success&&i?i(g.data):!g.success&&s&&s(g.error||{errMsg:"操作失败"}),c&&c(g),((p=(v=n.context)==null?void 0:v.params)==null?void 0:p.isPersistent)?E.debug("持久监听API:保留回调",{callbackId:e}):(this.cleanupCallback(e),E.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,s)=>{i.has(e)&&(i.delete(e),i.size===0&&n.push(s))}),n.forEach(i=>this.persistentCallbacksByApi.delete(i))}}clearCallbacks(){E.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),E.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 at=new Lr,N=(t,e,r)=>at.callApi(t,e,r),ue=t=>at.cleanupPersistentCallbacksByApi(t);function st(){return se(!0)}function br(t){return t==="offline"}function xr(t={}){return u.safeExecute(()=>{a.debug("Call getCode through offline webview bridge",{clientId:t.clientId}),N("getCode",{clientId:t.clientId},{success:e=>{var r;a.info("Get code success"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("Get code failed",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getCodeInHost",platform:st().type})}function Dr(t={}){return u.safeExecute(()=>{var n,i;const e=st(),r=String((t==null?void 0:t.clientId)||"").trim();if(!r){const s={errMsg:"clientId is required",code:"APP_KEY_MISSING"};a.error("Get code missing clientId"),(n=t.fail)==null||n.call(t,s);return}if(!br(e.type)){const s={errMsg:`Current environment (${e.type}) does not support getCode`,code:"PLATFORM_NOT_SUPPORTED"};a.error("Platform does not support getCode",{platform:e.type}),(i=t.fail)==null||i.call(t,s);return}xr(w(d({},t),{clientId:r}))},{context:"getCode",options:t})}function ot(){return se(!0)}const ct=["release","trial","develop"];function Ur(t={}){const e=String((t==null?void 0:t.appid)||"").trim(),r=(t==null?void 0:t.path)==null?"":t.path,n=t==null?void 0:t.env,i=n==null||n===""?void 0:String(n).trim();if(!e)throw{errMsg:"appid is required",code:"PARAM_MISSING"};if(typeof r!="string")throw{errMsg:"path must be a string",code:"PARAM_TYPE_ERROR"};if(i!==void 0&&!ct.includes(i))throw{errMsg:`env must be one of ${ct.join("/")}`,code:"PARAM_INVALID"};return w(d({},t),{appid:e,path:r.trim(),env:i})}function Wr(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram&&typeof window.wx.miniProgram.postMessage=="function"&&typeof window.wx.miniProgram.navigateBack=="function"}function $r(t={}){return u.safeExecute(()=>{var r;if(!Wr()){const n={errMsg:"wx.miniProgram.postMessage or wx.miniProgram.navigateBack is not available",code:"PLATFORM_NOT_SUPPORTED"};a.error("Weixin web-view relay APIs are not available"),(r=t.fail)==null||r.call(t,n);return}const e={type:"qsh_api_call",api:"navigateToMiniProgram",params:{appid:t.appid,path:t.path,env:t.env},timestamp:Date.now()};return a.debug("Relay navigateToMiniProgram through wx.miniProgram.postMessage",{appid:t.appid,path:t.path,env:t.env}),new Promise((n,i)=>{var s;try{window.wx.miniProgram.postMessage({data:e})}catch(c){a.error("Post navigateToMiniProgram message failed",c),(s=t.fail)==null||s.call(t,c),i(c);return}window.wx.miniProgram.navigateBack({delta:1,success:c=>{var g;const h=w(d({},c),{errMsg:(c==null?void 0:c.errMsg)||"navigateToMiniProgram:queued"});a.info("Navigate to mini program request queued in weixin web-view",{appid:t.appid,path:t.path,env:t.env}),(g=t.success)==null||g.call(t,h),n(h)},fail:c=>{var h;a.error("Navigate back after posting mini program message failed",c),(h=t.fail)==null||h.call(t,c),i(c)},complete:t.complete})})},{context:"navigateToMiniProgramInWeixin",platform:"weixin"})}function Fr(t={}){return u.safeExecute(()=>(a.debug("Call navigateToMiniProgram through webview bridge",{appid:t.appid,path:t.path,env:t.env}),new Promise((e,r)=>{N("navigateToMiniProgram",{appid:t.appid,path:t.path,env:t.env},{success:n=>{var i;a.info("Navigate to mini program success"),(i=t.success)==null||i.call(t,n),e(n)},fail:n=>{var i;a.error("Navigate to mini program failed",n),(i=t.fail)==null||i.call(t,n),r(n)},complete:t.complete})})),{context:"navigateToMiniProgramInHost",platform:ot().type})}function Br(t={}){return u.safeExecute(()=>{var n;const e=ot();let r;try{r=Ur(t)}catch(i){a.error("Navigate to mini program params validation failed",i),(n=t.fail)==null||n.call(t,i);return}return a.info("Start navigateToMiniProgram",{platform:e.type,appid:r.appid,path:r.path,env:r.env}),e.isWeixinMiniProgram?$r(r):Fr(r)},{context:"navigateToMiniProgram",options:t})}const Pe={ALBUM:"album",CAMERA:"camera"},Re={ORIGINAL:"original",COMPRESSED:"compressed"},kr={count:9,sizeType:[Re.ORIGINAL,Re.COMPRESSED],sourceType:[Pe.ALBUM,Pe.CAMERA]};function Gr(t={}){const e=d(d({},kr),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=[Re.COMPRESSED]),e.sourceType.length===0&&(e.sourceType=[Pe.ALBUM]),e}function ut(){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(!Z()){a.info("等待微信配置完成"),z().then(()=>lt(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.debug("调用微信图片选择",t),window.wx.chooseImage({count:t.count,sizeType:t.sizeType,sourceType:t.sourceType,success:r=>{var n,i;a.info("微信图片选择成功",{count:((n=r.localIds)==null?void 0:n.length)||0}),(i=t.success)==null||i.call(t,r)},fail:r=>{var n;a.error("微信图片选择失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"chooseImageInWeixin",platform:"weixin"})}function Kr(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用图片选择",t),N("chooseImage",w(d({},t),{disableTimeout:!0}),{success:e=>{var r,n;a.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;a.error("UniApp 图片选择失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"chooseImageInUniApp",platform:"uniapp"})}function zr(t={}){return u.safeExecute(()=>{var r;if(!ut()){const n={errMsg:`当前环境 (${l.type}) 不支持图片选择功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持图片选择",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Gr(t);a.info("开始选择图片",{platform:l.type,count:e.count,sizeType:e.sizeType,sourceType:e.sourceType}),m()?lt(e):Kr(e)},{context:"chooseImage",options:t})}function Vr(){return{supported:ut(),environment:l.type,implementation:m()?"weixin":"webview",features:{multipleSelection:!0,sizeTypeSelection:!0,sourceTypeSelection:!0,asyncSupport:!0}}}const te={QR_CODE:"qrCode",BAR_CODE:"barCode",DATA_MATRIX:"datamatrix",PDF417:"pdf417"},qr={onlyFromCamera:!0,scanType:[te.QR_CODE,te.BAR_CODE]};function Jr(t={}){const e=d(d({},qr),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 ft(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function dt(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(!Z()){a.info("等待微信配置完成"),z().then(()=>dt(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.debug("调用微信扫码",t),window.wx.scanQRCode({needResult:1,scanType:t.scanType,success:r=>{var i;a.info("微信扫码成功",{result:r.resultStr});const n={result:r.resultStr,scanType:jr(r.resultStr),charSet:"utf-8",errMsg:"scanCode:ok"};(i=t.success)==null||i.call(t,n)},fail:r=>{var n;a.error("微信扫码失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"scanCodeInWeixin",platform:"weixin"})}function jr(t){return t?t.length>50||/[^\d]/.test(t)?te.QR_CODE:te.BAR_CODE:"unknown"}function Hr(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用扫码",t),N("scanCode",w(d({},t),{disableTimeout:!0}),{success:e=>{var r;a.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;a.error("UniApp 扫码失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"scanCodeInUniApp",platform:"uniapp"})}function Yr(t={}){return u.safeExecute(()=>{var r;if(!ft()){const n={errMsg:`当前环境 (${l.type}) 不支持扫码功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持扫码",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Jr(t);a.info("开始扫码",{platform:l.type,onlyFromCamera:e.onlyFromCamera,scanType:e.scanType}),m()?dt(e):Hr(e)},{context:"scanCode",options:t})}function Zr(){return{supported:ft(),environment:l.type,implementation:m()?"weixin":"webview",features:{onlyFromCamera:!0,scanTypeSelection:!0,multipleTypes:!0,asyncSupport:!0}}}const le={WGS84:"wgs84",GCJ02:"gcj02",BD09:"bd09"},Xr={type:le.WGS84,altitude:!1},Qr={scale:18};function en(t={}){const e=d(d({},Xr),t);return Object.values(le).includes(e.type)||(e.type=le.WGS84),e.altitude=!!e.altitude,e}function tn(t={}){const e=d({},t);return Object.values(le).includes(e.type)||(e.type=le.WGS84),e.needFullAccuracy=!!e.needFullAccuracy,e}function rn(t={}){const e=d(d({},Qr),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)?(a.warn("scale 参数无效,使用默认值 18",{scale:e.scale}),e.scale=18):e.scale=Math.max(1,Math.min(28,Math.floor(r)))}return e}function be(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function gt(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(!Z()){a.info("等待微信配置完成"),z().then(()=>gt(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.debug("调用微信定位",t),window.wx.getLocation({type:t.type,success:r=>{var n;a.info("微信定位成功",{latitude:r.latitude,longitude:r.longitude}),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;a.error("微信定位失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"getLocationInWeixin",platform:"weixin"})}function ht(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(!Z()){a.info("等待微信配置完成"),z().then(()=>ht(t)).catch(r=>{var n;a.error("微信配置失败",r),(n=t.fail)==null||n.call(t,{errMsg:`微信配置失败: ${r.message}`})});return}a.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;a.info("微信查看位置成功"),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;a.error("微信查看位置失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"openLocationInWeixin",platform:"weixin"})}function nn(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用获取位置",t),N("getLocation",t,{success:e=>{var r;a.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;a.error("UniApp 获取位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"getLocationInUniApp",platform:"uniapp"})}function an(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用查看位置",t),N("openLocation",t,{success:e=>{var r;a.info("UniApp 查看位置成功"),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("UniApp 查看位置失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"openLocationInUniApp",platform:"uniapp"})}function sn(t={}){return u.safeExecute(()=>{var r;if(!be()){const n={errMsg:`当前环境 (${l.type}) 不支持定位功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持定位",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=en(t);a.info("开始获取位置",{platform:l.type,type:e.type,altitude:e.altitude}),m()?gt(e):nn(e)},{context:"getLocation",options:t})}function on(t={}){return u.safeExecute(()=>{var r,n,i;if(!be()){const s={errMsg:`当前环境 (${l.type}) 不支持查看位置功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持查看位置",{platform:l.type}),(r=t.fail)==null||r.call(t,s);return}let e;try{e=rn(t)}catch(s){a.error("参数验证失败",s),(n=t.fail)==null||n.call(t,s),(i=t.complete)==null||i.call(t);return}a.info("开始查看位置",{platform:l.type,latitude:e.latitude,longitude:e.longitude,name:e.name}),m()?ht(e):an(e)},{context:"openLocation",options:t})}function cn(){const t=m();return{supported:be(),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 mt(t,e,r){t.forEach(n=>{if(typeof n=="function"){u.safeExecute(()=>n(e),{context:r});return}a.warn("监听回调不是函数,已跳过",{type:typeof n})})}function un(t={}){return u.safeExecute(()=>{var r,n;if(m()){const i={errMsg:`当前环境 (${l.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};a.error("当前环境不支持此接口",{platform:l.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=tn(t);a.info("正在开启定位监听"),N("startLocationUpdate",{type:e.type,needFullAccuracy:e.needFullAccuracy},{success:i=>{var s;a.info("定位监听已启动"),(s=t.success)==null||s.call(t,i)},fail:i=>{var s;return(s=t.fail)==null?void 0:s.call(t,i)},complete:t.complete})},{context:"startLocationUpdate"})}function ln(t={}){return u.safeExecute(()=>{var e,r;if(m()){const n={errMsg:`当前环境 (${l.type}) 不支持该接口`,code:"PLATFORM_NOT_SUPPORTED"};a.error("当前环境不支持此接口",{platform:l.type}),(e=t.fail)==null||e.call(t,n),(r=t.complete)==null||r.call(t,n);return}a.info("正在停止定位监听"),N("stopLocationUpdate",t,{success:n=>{var i;a.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 fn(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(typeof t!="function")throw a.error("onLocationChange 回调不是函数",{type:typeof t}),{errMsg:"onLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};const e=q.size>0;q.add(t),e||(a.debug("注册实时位置变化监听器"),N("onLocationChange",{isPersistent:!0},{success:r=>{a.debug("收到实时位置推送",r),mt(q,r,"onLocationChange")},fail:r=>{a.warn("位置变化监听出错,请通过 onLocationChangeError 监听错误",r),q.delete(t),q.size===0&&ue("onLocationChange")}}))},{context:"onLocationChange"})}function dn(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(t&&typeof t!="function")throw a.error("offLocationChange 回调不是函数",{type:typeof t}),{errMsg:"offLocationChange 回调必须是函数",code:"INVALID_CALLBACK"};t?q.delete(t):q.clear(),!(q.size>0)&&(a.info("移除位置变化监听器"),N("offLocationChange",{},{success:()=>{a.info("位置变化监听已移除"),ue("onLocationChange")},fail:e=>{a.error("移除位置变化监听失败",e),ue("onLocationChange")}}))},{context:"offLocationChange"})}function gn(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(typeof t!="function")throw a.error("onLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"onLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};const e=J.size>0;J.add(t),e||(a.debug("注册位置更新错误监听器"),N("onLocationChangeError",{isPersistent:!0},{success:r=>{a.warn("持续定位发生异常",r),mt(J,r,"onLocationChangeError")},fail:r=>{a.warn("位置更新错误监听注册失败",r),J.delete(t),J.size===0&&ue("onLocationChangeError")}}))},{context:"onLocationChangeError"})}function hn(t){return u.safeExecute(()=>{if(m()){a.warn("当前环境不支持此接口",{platform:l.type});return}if(t&&typeof t!="function")throw a.error("offLocationChangeError 回调不是函数",{type:typeof t}),{errMsg:"offLocationChangeError 回调必须是函数",code:"INVALID_CALLBACK"};t?J.delete(t):J.clear(),!(J.size>0)&&(a.info("移除定位错误监听器"),N("offLocationChangeError",{},{success:()=>{a.info("定位错误监听已移除"),ue("onLocationChangeError")},fail:e=>{a.error("移除定位错误监听失败",e),ue("onLocationChangeError")}}))},{context:"offLocationChangeError"})}const mn={latitude:null,longitude:null};function pn(t={}){const e=d(d({},mn),t);return e.latitude!==null&&e.latitude!==void 0&&(typeof e.latitude!="number"?(a.warn("latitude 参数类型错误,已忽略",{latitude:e.latitude}),e.latitude=null):(e.latitude<-90||e.latitude>90)&&(a.warn("latitude 超出范围,已忽略",{latitude:e.latitude}),e.latitude=null)),e.longitude!==null&&e.longitude!==void 0&&(typeof e.longitude!="number"?(a.warn("longitude 参数类型错误,已忽略",{longitude:e.longitude}),e.longitude=null):(e.longitude<-180||e.longitude>180)&&(a.warn("longitude 超出范围,已忽略",{longitude:e.longitude}),e.longitude=null)),e}function pt(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function wt(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(!Z()){a.info("等待微信配置完成"),z().then(()=>wt(t)).catch(i=>{var s;a.error("微信配置失败",i),(s=t.fail)==null||s.call(t,{errMsg:`微信配置失败: ${i.message}`})});return}a.debug("调用微信位置选择",t);const e={success:i=>{var c;a.info("微信位置选择成功",{name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude});const s={name:i.name,address:i.address,latitude:i.latitude,longitude:i.longitude,errMsg:"chooseLocation:ok"};(c=t.success)==null||c.call(t,s)},fail:i=>{var s;a.error("微信位置选择失败",i),(s=t.fail)==null||s.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(w(d({},r),{success:e.success,fail:e.fail,complete:e.complete}))},{context:"chooseLocationInWeixin",platform:"weixin"})}function wn(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用位置选择",t);const e={disableTimeout:!0,success:r=>{var n;a.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;a.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),N("chooseLocation",e,{success:r=>{e.success(r)},fail:r=>{e.fail(r)},complete:e.complete})},{context:"chooseLocationInUniApp",platform:"uniapp"})}function En(t={}){return u.safeExecute(()=>{var r;if(!pt()){const n={errMsg:`当前环境 (${l.type}) 不支持位置选择功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持位置选择",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=pn(t);a.info("开始选择位置",{platform:l.type,latitude:e.latitude,longitude:e.longitude}),m()?wt(e):wn(e)},{context:"chooseLocation",options:t})}function yn(){return{supported:pt(),environment:l.type,implementation:m()?"weixin":"webview",features:{chooseLocation:!0,centerPoint:!0,asyncSupport:!0}}}function In(t){return t==="timeline"||Number(t)===1?1:0}function An(t={}){if(!t||typeof t!="object")throw{errMsg:"shareDirected 参数必须是对象",code:"PARAM_TYPE_ERROR"};const e=String(t.kind||"").trim(),r=t.payload||{},n=In(t.scene);if(!["web","image","text"].includes(e))throw{errMsg:'shareDirected: kind 仅支持 "web"|"image"|"text"',code:"PARAM_INVALID"};if(e==="web"){if(!r.path&&!r.href)throw{errMsg:"shareDirected(web): payload.path 或 payload.href 必填",code:"PARAM_MISSING"};if(!r.title||!r.summary||!r.imageUrl)throw{errMsg:"shareDirected(web): title/summary/imageUrl 必填",code:"PARAM_MISSING"}}if(e==="image"&&!r.imageUrl)throw{errMsg:"shareDirected(image): payload.imageUrl 必填",code:"PARAM_MISSING"};if(e==="text"&&!r.text&&!r.summary)throw{errMsg:"shareDirected(text): payload.text 或 payload.summary 必填",code:"PARAM_MISSING"};return{kind:e,scene:n,payload:r,success:t.success,fail:t.fail,complete:t.complete}}function _n(t){return t.isWeixinMiniProgram?"已同步分享内容,请点击右上角“···”选择发送给朋友或分享到朋友圈。":"正在拉起微信分享面板,请选择聊天框或朋友圈。"}function Cn(t){return{type:"qsh_api_call",api:"shareDirected",params:{kind:t.kind,scene:t.scene,payload:t.payload},timestamp:Date.now()}}function On(t){const e=typeof window!="undefined"&&window.wx&&window.wx.miniProgram;if(!e||typeof e.postMessage!="function")throw{errMsg:"当前微信小程序容器未注入 postMessage 能力,无法发起 shareDirected",code:"MINIPROGRAM_BRIDGE_UNAVAILABLE"};e.postMessage({data:[t]})}function Et(t={}){return u.safeExecute(()=>{var i,s,c,h,g,P,v;let e;try{e=An(t)}catch(p){return(i=t.fail)==null||i.call(t,p),Promise.reject(p)}const r=se(!0),n=_n(r);if(r.isWeixinMiniProgram)try{On(Cn(e));const p={success:!0,hint:n};return(s=e.success)==null||s.call(e,p),(c=e.complete)==null||c.call(e,p),Promise.resolve(p)}catch(p){return(h=e.fail)==null||h.call(e,p),(g=e.complete)==null||g.call(e,p),Promise.reject(p)}if(r.type==="h5"&&!r.isUniAppWebView&&!r.isOfflineWebview){const p={errMsg:"当前页面不在宿主 WebView 中,无法分享。请在 unified-platform-app 内打开该 H5 再重试。",code:"NOT_IN_CONTAINER"};return(P=e.fail)==null||P.call(e,p),(v=e.complete)==null||v.call(e,p),Promise.reject(p)}return new Promise((p,ye)=>{N("shareDirected",{kind:e.kind,scene:e.scene,payload:e.payload},{success:Ie=>{var Ae,$t;const fe=w(d({},Ie),{hint:n});(Ae=e.success)==null||Ae.call(e,fe),($t=e.complete)==null||$t.call(e,fe),p(fe)},fail:Ie=>{var fe,Ae;(fe=e.fail)==null||fe.call(e,Ie),(Ae=e.complete)==null||Ae.call(e,Ie),ye(Ie)}})})},{context:"shareDirected",options:t})}function Pn(t={}){return new Promise((e,r)=>{Et(w(d({},t),{success:e,fail:r}))})}const Rn={OFF:"off",ON:"on",UNAVAILABLE:"unavailable",UNAUTHORIZED:"unauthorized"},Nn={allowDuplicatesKey:!1,services:[]};function Ne(t={}){return d(d({},Nn),t)}function Ee(){return["weixin","webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function Mn(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}Z()||(a.info("等待微信配置完成"),yield z()),wx.openBluetoothAdapter({success:()=>{a.info("微信蓝牙适配器已打开"),yt(t)},fail:r=>{var n;a.error("蓝牙适配器打开失败",r),(n=t.fail)==null||n.call(t,r)}})}),{context:"openBluetoothAdapterInWeixin"})}function Sn(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用蓝牙功能",t),N("bluetooth",t,{success:e=>{var r;a.info("UniApp 蓝牙调用成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("UniApp 蓝牙调用失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"bluetoothInUniApp"})}function Tn(t){return u.safeExecute(()=>{var e;a.debug("通过 WebView 桥接调用蓝牙设备搜索功能",t),N("bluetoothDevicesDiscovery",{action:"startBluetoothDevicesDiscovery",params:{services:t.services||[],allowDuplicatesKey:(e=t.allowDuplicatesKey)!=null?e:!1}},{success:r=>{var n;console.log("[Bluetooth] 设备开启搜索成功:",r),a.info("UniApp 蓝牙设备开启搜索成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 设备开启搜索失败:",r),a.error("UniApp 蓝牙设备开启搜索失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"startBluetoothDevicesDiscoveryInUniApp"})}const Me=new Set;function vn(t,e={}){return u.safeExecute(()=>{var r;return Me.add(t),Me.size===1&&N("onBluetoothDeviceFound",{action:"onBluetoothDeviceFound",isPersistent:!0,params:{services:e.services||[],allowDuplicatesKey:(r=e.allowDuplicatesKey)!=null?r:!1}},{success:n=>{Me.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}),()=>Me.delete(t)},{context:"qsh_onBluetoothDeviceFound"})}function Ln(t){return u.safeExecute(()=>{var e;a.debug("通过 WebView 桥接调用蓝牙连接功能",t),N("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),a.info("UniApp 蓝牙连接成功",r),(n=t.success)==null||n.call(t,r)},fail:r=>{var n;console.error("[Bluetooth] 蓝牙连接失败:",r),a.error("UniApp 蓝牙连接失败",r),(n=t.fail)==null||n.call(t,r)},complete:t.complete})},{context:"createBLEConnectionInUniApp"})}function bn(t={}){return u.safeExecute(()=>{var r;if(!Ee()){const n={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持蓝牙",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=Ne(t);a.info("开始蓝牙操作",{platform:l.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),m()?Mn(e):Sn(e)},{context:"openBluetoothAdapter",options:t})}function xn(t={}){return u.safeExecute(()=>{var r,n;if(!Ee()){const i={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持蓝牙",{platform:l.type}),(r=t.fail)==null||r.call(t,i),(n=t.complete)==null||n.call(t,i);return}const e=Ne(t);a.info("开始搜索蓝牙设备",{platform:l.type,services:e.services,allowDuplicatesKey:e.allowDuplicatesKey}),m()?startBluetoothDevicesDiscoveryInWeixin(e):Tn(e)},{context:"startBluetoothDevicesDiscovery",options:t})}function yt(t,e={}){return u.safeExecute(()=>{var n,i;if(!Ee()){const s={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持蓝牙",{platform:l.type}),(n=e.fail)==null||n.call(e,s),(i=e.complete)==null||i.call(e,s);return}const r=Ne(e);a.info("注册蓝牙设备发现监听",{platform:l.type}),m()?onBluetoothDeviceFoundInWeixin(r):vn(t,r)},{context:"onBluetoothDeviceFound",options:e})}function Dn(t={}){return u.safeExecute(()=>{var s,c,h,g;if(!Ee()){const P={errMsg:`当前环境 (${l.type}) 不支持蓝牙功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持蓝牙连接",{platform:l.type}),(s=t.fail)==null||s.call(t,P),(c=t.complete)==null||c.call(t,P);return}const e=Ne(t),{name:r,deviceId:n,autoConnect:i=!1}=e;if(!n){const P={errMsg:"缺少 deviceId 参数",code:"INVALID_PARAMS"};(h=t.fail)==null||h.call(t,P),(g=t.complete)==null||g.call(t,P);return}a.info("创建蓝牙连接",{deviceId:n,autoConnect:i,platform:l.type}),m()?uni.createBLEConnection({deviceId:n,autoConnect:i,success:t.success,fail:t.fail,complete:t.complete}):Ln(e)},{context:"createBLEConnection",options:t})}function Un(){return{supported:Ee(),environment:l.type,implementation:m()?"weixin":"webview",features:{discovery:!0,connect:!0,readWrite:!0,notify:!0,asyncSupport:!0}}}const Wn={};function $n(t={}){return d(d({},Wn),t)}function It(){return["webview","UniApp","plus","nvue","uvue","offline"].includes(l.type)}function Fn(t){return u.safeExecute(()=>{a.debug("通过 WebView 桥接调用打印PDF",t),N("printPdf",w(d({},t),{isPersistent:!0}),{success:e=>{var r;a.info("UniApp 打印PDF成功",e),(r=t.success)==null||r.call(t,e)},fail:e=>{var r;a.error("UniApp 打印PDF失败",e),(r=t.fail)==null||r.call(t,e)},complete:t.complete})},{context:"printPdfInUniApp",platform:"uniapp"})}function Bn(t={}){return u.safeExecute(()=>{var r;if(!It()){const n={errMsg:`当前环境 (${l.type}) 不支持打印PDF功能`,code:"PLATFORM_NOT_SUPPORTED"};a.error("平台不支持打印PDF",{platform:l.type}),(r=t.fail)==null||r.call(t,n);return}const e=$n(t);a.info("开始打印PDF",{platform:l.type}),Fn(e)},{context:"printPdf",options:t})}function kn(){return{supported:It(),environment:l.type,implementation:"uniapp",features:{asyncSupport:!0}}}const xe="/pages/face/index";function Gn(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 At(){return m()}function Kn(){return typeof window!="undefined"&&window.wx&&window.wx.miniProgram&&typeof window.wx.miniProgram.navigateTo=="function"}function zn(t){const e=w(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 Vn(t){return u.safeExecute(()=>{if(!Kn()){a.error("微信小程序导航API不可用");return}const e=zn(t);a.debug("跳转宿主人脸识别页面",{name:t.name,targetUrl:e}),window.wx.miniProgram.navigateTo({url:e,success:()=>{a.info("已跳转到宿主人脸识别页面",{targetUrl:e})},fail:r=>{a.error("跳转宿主人脸识别页面失败",r)}})},{context:"faceVerifyInWeixin",platform:"weixin"})}function qn(t={}){return u.safeExecute(()=>{if(!At()){a.error("平台不支持人脸识别",{platform:l.type});return}let e;try{e=Gn(t)}catch(r){a.error("人脸识别参数校验失败",r);return}a.info("开始人脸识别",{platform:l.type,name:e.name,pagePath:xe}),Vn(e)},{context:"faceVerify",options:t})}function Jn(){return{supported:At(),environment:l.type,implementation:"weixin",features:{asyncSupport:!0,hostPageNavigation:!0}}}const _t=se();function jn(){if(typeof window=="undefined"||!se(!0).isWeixinMiniProgram)return!1;const e=ve().getRuntimeConfig();return typeof e.clientId=="string"&&e.clientId.length>0}function Hn(){return I(this,null,function*(){yield jt(),jn()&&(yield z())})}X.useResponse(Xe.response,{priority:1e3});let Ct=!1;function Ot(){if(Ct)return;Ct=!0,mr([{name:"load-weixin-sdk",run:qe,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(Ot,0):document.addEventListener("DOMContentLoaded",Ot));function A(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"),s=r&&typeof r=="object"?r:{},c=()=>i?t(s,...n):new Promise((g,P)=>{const v=w(d({},s),{success:p=>{typeof s.success=="function"&&s.success(p),g(p)},fail:p=>{typeof s.fail=="function"&&s.fail(p),P(p)},complete:s.complete});t(v,...n)});return(typeof window=="undefined"?Promise.resolve():Ke()).then(()=>c()).catch(g=>{throw console.error(`[QSH-SDK] ${e||"API"} call failed:`,g),g})}}function Se(t){return typeof t=="function"?{success:t}:t&&typeof t=="object"?t:{}}const Pt=A(Cr),Rt=A(Or),Nt=A(Pr),Mt=A(Rr),St=A(Nr),Tt=A(Mr);function vt(t){const e=()=>Sr(t);return(typeof window=="undefined"?Promise.resolve():Ke()).then(()=>e())}const De=A(Dr,{apiName:"getCode"});function Yn(t={}){return new Promise((e,r)=>{De(w(d({},t),{success:e,fail:r}))})}const Ue=A(Br,{apiName:"navigateToMiniProgram"});function Zn(t={}){return new Promise((e,r)=>{Ue(w(d({},t),{success:e,fail:r}))})}const We=A(zr);function Xn(t={}){return new Promise((e,r)=>{We(w(d({},t),{success:e,fail:r}))})}const Lt=A(Bn);function Qn(t={}){return new Promise((e,r)=>{Lt(w(d({},t),{success:e,fail:r}))})}const $e=A(Yr),ei=A(qn);function ti(t={}){return new Promise((e,r)=>{$e(w(d({},t),{success:e,fail:r}))})}const ri=A(Et,{apiName:"shareDirected"}),ni=A(Pn,{apiName:"shareDirectedAsync"}),Fe=A(sn);function ii(t={}){return new Promise((e,r)=>{Fe(w(d({},t),{success:e,fail:r}))})}const Be=A(on);function ai(t={}){return new Promise((e,r)=>{Be(w(d({},t),{success:e,fail:r}))})}const ke=A(En);function si(t={}){return new Promise((e,r)=>{ke(w(d({},t),{success:e,fail:r}))})}const bt=A(bn);function oi(t={}){return new Promise((e,r)=>{bt(w(d({},t),{success:e,fail:r}))})}const xt=A(xn);function ci(t={}){return new Promise((e,r)=>{xt(w(d({},t),{success:e,fail:r}))})}const Dt=A(yt);function ui(t={}){return new Promise((e,r)=>{Dt(w(d({},t),{success:e,fail:r}))})}const Ut=A(Dn);function li(t={}){return new Promise((e,r)=>{Ut(w(d({},t),{success:e,fail:r}))})}const re={navigateTo:Pt,navigateBack:Rt,switchTab:Nt,reLaunch:Mt,redirectTo:St,postMessage:Tt,getEnv:vt,getCode:De,getCodeAsync:Yn,navigateToMiniProgram:Ue,navigateToMiniProgramAsync:Zn,chooseImage:We,chooseImageAsync:Xn,scanCode:$e,scanCodeAsync:ti,getLocation:Fe,getLocationAsync:ii,openLocation:Be,openLocationAsync:ai,chooseLocation:ke,chooseLocationAsync:si,onLocationChange:t=>A((e={})=>fn(e.success),{apiName:"onLocationChange"})(Se(t)),offLocationChange:t=>A((e={})=>dn(e.success),{apiName:"offLocationChange"})(Se(t)),onLocationChangeError:t=>A((e={})=>gn(e.success),{apiName:"onLocationChangeError"})(Se(t)),offLocationChangeError:t=>A((e={})=>hn(e.success),{apiName:"offLocationChangeError"})(Se(t)),startLocationUpdate:A(un,{apiName:"startLocationUpdate"}),stopLocationUpdate:A(ln,{apiName:"stopLocationUpdate"}),environment:_t,ready:Hn,init:ze,isReady:Gt,getState:Kt,config:Je,weixin:{config:Je,waitForConfig:z,isConfigReady:Z,getConfigState:Qt,retryConfig:er},webView:null,ImageSourceTypes:Pe,ImageSizeTypes:Re,getImageCapabilities:Vr,ScanTypes:te,getScanCapabilities:Zr,CoordinateTypes:le,getLocationCapabilities:cn,getChooseLocationCapabilities:yn,openBluetoothAdapter:bt,openBluetoothAdapterAsync:oi,startBluetoothDevicesDiscovery:xt,startBluetoothDevicesDiscoveryAsync:ci,onBluetoothDeviceFound:Dt,onBluetoothDeviceFoundAsync:ui,createBLEConnection:Ut,createBLEConnectionAsync:li,BluetoothStates:Rn,shareDirected:ri,shareDirectedAsync:ni,getBluetoothCapabilities:Un,printPdf:Lt,printPdfAsync:Qn,getPrintCapabilities:kn,faceVerify:ei,getFaceCapabilities:Jn,plugins:{manager:he,register:t=>he.register(t),install:t=>he.install(t,re),list:()=>he.getPluginList()},interceptors:{chain:X,useRequest:(t,e)=>X.useRequest(t,e),useResponse:(t,e)=>X.useResponse(t,e),builtin:{logging:nr,performance:V,createRetry:ir,createValidation:ar,errorNormalizer:Xe}},metrics:{getPerformanceReport:()=>V.getReport(),clearPerformanceMetrics:()=>V.clearMetrics()},errors:{codes:o,messages:Le,categories:F,normalize:Ze,create:dr,isStandard:gr},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:L,setLogReporter:t=>L.setReporter(t),errorHandler:u,stateManager:Y,enableDevMode:()=>L.enableDevMode(),getLogs:t=>L.getHistory(t),getStats:()=>({logger:L.getStats(),state:Y.getStats(),weixinConfig:ve().getStats(),plugins:he.getStats(),interceptors:X.getStats(),store:k.getStats()}),getWeixinConfigManager:ve,exportDebugInfo:()=>L.exportToJSON()}};_t.isWeixinMiniProgram?re.webView=window.wx&&window.wx.miniProgram:re.webView={navigateTo:Pt,navigateBack:Rt,switchTab:Nt,reLaunch:Mt,redirectTo:St,postMessage:Tt,getEnv:vt,getCode:De,navigateToMiniProgram:Ue,chooseImage:We,scanCode:$e,getLocation:Fe,openLocation:Be,chooseLocation:ke};const Wt=typeof window.uni!="undefined"?window.uni:{};return Object.keys(Wt).forEach(t=>{re.hasOwnProperty(t)||(re[t]=Wt[t])}),typeof window!="undefined"&&(window.qsh=re),re});
2
2
  //# sourceMappingURL=qsh-webview-sdk.umd.js.map