diff --git a/packages/uni-app-plus/dist/automator.js b/packages/uni-app-plus/dist/automator.js index 2d70b5824e1d0292d2a1dfec39959c849adbfb88..773906880c5a1e8c95ee18b0e7fce11d3a5fdd42 100644 --- a/packages/uni-app-plus/dist/automator.js +++ b/packages/uni-app-plus/dist/automator.js @@ -12,4 +12,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -var __assign=function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i0)return firstSocketTaskEmitter(__assign({method:method.replace("Socket","")},args[0])).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}));if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}else(id=args[0].id,url=args[0].url,new Promise((function(resolve,reject){var socketTask=uni.connectSocket({url:url,success:function(){resolve({result:{errMsg:"connectSocket:ok"}})},fail:function(){reject({result:{errMsg:"connectSocket:fail"}})}});socketInstanceMap.set(id,{instance:socketTask,isOpend:!1}),socketTask.onOpen((function(data){socketInstanceMap.get(id).isOpend=!0,socketInstanceMap.get(id).openData=data}))}))).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}))}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(var args=[],_i=0;_i"+formatHTML(toHTML(node,"inner"))+"":formatHTML(node.toString()):formatHTML(node.pureChildren.map((function(child){return child.toString()})).join(""))}var FUNCTIONS={input:{input:function(el,value){el.setValue(value)}},textarea:{input:function(el,value){el.setValue(value)}},"scroll-view":{scrollTo:function(el,x,y){el.scrollTo(y)},scrollTop:function(el){return 0},scrollLeft:function(el){return 0},scrollWidth:function(el){return 0},scrollHeight:function(el){return 0}},swiper:{swipeTo:function(el,index){el.__vue__.current=index}},"movable-view":{moveTo:function(el,x,y){var vm=el.__vue__;vm.x=x,vm.y=y}},switch:{tap:function(el){var vm=el.__vue__;vm.checked=!vm.checked}},slider:{slideTo:function(el,value){el.__vue__.value=value}}};function getRoot(pageId){return getDocument(pageId).body}var NativeAdapter={getWindow:function(pageId){return getRoot(pageId)},getDocument:function(pageId){return getRoot(pageId)},getEl:function(elementId,pageId){var element=getDocument(pageId).getRef(elementId);if(!element)throw Error("element destroyed");return element},getOffset:function(node){var weex=node.__$weex__||node.ownerDocument.__$weex__;return new Promise((function(resolve){weex.requireModule("dom").getComponentRect(node.ref,(function(res){res.result?resolve({left:res.size.left,top:res.size.top}):resolve({left:0,top:0})}))}))},querySelector:function(context,selector){return Promise.resolve(transEl(querySelector(context,selector)))},querySelectorAll:function(context,selector){return Promise.resolve({elements:querySelector(context,selector,[]).map((function(el){return transEl(el)}))})},queryProperties:function(context,names){var options=DOM_PROPERTIES.find((function(options){return options.test(names,context)}));return options?options.call(context).then((function(properties){return{properties:properties}})):Promise.resolve({properties:names.map((function(name){return getDataByPath(context,name)}))})},queryAttributes:function(context,names){var attr=context.attr;return Promise.resolve({attributes:names.map((function(name){return"class"===name?(context.classList||[]).join(" "):String(attr[name]||attr[camelize(name)]||"")}))})},queryStyles:function(context,names){var style=context.style;return Promise.resolve({styles:names.map((function(name){return style[name]}))})},queryHTML:function(context,type){return Promise.resolve({html:toHTML(context,type)})},dispatchTapEvent:function(el){return el.fireEvent("click",{timeStamp:Date.now(),target:el,currentTarget:el},!0),Promise.resolve()},dispatchLongpressEvent:function(el){return el.fireEvent("longpress",{timeStamp:Date.now(),target:el,currentTarget:el},!0),Promise.resolve()},dispatchTouchEvent:function(el,type,eventInitDict){return eventInitDict||(eventInitDict={}),eventInitDict.touches||(eventInitDict.touches=[]),eventInitDict.changedTouches||(eventInitDict.changedTouches=[]),eventInitDict.touches.length||eventInitDict.touches.push({identifier:Date.now(),target:el}),el.fireEvent(type,Object.assign({timeStamp:Date.now(),target:el,currentTarget:el},eventInitDict),!0),Promise.resolve()},callFunction:function(el,functionName,args){var fn=getDataByPath(FUNCTIONS,functionName);return fn?Promise.resolve({result:fn.apply(null,__spreadArrays([el],args))}):Promise.reject(Error(functionName+" not exists"))},triggerEvent:function(el,type,detail){var vm=el.__vue__;return vm?vm.$trigger&&vm.$trigger(type,{},detail):el.fireEvent(type,{timeStamp:Date.now(),target:el,currentTarget:el},!1,{params:[{detail:detail}]}),Promise.resolve()}};function initNativeApi(){return Object.assign({},function(adapter){return{"Page.getElement":function(params){return adapter.querySelector(adapter.getDocument(params.pageId),params.selector)},"Page.getElements":function(params){return adapter.querySelectorAll(adapter.getDocument(params.pageId),params.selector)},"Page.getWindowProperties":function(params){return adapter.queryProperties(adapter.getWindow(params.pageId),params.names)}}}(NativeAdapter),function(adapter){var getEl=function(params){return adapter.getEl(params.elementId,params.pageId)};return{"Element.getElement":function(params){return adapter.querySelector(getEl(params),params.selector)},"Element.getElements":function(params){return adapter.querySelectorAll(getEl(params),params.selector)},"Element.getDOMProperties":function(params){return adapter.queryProperties(getEl(params),params.names)},"Element.getProperties":function(params){var el=getEl(params),ctx=el.__vue__||el.attr||{};return el.__vueParentComponent&&(ctx=Object.assign({},ctx,el.__vueParentComponent.attrs,el.__vueParentComponent.props)),adapter.queryProperties(ctx,params.names)},"Element.getOffset":function(params){return adapter.getOffset(getEl(params))},"Element.getAttributes":function(params){return adapter.queryAttributes(getEl(params),params.names)},"Element.getStyles":function(params){return adapter.queryStyles(getEl(params),params.names)},"Element.getHTML":function(params){return adapter.queryHTML(getEl(params),params.type)},"Element.tap":function(params){return adapter.dispatchTapEvent(getEl(params))},"Element.longpress":function(params){return adapter.dispatchLongpressEvent(getEl(params))},"Element.touchstart":function(params){return adapter.dispatchTouchEvent(getEl(params),"touchstart",params)},"Element.touchmove":function(params){return adapter.dispatchTouchEvent(getEl(params),"touchmove",params)},"Element.touchend":function(params){return adapter.dispatchTouchEvent(getEl(params),"touchend",params)},"Element.callFunction":function(params){return adapter.callFunction(getEl(params),params.functionName,params.args)},"Element.triggerEvent":function(params){return adapter.triggerEvent(getEl(params),params.type,params.detail)}}}(NativeAdapter))}var E=function(){};E.prototype={on:function(name,callback,ctx){var e=this.e||(this.e={});return(e[name]||(e[name]=[])).push({fn:callback,ctx:ctx}),this},once:function(name,callback,ctx){var self=this;function listener(){self.off(name,listener),callback.apply(ctx,arguments)}return listener._=callback,this.on(name,listener,ctx)},emit:function(name){for(var data=[].slice.call(arguments,1),evtArr=((this.e||(this.e={}))[name]||[]).slice(),i=0,len=evtArr.length;i=0;i--)if(evts[i].fn===callback||evts[i].fn._===callback){evts.splice(i,1);break}liveEvents=evts}return liveEvents.length?e[name]=liveEvents:delete e[name],this}};var Emitter=E;function initBridge(subscribeNamespace){var emitter=new Emitter;return{subscribe:function(event,callback,once){void 0===once&&(once=!1),emitter[once?"once":"on"](subscribeNamespace+"."+event,callback)},subscribeHandler:function(event,args,pageId){emitter.emit(subscribeNamespace+"."+event,args,pageId)}}}var extend=Object.assign,UniXServiceJSBridge=extend(initBridge("service"),{publishHandler:function(event,args,pageId){UniViewJSBridge.subscribeHandler(event,args,pageId)}}),UniXViewJSBridge=extend(initBridge("view"),{publishHandler:function(event,args,pageId){UniServiceJSBridge.subscribeHandler(event,args,pageId)}});if("undefined"==typeof UniServiceJSBridge&&"undefined"==typeof UniViewJSBridge){var __global__="undefined"==typeof globalThis?Function("return this")():globalThis;__global__.UniServiceJSBridge=UniXServiceJSBridge,__global__.UniViewJSBridge=UniXViewJSBridge}var Api={};Object.keys(App$1).forEach((function(method){Api["App."+method]=App$1[method]})),Object.keys(Page$1).forEach((function(method){Api["Page."+method]=Page$1[method]})),Object.keys(Element$1).forEach((function(method){Api["Element."+method]=Element$1[method]}));var NVueApi,fallback,socketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function send(data){socketTask.send({data:JSON.stringify(data)})}function onMessage(res){var _a=JSON.parse(res.data),id=_a.id,method=_a.method,params=_a.params,data={id:id},fn=Api[method];if(!fn){if(fallback){var result=fallback(id,method,params,data);if(!0===result)return;fn=result}if(!fn)return data.error={message:method+" unimplemented"},send(data)}try{fn(params,send).then((function(res){res&&(data.result=res)})).catch((function(err){data.error={message:err.message}})).finally((function(){send(data)}))}catch(err){data.error={message:err.message},send(data)}}fallback=function(id,method,params,data){var pageId=params.pageId,page=function(pageId){var pages=getCurrentPages();if(!pageId)return pages[pages.length-1];return pages.find((function(page){return page.$page.id===pageId}))}(pageId);return page?!page.$page.meta.isNVue?(UniServiceJSBridge.publishHandler("sendAutoMessage",{id:id,method:method,params:params},pageId),!0):(NVueApi||(NVueApi=initNativeApi()),NVueApi[method]):(data.error={message:"page["+pageId+"] not exists"},send(data),!0)},UniServiceJSBridge.subscribe("onAutoMessageReceive",(function(res){send(res)})),setTimeout((function(){if("undefined"!=typeof window&&(window.__uniapp_x_||window.__uniapp_x_postMessage))!function(data,callback){var _a,id=0;callback&&(id=postMessageId++,postMessageCallbacks[id]=callback);var message={data:{id:id,type:"automator",data:data}};console.log("postMessageToUniXWebView",message),(null===(_a=null===window||void 0===window?void 0:window.__uniapp_x_)||void 0===_a?void 0:_a.postMessage)?window.__uniapp_x_.postMessage(JSON.stringify(message)):(null===window||void 0===window?void 0:window.__uniapp_x_postMessage)&&window.__uniapp_x_postMessage({data:message})}({action:"ready"});else{if(wsEndpoint&&wsEndpoint.endsWith(":0000"))return;void 0===options&&(options={}),(socketTask=uni.connectSocket({url:options.wsEndpoint||wsEndpoint,complete:function(){}})).onMessage(onMessage),socketTask.onOpen((function(res){options.success&&options.success(),console.log("已开启自动化测试...")})),socketTask.onError((function(res){console.log("automator.onError",res)})),socketTask.onClose((function(){options.fail&&options.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))}var options}),500);export{send}; +var __assign=function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i0)return firstSocketTaskEmitter(__assign({method:method.replace("Socket","")},args[0])).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}));if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}else(id=args[0].id,url=args[0].url,new Promise((function(resolve,reject){var socketTask=uni.connectSocket({url:url,success:function(){resolve({result:{errMsg:"connectSocket:ok"}})},fail:function(){reject({result:{errMsg:"connectSocket:fail"}})}});socketInstanceMap.set(id,{instance:socketTask,isOpend:!1}),socketTask.onOpen((function(data){socketInstanceMap.get(id).isOpend=!0,socketInstanceMap.get(id).openData=data}))}))).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}))}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(var args=[],_i=0;_i"+formatHTML(toHTML(node,"inner"))+"":formatHTML(node.toString()):formatHTML(node.pureChildren.map((function(child){return child.toString()})).join(""))}var FUNCTIONS={input:{input:function(el,value){el.setValue(value)}},textarea:{input:function(el,value){el.setValue(value)}},"scroll-view":{scrollTo:function(el,x,y){el.scrollTo(y)},scrollTop:function(el){return 0},scrollLeft:function(el){return 0},scrollWidth:function(el){return 0},scrollHeight:function(el){return 0}},swiper:{swipeTo:function(el,index){el.__vue__.current=index}},"movable-view":{moveTo:function(el,x,y){var vm=el.__vue__;vm.x=x,vm.y=y}},switch:{tap:function(el){var vm=el.__vue__;vm.checked=!vm.checked}},slider:{slideTo:function(el,value){el.__vue__.value=value}}};function getRoot(pageId){return getDocument(pageId).body}var NativeAdapter={getWindow:function(pageId){return getRoot(pageId)},getDocument:function(pageId){return getRoot(pageId)},getEl:function(elementId,pageId){var element=getDocument(pageId).getRef(elementId);if(!element)throw Error("element destroyed");return element},getOffset:function(node){var weex=node.__$weex__||node.ownerDocument.__$weex__;return new Promise((function(resolve){weex.requireModule("dom").getComponentRect(node.ref,(function(res){res.result?resolve({left:res.size.left,top:res.size.top}):resolve({left:0,top:0})}))}))},querySelector:function(context,selector){return Promise.resolve(transEl(querySelector(context,selector)))},querySelectorAll:function(context,selector){return Promise.resolve({elements:querySelector(context,selector,[]).map((function(el){return transEl(el)}))})},queryProperties:function(context,names){var options=DOM_PROPERTIES.find((function(options){return options.test(names,context)}));return options?options.call(context).then((function(properties){return{properties:properties}})):Promise.resolve({properties:names.map((function(name){return getDataByPath(context,name)}))})},queryAttributes:function(context,names){var attr=context.attr;return Promise.resolve({attributes:names.map((function(name){return"class"===name?(context.classList||[]).join(" "):String(attr[name]||attr[camelize(name)]||"")}))})},queryStyles:function(context,names){var style=context.style;return Promise.resolve({styles:names.map((function(name){return style[name]}))})},queryHTML:function(context,type){return Promise.resolve({html:toHTML(context,type)})},dispatchTapEvent:function(el){return el.fireEvent("click",{timeStamp:Date.now(),target:el,currentTarget:el},!0),Promise.resolve()},dispatchLongpressEvent:function(el){return el.fireEvent("longpress",{timeStamp:Date.now(),target:el,currentTarget:el},!0),Promise.resolve()},dispatchTouchEvent:function(el,type,eventInitDict){return eventInitDict||(eventInitDict={}),eventInitDict.touches||(eventInitDict.touches=[]),eventInitDict.changedTouches||(eventInitDict.changedTouches=[]),eventInitDict.touches.length||eventInitDict.touches.push({identifier:Date.now(),target:el}),el.fireEvent(type,Object.assign({timeStamp:Date.now(),target:el,currentTarget:el},eventInitDict),!0),Promise.resolve()},callFunction:function(el,functionName,args){var fn=getDataByPath(FUNCTIONS,functionName);return fn?Promise.resolve({result:fn.apply(null,__spreadArrays([el],args))}):Promise.reject(Error(functionName+" not exists"))},triggerEvent:function(el,type,detail){var vm=el.__vue__;return vm?vm.$trigger&&vm.$trigger(type,{},detail):el.fireEvent(type,{timeStamp:Date.now(),target:el,currentTarget:el},!1,{params:[{detail:detail}]}),Promise.resolve()}};function initNativeApi(){return Object.assign({},function(adapter){return{"Page.getElement":function(params){return adapter.querySelector(adapter.getDocument(params.pageId),params.selector)},"Page.getElements":function(params){return adapter.querySelectorAll(adapter.getDocument(params.pageId),params.selector)},"Page.getWindowProperties":function(params){return adapter.queryProperties(adapter.getWindow(params.pageId),params.names)}}}(NativeAdapter),function(adapter){var getEl=function(params){return adapter.getEl(params.elementId,params.pageId)};return{"Element.getElement":function(params){return adapter.querySelector(getEl(params),params.selector)},"Element.getElements":function(params){return adapter.querySelectorAll(getEl(params),params.selector)},"Element.getDOMProperties":function(params){return adapter.queryProperties(getEl(params),params.names)},"Element.getProperties":function(params){var el=getEl(params),ctx=el.__vue__||el.attr||{};return el.__vueParentComponent&&(ctx=Object.assign({},ctx,el.__vueParentComponent.attrs,el.__vueParentComponent.props)),adapter.queryProperties(ctx,params.names)},"Element.getOffset":function(params){return adapter.getOffset(getEl(params))},"Element.getAttributes":function(params){return adapter.queryAttributes(getEl(params),params.names)},"Element.getStyles":function(params){return adapter.queryStyles(getEl(params),params.names)},"Element.getHTML":function(params){return adapter.queryHTML(getEl(params),params.type)},"Element.tap":function(params){return adapter.dispatchTapEvent(getEl(params))},"Element.longpress":function(params){return adapter.dispatchLongpressEvent(getEl(params))},"Element.touchstart":function(params){return adapter.dispatchTouchEvent(getEl(params),"touchstart",params)},"Element.touchmove":function(params){return adapter.dispatchTouchEvent(getEl(params),"touchmove",params)},"Element.touchend":function(params){return adapter.dispatchTouchEvent(getEl(params),"touchend",params)},"Element.callFunction":function(params){return adapter.callFunction(getEl(params),params.functionName,params.args)},"Element.triggerEvent":function(params){return adapter.triggerEvent(getEl(params),params.type,params.detail)}}}(NativeAdapter))}var E=function(){};E.prototype={on:function(name,callback,ctx){var e=this.e||(this.e={});return(e[name]||(e[name]=[])).push({fn:callback,ctx:ctx}),this},once:function(name,callback,ctx){var self=this;function listener(){self.off(name,listener),callback.apply(ctx,arguments)}return listener._=callback,this.on(name,listener,ctx)},emit:function(name){for(var data=[].slice.call(arguments,1),evtArr=((this.e||(this.e={}))[name]||[]).slice(),i=0,len=evtArr.length;i=0;i--)if(evts[i].fn===callback||evts[i].fn._===callback){evts.splice(i,1);break}liveEvents=evts}return liveEvents.length?e[name]=liveEvents:delete e[name],this}};var Emitter=E;function initBridge(subscribeNamespace){var emitter=new Emitter;return{subscribe:function(event,callback,once){void 0===once&&(once=!1),emitter[once?"once":"on"](subscribeNamespace+"."+event,callback)},subscribeHandler:function(event,args,pageId){emitter.emit(subscribeNamespace+"."+event,args,pageId)}}}var extend=Object.assign,UniXServiceJSBridge=extend(initBridge("service"),{publishHandler:function(event,args,pageId){UniViewJSBridge.subscribeHandler(event,args,pageId)}}),UniXViewJSBridge=extend(initBridge("view"),{publishHandler:function(event,args,pageId){UniServiceJSBridge.subscribeHandler(event,args,pageId)}});if("undefined"==typeof UniServiceJSBridge&&"undefined"==typeof UniViewJSBridge){var __global__="undefined"==typeof globalThis?Function("return this")():globalThis;__global__.UniServiceJSBridge=UniXServiceJSBridge,__global__.UniViewJSBridge=UniXViewJSBridge}var Api={};Object.keys(App$1).forEach((function(method){Api["App."+method]=App$1[method]})),Object.keys(Page$1).forEach((function(method){Api["Page."+method]=Page$1[method]})),Object.keys(Element$1).forEach((function(method){Api["Element."+method]=Element$1[method]}));var NVueApi,fallback,socketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function send(data){socketTask.send({data:JSON.stringify(data)})}function onMessage(res){var _a=JSON.parse(res.data),id=_a.id,method=_a.method,params=_a.params,data={id:id},fn=Api[method];if(!fn){if(fallback){var result=fallback(id,method,params,data);if(!0===result)return;fn=result}if(!fn)return data.error={message:method+" unimplemented"},send(data)}try{fn(params,send).then((function(res){res&&(data.result=res)})).catch((function(err){data.error={message:err.message}})).finally((function(){send(data)}))}catch(err){data.error={message:err.message},send(data)}}fallback=function(id,method,params,data){var pageId=params.pageId,page=function(pageId){var pages=getCurrentPages();if(!pageId)return pages[pages.length-1];return pages.find((function(page){return page.$page.id===pageId}))}(pageId);return page?!page.$page.meta.isNVue?(UniServiceJSBridge.publishHandler("sendAutoMessage",{id:id,method:method,params:params},pageId),!0):(NVueApi||(NVueApi=initNativeApi()),NVueApi[method]):(data.error={message:"page["+pageId+"] not exists"},send(data),!0)},UniServiceJSBridge.subscribe("onAutoMessageReceive",(function(res){send(res)})),setTimeout((function(){if("undefined"!=typeof window&&(window.__uniapp_x_||window.__uniapp_x_postMessage))!function(data,callback){var _a,id=0;callback&&(id=postMessageId++,postMessageCallbacks[id]=callback);var message={data:{id:id,type:"automator",data:data}};console.log("postMessageToUniXWebView",message),(null===(_a=null===window||void 0===window?void 0:window.__uniapp_x_)||void 0===_a?void 0:_a.postMessage)?window.__uniapp_x_.postMessage(JSON.stringify(message)):(null===window||void 0===window?void 0:window.__uniapp_x_postMessage)&&window.__uniapp_x_postMessage({data:message})}({action:"ready"});else{if(wsEndpoint&&wsEndpoint.endsWith(":0000"))return;void 0===options&&(options={}),(socketTask=uni.connectSocket({url:options.wsEndpoint||wsEndpoint,complete:function(){}})).onMessage(onMessage),socketTask.onOpen((function(res){options.success&&options.success(),console.log("已开启自动化测试...")})),socketTask.onError((function(res){console.log("automator.onError",res)})),socketTask.onClose((function(){options.fail&&options.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))}var options}),500);export{send}; diff --git a/packages/uni-app-plus/lib/uni.automator.js b/packages/uni-app-plus/lib/uni.automator.js index fb27cca3e0722465d9b78fc8e8107ace6ba9efd7..34ca6dbf461db493a6a79130c3d75fd066e032a0 100644 --- a/packages/uni-app-plus/lib/uni.automator.js +++ b/packages/uni-app-plus/lib/uni.automator.js @@ -1 +1 @@ -"use strict";var t=require("fs"),e=require("debug"),s=require("postcss-selector-parser"),a=require("fs-extra"),i=require("licia/dateFormat"),r=require("path"),o=require("util"),n=require("jimp"),l=require("dns");function c(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var d=c(t),u=c(e),h=c(s),p=c(a),m=c(i),y=c(r),f=c(n),v=c(l);function g(t){t.walk((t=>{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}}))}u.default("automator:devtool");const $=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const w=/^win/.test(process.platform);function M(t){try{return require(t)}catch(e){return require(require.resolve(t,{paths:[process.cwd()]}))}}const P=u.default("automator:launcher"),_=o.promisify(d.default.readdir),A=o.promisify(d.default.stat);async function E(t){const e=await _(t);return(await Promise.all(e.map((async e=>{const s=r.resolve(t,e);return(await A(s)).isDirectory()?E(s):s})))).reduce(((t,e)=>t.concat(e)),[])}class S{constructor(t){this.isX=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),this.id=t.id,this.app=t.executablePath,this.appid=t.appid||process.env.UNI_APP_ID||(this.isX?"__UNI__uniappx":"HBuilder"),this.package=t.package||(this.isX?"io.dcloud.uniappx":"io.dcloud.HBuilder"),this.activity=t.activity||(this.isX?"io.dcloud.uniapp.UniAppActivity":"io.dcloud.PandoraEntry")}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then((()=>(P(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1))).catch((()=>(P(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0)))}push(t){return E(t).then((e=>{const s=e.map((e=>{const s=(t=>w?t.replace(/\\/g,"/"):t)(r.join(this.DIR_WWW,r.relative(t,e)));return P(`${m.default("yyyy-mm-dd HH:MM:ss:l")} push ${e} ${s}`),this.pushFile(e,s)}));return Promise.all(s)})).then((t=>!0))}get FILE_APP_SERVICE(){return`${this.DIR_WWW}/app-service.js`}}const b=u.default("automator:simctl");function H(t){const e=parseInt(t);return e>9?String(e):"0"+e}class x extends S{constructor(){super(...arguments),this.bundleVersion=""}async init(){const t=M("node-simctl").Simctl;this.tool=new t({udid:this.id});try{await this.tool.bootDevice()}catch(t){}await this.initSDCard(),b(`${m.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const t=await this.tool.appInfo(this.package);b(`${m.default("yyyy-mm-dd HH:MM:ss:l")} appInfo ${t}`);const e=t.match(/DataContainer\s+=\s+"(.*)"/);if(!e)return Promise.resolve("");const s=t.match(/CFBundleVersion\s+=\s+(.*);/);if(!s)return Promise.resolve("");this.sdcard=e[1].replace("file:",""),this.bundleVersion=s[1],b(`${m.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.bundleVersion)}formatVersion(t){const e=t.split(".");return 3!==e.length?t:e[0]+H(e[1])+H(e[2])}async install(){return b(`${m.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),await this.tool.installApp(this.app),await this.tool.grantPermission(this.package,"all"),await this.initSDCard(),Promise.resolve(!0)}async start(){console.log("ios simulator start");try{await this.tool.terminateApp(this.package)}catch(t){console.error("ios simulator start terminateApp fail",t)}try{await this.tool.launchApp(this.package)}catch(t){console.error("ios simulator start launchApp fail",t),console.error(t)}return Promise.resolve(!0)}async exit(){return await this.tool.terminateApp(this.package),await this.tool.shutdownDevice(),Promise.resolve(!0)}async captureScreenshot(t){const e=await Promise.resolve(await this.tool.getScreenshot());return new Promise(((s,a)=>{var i,r;void 0!==(null===(i=null==t?void 0:t.area)||void 0===i?void 0:i.x)&&void 0!==(null===(r=null==t?void 0:t.area)||void 0===r?void 0:r.y)?f.default.read(Buffer.from(e,"base64")).then((e=>{const i=t.area.x,r=t.area.y;let o=e.bitmap.width-i;t.area.width&&(o=Math.min(o,t.area.width));let n=e.bitmap.height-r;t.area.height&&(n=Math.min(n,t.area.height)),e.crop(i,r,o,n).getBase64Async(f.default.MIME_PNG).then((t=>{s(t.replace("data:image/png;base64,",""))})).catch((t=>{a(t)}))})).catch((t=>{a(t)})):s(e)}))}exists(t){return p.default.existsSync(t)?Promise.resolve(!0):Promise.reject(Error(`${t} not exists`))}pushFile(t,e){return Promise.resolve(p.default.copySync(t,e))}adbCommand(t){return new Promise((t=>{t("adbCommand only for App Android!")}))}get DIR_WWW(){return"true"===process.env.UNI_APP_X?`${this.sdcard}/Documents/uni-app-x/apps/__UNI__uniappx/www/`:`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const I=M("adbkit"),N=u.default("automator:adb");class D extends S{constructor(){super(...arguments),this.needStart=!0}async init(){if(void 0!==v.default.setDefaultResultOrder&&v.default.setDefaultResultOrder("ipv4first"),this.tool=I.createClient(),N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} init ${await this.tool.version()}`),!this.id){const t=await this.tool.listDevices();if(!t.length)throw Error("Device not found");this.id=t[0].id}console.log("before echo ${$EXTERNAL_STORAGE}"),this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),console.log("after echo ${$EXTERNAL_STORAGE}",this.sdcard),N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}root(){return this.tool.root(this.id).then((()=>{N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${this.sdcard}`)})).catch((t=>{N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${t}`)}))}version(){return this.shell(this.COMMAND_VERSION).then((t=>{const e=t.match(/versionName=(.*)/);return e&&e.length>1?e[1]:""}))}formatVersion(t){return t}async install(){let t=!0;try{const e=(await this.tool.getProperties(this.id))["ro.build.version.release"].split(".")[0];parseInt(e)<6&&(t=!1)}catch(t){}if(N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${t}`),t){const t=M("adbkit/lib/adb/command.js"),e=t.prototype._send;t.prototype._send=function(t){return 0===t.indexOf("shell:pm install -r ")&&(t=t.replace("shell:pm install -r ","shell:pm install -r -g "),N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ${t} `)),e.call(this,t)}}return this.tool.install(this.id,this.app).then((()=>{N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} installed`),this.init()}))}start(){return this.needStart?this.exit().then((()=>this.shell(this.COMMAND_START))):Promise.resolve()}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(t){return this.tool.screencap(this.id).then((e=>new Promise(((s,a)=>{const i=[];e.on("data",(function(t){i.push(t)})),e.on("end",(function(){var e,r;void 0!==(null===(e=t.area)||void 0===e?void 0:e.x)&&void 0!==(null===(r=t.area)||void 0===r?void 0:r.y)?f.default.read(Buffer.concat(i)).then((e=>{var i,r,o,n;const l=t.area.x,c=t.area.y;let d=e.bitmap.width-l;(null===(i=t.area)||void 0===i?void 0:i.width)&&(d=Math.min(d,null===(r=t.area)||void 0===r?void 0:r.width));let u=e.bitmap.height-c;(null===(o=t.area)||void 0===o?void 0:o.height)&&(u=Math.min(u,null===(n=t.area)||void 0===n?void 0:n.height)),e.crop(l,c,d,u).getBase64Async(f.default.MIME_PNG).then((t=>{s(t.replace("data:image/png;base64,",""))})).catch((t=>{a(t)}))})).catch((t=>{a(t)})):s(Buffer.concat(i).toString("base64"))}))}))))}adbCommand(t){return new Promise((e=>{this.tool.shell(this.id,t).then((t=>{let s,a="";t.on("data",(t=>{a+=t.toString(),s&&clearTimeout(s),s=setTimeout((()=>{e(a)}),50)})),setTimeout((()=>{e(a)}),1500)}))}))}exists(t){return this.tool.stat(this.id,t)}pushFile(t,e){return this.tool.push(this.id,t,e)}async push(t){if(!process.env.UNI_HBUILDERX_PLUGINS)return super.push(t);const e=y.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher","out","export","pushResources.js"),s=process.env.HX_CONFIG_ADB_PATH||y.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher-tools","tools","adbs","adb"),a=[e,s].map((t=>d.default.promises.access(t,d.default.constants.F_OK).then((()=>`${t} exists`)).catch((()=>`${t} not exists`))));return Promise.all(a).then((()=>{const{PushResources:a}=require(e);return new a({adbPath:s,appid:this.appid,uuid:this.id,packageName:this.package,sourcePath:t}).start(),this.needStart=!1,!0})).catch((async e=>(console.log("pushResources or adb not exists: ",e),await super.push(t))))}shell(t){return N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.tool.shell(this.id,t).then(I.util.readAll).then((t=>{const e=t.toString();return N(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e}))}get DIR_WWW(){return`/storage/emulated/0/Android/data/${this.package}/apps/${this.appid}/www`}get COMMAND_EXTERNAL(){return"echo $EXTERNAL_STORAGE"}get COMMAND_VERSION(){return`dumpsys package ${this.package}`}get COMMAND_STOP(){return`am force-stop ${this.package}`}get COMMAND_START(){return`am start -n ${this.package}/${this.activity} --es appid ${this.appid} --ez needUpdateApp false --ez reload true --ez externalStorage true`}}const R=u.default("automator:devtool");let C,O=!1;const T={android:/android_version=(.*)/,ios:/iphone_version=(.*)/};const L={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>C.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshotWithDevice":{reflect:async(t,e)=>{const s=await C.captureScreenshot(e);return R(`App.captureScreenshot ${s.length}`),{data:s}}},"App.adbCommand":{reflect:async(t,e)=>{const s=await C.adbCommand(e);return R(`App.adbCommand ${s.length}`),{data:s}}}};!function(t){$.forEach((e=>{t[e]=function(t){return{reflect:async(e,s)=>e(t,s,!1),params:t=>(t.selector&&(t.selector=h.default(g).processSync(t.selector)),t)}}(e)}))}(L);const k={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,e){t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),C=function(t,e){return"ios"===t?new x(e):new D(e)}(t.platform,t),await C.init();const s=await C.version();if(s){if(t.version){const e=C.formatVersion(function(t,e){if(t.endsWith(".txt"))try{const s=d.default.readFileSync(t).toString().match(T[e]);if(s)return s[1]}catch(t){console.error(t)}return t}(t.version,t.platform));R(`version: ${s}`),R(`newVersion: ${e}`),e!==s&&(O=!0)}}else O=!0;if(O){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!d.default.existsSync(t.executablePath))throw Error(`${t.executablePath} not exists`)}return t},create:async function(t,e,s){O&&await C.install(),(O||s.compiled||await C.shouldPush())&&await C.push(t),await C.start()}},adapter:L};module.exports=k; +"use strict";var e=require("fs"),t=require("path"),s=require("debug"),a=require("jsonc-parser"),r=require("fs-extra"),i=require("postcss-selector-parser"),o=require("licia/dateFormat"),n=require("util"),l=require("jimp"),c=require("dns"),d=require("child_process");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=u(e),h=u(t),m=u(s),f=u(r),y=u(i),_=u(o),v=u(l),I=u(c);function P(e){e.walk((e=>{if("tag"===e.type){const t=e.value;e.value="page"===t?"body":"uni-"+t}}))}m.default("automator:devtool");const N=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const E=/^win/.test(process.platform);function S(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}const g=m.default("automator:launcher"),w=n.promisify(p.default.readdir),D=n.promisify(p.default.stat);async function U(e){const s=await w(e);return(await Promise.all(s.map((async s=>{const a=t.resolve(e,s);return(await D(a)).isDirectory()?U(a):a})))).reduce(((e,t)=>e.concat(t)),[])}class ${constructor(e){this.isX=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),this.id=e.id,this.app=e.executablePath,this.appid=e.appid||process.env.UNI_APP_ID||(this.isX?"__UNI__uniappx":"HBuilder"),this.package=e.package||(this.isX?"io.dcloud.uniappx":"io.dcloud.HBuilder"),this.activity=e.activity||(this.isX?"io.dcloud.uniapp.UniAppActivity":"io.dcloud.PandoraEntry")}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then((()=>(g(`${_.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1))).catch((()=>(g(`${_.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0)))}push(e){return U(e).then((s=>{const a=s.map((s=>{const a=(e=>E?e.replace(/\\/g,"/"):e)(t.join(this.DIR_WWW,t.relative(e,s)));return g(`${_.default("yyyy-mm-dd HH:MM:ss:l")} push ${s} ${a}`),this.pushFile(s,a)}));return Promise.all(a)})).then((e=>!0))}get FILE_APP_SERVICE(){return`${this.DIR_WWW}/app-service.js`}}const A=m.default("automator:simctl");function M(e){const t=parseInt(e);return t>9?String(t):"0"+t}class R extends ${constructor(){super(...arguments),this.bundleVersion=""}async init(){const e=S("node-simctl").Simctl;this.tool=new e({udid:this.id});try{await this.tool.bootDevice()}catch(e){}await this.initSDCard(),A(`${_.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const e=await this.tool.appInfo(this.package);A(`${_.default("yyyy-mm-dd HH:MM:ss:l")} appInfo ${e}`);const t=e.match(/DataContainer\s+=\s+"(.*)"/);if(!t)return Promise.resolve("");const s=e.match(/CFBundleVersion\s+=\s+(.*);/);if(!s)return Promise.resolve("");this.sdcard=t[1].replace("file:",""),this.bundleVersion=s[1],A(`${_.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.bundleVersion)}formatVersion(e){const t=e.split(".");return 3!==t.length?e:t[0]+M(t[1])+M(t[2])}async install(){return A(`${_.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),await this.tool.installApp(this.app),await this.tool.grantPermission(this.package,"all"),await this.initSDCard(),Promise.resolve(!0)}async start(){A("ios simulator start");try{await this.tool.terminateApp(this.package)}catch(e){console.error("ios simulator start terminateApp fail",e)}try{await this.tool.launchApp(this.package)}catch(e){console.error("ios simulator start launchApp fail",e),console.error(e)}return Promise.resolve(!0)}async exit(){return await this.tool.terminateApp(this.package),await this.tool.shutdownDevice(),Promise.resolve(!0)}async captureScreenshot(e){const t=await Promise.resolve(await this.tool.getScreenshot());return new Promise(((s,a)=>{var r,i;void 0!==(null===(r=null==e?void 0:e.area)||void 0===r?void 0:r.x)&&void 0!==(null===(i=null==e?void 0:e.area)||void 0===i?void 0:i.y)?v.default.read(Buffer.from(t,"base64")).then((t=>{const r=e.area.x,i=e.area.y;let o=t.bitmap.width-r;e.area.width&&(o=Math.min(o,e.area.width));let n=t.bitmap.height-i;e.area.height&&(n=Math.min(n,e.area.height)),t.crop(r,i,o,n).getBase64Async(v.default.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{a(e)}))})).catch((e=>{a(e)})):s(t)}))}exists(e){return f.default.existsSync(e)?Promise.resolve(!0):Promise.reject(Error(`${e} not exists`))}pushFile(e,t){return Promise.resolve(f.default.copySync(e,t))}adbCommand(e){return new Promise((e=>{e("adbCommand only for App Android!")}))}get DIR_WWW(){return"true"===process.env.UNI_APP_X?`${this.sdcard}/Documents/uni-app-x/apps/__UNI__uniappx/www/`:`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const H=S("adbkit"),b=m.default("automator:adb");class x extends ${constructor(){super(...arguments),this.needStart=!0}async init(){if(void 0!==I.default.setDefaultResultOrder&&I.default.setDefaultResultOrder("ipv4first"),this.tool=H.createClient(),b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} init ${await this.tool.version()}`),!this.id){const e=await this.tool.listDevices();if(!e.length)throw Error("Device not found");this.id=e[0].id}console.log("before echo ${$EXTERNAL_STORAGE}"),this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),console.log("after echo ${$EXTERNAL_STORAGE}",this.sdcard),b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}root(){return this.tool.root(this.id).then((()=>{b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${this.sdcard}`)})).catch((e=>{b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${e}`)}))}version(){return this.shell(this.COMMAND_VERSION).then((e=>{const t=e.match(/versionName=(.*)/);return t&&t.length>1?t[1]:""}))}formatVersion(e){return e}async install(){let e=!0;try{const t=(await this.tool.getProperties(this.id))["ro.build.version.release"].split(".")[0];parseInt(t)<6&&(e=!1)}catch(e){}if(b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${e}`),e){const e=S("adbkit/lib/adb/command.js"),t=e.prototype._send;e.prototype._send=function(e){return 0===e.indexOf("shell:pm install -r ")&&(e=e.replace("shell:pm install -r ","shell:pm install -r -g "),b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} ${e} `)),t.call(this,e)}}return this.tool.install(this.id,this.app).then((()=>{b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} installed`),this.init()}))}start(){return this.needStart?this.exit().then((()=>this.shell(this.COMMAND_START))):Promise.resolve()}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(e){return this.tool.screencap(this.id).then((t=>new Promise(((s,a)=>{const r=[];t.on("data",(function(e){r.push(e)})),t.on("end",(function(){var t,i;void 0!==(null===(t=e.area)||void 0===t?void 0:t.x)&&void 0!==(null===(i=e.area)||void 0===i?void 0:i.y)?v.default.read(Buffer.concat(r)).then((t=>{var r,i,o,n;const l=e.area.x,c=e.area.y;let d=t.bitmap.width-l;(null===(r=e.area)||void 0===r?void 0:r.width)&&(d=Math.min(d,null===(i=e.area)||void 0===i?void 0:i.width));let u=t.bitmap.height-c;(null===(o=e.area)||void 0===o?void 0:o.height)&&(u=Math.min(u,null===(n=e.area)||void 0===n?void 0:n.height)),t.crop(l,c,d,u).getBase64Async(v.default.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{a(e)}))})).catch((e=>{a(e)})):s(Buffer.concat(r).toString("base64"))}))}))))}adbCommand(e){return new Promise((t=>{this.tool.shell(this.id,e).then((e=>{let s,a="";e.on("data",(e=>{a+=e.toString(),s&&clearTimeout(s),s=setTimeout((()=>{t(a)}),50)})),setTimeout((()=>{t(a)}),1500)}))}))}exists(e){return this.tool.stat(this.id,e)}pushFile(e,t){return this.tool.push(this.id,e,t)}async push(e){if(!process.env.UNI_HBUILDERX_PLUGINS)return super.push(e);const t=h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher","out","export","pushResources.js"),s=process.env.HX_CONFIG_ADB_PATH||h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher-tools","tools","adbs","adb"),a=[t,s].map((e=>p.default.promises.access(e,p.default.constants.F_OK).then((()=>`${e} exists`)).catch((()=>`${e} not exists`))));return Promise.all(a).then((()=>{const{PushResources:a}=require(t);return new a({adbPath:s,appid:this.appid,uuid:this.id,packageName:this.package,sourcePath:e}).start(),this.needStart=!1,!0})).catch((async t=>(console.log("pushResources or adb not exists: ",t),await super.push(e))))}shell(e){return b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${e}`),this.tool.shell(this.id,e).then(H.util.readAll).then((e=>{const t=e.toString();return b(`${_.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${t}`),t}))}get DIR_WWW(){return`/storage/emulated/0/Android/data/${this.package}/apps/${this.appid}/www`}get COMMAND_EXTERNAL(){return"echo $EXTERNAL_STORAGE"}get COMMAND_VERSION(){return`dumpsys package ${this.package}`}get COMMAND_STOP(){return`am force-stop ${this.package}`}get COMMAND_START(){return`am start -n ${this.package}/${this.activity} --es appid ${this.appid} --ez needUpdateApp false --ez reload true --ez externalStorage true`}}const T=m.default("automator:devtool");let C,O=!1;const X={android:/android_version=(.*)/,ios:/iphone_version=(.*)/};const k={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>C.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshotWithDevice":{reflect:async(e,t)=>{const s=await C.captureScreenshot(t);return T(`App.captureScreenshot ${s.length}`),{data:s}}},"App.adbCommand":{reflect:async(e,t)=>{const s=await C.adbCommand(t);return T(`App.adbCommand ${s.length}`),{data:s}}}};!function(e){N.forEach((t=>{e[t]=function(e){return{reflect:async(t,s)=>t(e,s,!1),params:e=>(e.selector&&(e.selector=y.default(P).processSync(e.selector)),e)}}(t)}))}(k);const j={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(e,t){e.platform=(e.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(e,e[e.platform]),C=function(e,t){return"ios"===e?new R(t):new x(t)}(e.platform,e),await C.init();const s=await C.version();if(s){if(e.version){const t=C.formatVersion(function(e,t){if(e.endsWith(".txt"))try{const s=p.default.readFileSync(e).toString().match(X[t]);if(s)return s[1]}catch(e){console.error(e)}return e}(e.version,e.platform));T(`version: ${s}`),T(`newVersion: ${t}`),t!==s&&(O=!0)}}else O=!0;if(O){if(!e.executablePath)throw Error(`app-plus->${e.platform}->executablePath is not provided`);if(!p.default.existsSync(e.executablePath))throw Error(`${e.executablePath} not exists`)}return e},create:async function(e,t,s){O&&await C.install(),(O||s.compiled||await C.shouldPush())&&await C.push(e),await C.start()}},adapter:k,beforeCompile(){if(process.env.UNI_INPUT_DIR&&"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW){const e=a.parse(r.readFileSync(h.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8")),t=h.default.resolve(process.env.UNI_INPUT_DIR,"unpackage",".automator","app-webview");process.env.UNI_INPUT_DIR=h.default.resolve(t,"src"),process.env.UNI_OUTPUT_DIR=h.default.resolve(t,"unpackage","dist","dev"),r.existsSync(process.env.UNI_INPUT_DIR)&&r.emptyDirSync(process.env.UNI_INPUT_DIR),r.copySync(h.default.resolve(__dirname,"..","lib","app-webview","project"),process.env.UNI_INPUT_DIR);const s=a.parse(r.readFileSync(h.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8"));r.writeFileSync(h.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),JSON.stringify(Object.assign(Object.assign({},s),{name:e.name||"",appid:e.appid||""}),null,2))}else if(process.env.UNI_INPUT_DIR&&"ios"===process.env.UNI_OS_NAME&&C.app&&C.app.endsWith(".app")){const e=h.default.resolve(process.env.UNI_INPUT_DIR,"uni_modules");if(!r.readdirSync(e).some((t=>r.existsSync(h.default.resolve(e,t,"utssdk")))))return;process.env.UNI_APP_X="true"===process.env.UNI_APP_X?"1":"0",process.env.HX_DEPENDENCIES_DIR=h.default.join(process.env.UNI_OUTPUT_DIR,"../../../cache/.automator/uts_standard_simulator"),process.env.HX_RUN_DEVICE_TYPE="ios_simulator",C.app&&(process.env.UTS_BASE_INFO=p.default.readFileSync(h.default.resolve(C.app,"Frameworks/DCloudUTSFoundation.framework/uts-info.json"),"utf8")),!process.env.HX_Version&&process.env.UNI_HBUILDERX_PLUGINS&&(process.env.HX_Version=require(h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"about","package.json")).version),T("HX_DEPENDENCIES_DIR",process.env.HX_DEPENDENCIES_DIR),T("UTS_BASE_INFO",process.env.UTS_BASE_INFO)}},afterCompile(){if("ios_simulator"===process.env.HX_RUN_DEVICE_TYPE&&C.app){process.env.UNI_APP_X="1"===process.env.UNI_APP_X?"true":"false";const t=h.default.resolve(process.env.HX_DEPENDENCIES_DIR,"Resources"),s=h.default.resolve(process.env.HX_DEPENDENCIES_DIR,"modules"),a=p.default.existsSync(t),i=p.default.existsSync(s),o=(e=h.default.basename(C.app),h.default.resolve(process.env.HX_DEPENDENCIES_DIR,".automator/"+e));if(!a&&!i)return;if(r.existsSync(o)&&r.emptyDirSync(o),r.copySync(C.app,o),C.app=o,a&&r.copySync(t,h.default.resolve(C.app,"Resources")),i){const e=[];r.readdirSync(s).forEach((t=>{t.endsWith(".framework")&&(e.push(t),r.copySync(h.default.join(s,t),h.default.resolve(C.app,"Frameworks",t)))})),e.forEach((e=>{const t=`'${process.env.UNI_HBUILDERX_PLUGINS}/launcher-tools/tools/uts/optool' 'install' '-c' 'weak' '-p' '@rpath/${e}/${e.replace(".framework","")}' '-t' '${C.app}'`,s=d.execSync(t);T(t,s.toString())}))}if(a||i){const e=d.execSync(`codesign -fs "-" "${C.app}"`);T("codesign success",e.toString())}}var e}};module.exports=j; diff --git a/packages/uni-automator/dist/index.js b/packages/uni-automator/dist/index.js index a6e0952bd069cd2d8b0ae1e92baf438949fc05f9..0ff81d8ab953c840c8362fa19d7003da92263be7 100644 --- a/packages/uni-automator/dist/index.js +++ b/packages/uni-automator/dist/index.js @@ -1,4 +1,4 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("fs"),t=require("path"),s=require("debug"),n=require("merge"),i=require("jsonc-parser"),o=require("licia/isRelative"),r=require("ws"),a=require("events"),c=require("licia/uuid"),p=require("licia/stringify"),l=require("licia/dateFormat"),u=require("licia/waitUntil"),h=require("os"),d=require("address"),m=require("default-gateway"),g=require("licia/isStr"),v=require("licia/getPort"),y=require("qrcode-terminal"),f=require("licia/fs"),w=require("licia/isFn"),P=require("licia/trim"),I=require("licia/startWith"),M=require("licia/isNum"),_=require("licia/sleep"),k=require("licia/isUndef"),E=require("child_process"),A=require("licia/toStr"),U=require("fs-extra");function T(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var N=T(e),b=T(t),C=T(s),R=T(o),O=T(r),D=T(c),S=T(p),j=T(l),x=T(u),$=T(h),q=T(d),F=T(m),L=T(g),H=T(v),W=T(y),X=T(f),B=T(w),V=T(P),J=T(I),G=T(M),z=T(_),Y=T(k),K=T(A);class Q extends a.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",(e=>{this.emit("message",e.data)})),this.ws.addEventListener("close",(()=>{this.emit("close")}))}send(e){this.ws.send(e)}close(){this.ws.close()}}const Z=new Map,ee=["onCompassChange","onThemeChange","onUserCaptureScreen","onWindowResize","onMemoryWarning","onAccelerometerChange","onKeyboardHeightChange","onNetworkStatusChange","onPushMessage","onLocationChange","onGetWifiList","onWifiConnected","onWifiConnectedWithPartialInfo","onSocketOpen","onSocketError","onSocketMessage","onSocketClose"];const te=new Map;function se(e,t){(null==e?void 0:e.success)&&"function"==typeof(null==e?void 0:e.success)&&(t?e.success(t):e.success()),(null==e?void 0:e.complete)&&"function"==typeof(null==e?void 0:e.complete)&&(t?e.complete(t):e.complete())}function ne(e,t){(null==e?void 0:e.fail)&&"function"==typeof(null==e?void 0:e.fail)&&(t?e.fail(t):e.fail()),(null==e?void 0:e.complete)&&"function"==typeof(null==e?void 0:e.complete)&&(t?e.complete(t):e.complete())}async function ie(e,t){const[s,n]=function(e){return L.default(e)?[!0,[e]]:[!1,e]}(t),i=await e(n);return s?i[0]:i}function oe(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}/^win/.test(process.platform);const re="Connection closed";class ae extends a.EventEmitter{constructor(e,t,s){super(),this.puppet=t,this.namespace=s,this.callbacks=new Map,this.transport=e,this.isAlive=!0,this.id=Date.now(),this.debug=C.default("automator:protocol:"+this.namespace),this.onMessage=e=>{var t,s;if(this.isAlive=!0,"true"===process.env.UNI_APP_X&&'"pong"'===e)return;this.debug(`${j.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:n,method:i,error:o,result:r,params:a}=JSON.parse(e);if(null===(t=null==r?void 0:r.method)||void 0===t?void 0:t.startsWith("on"))return void((e,t)=>{const s=Z.get(e.method);(null==s?void 0:s.has(t))&&s.get(t)(e.data)})(r,n);if(null===(s=null==r?void 0:r.method)||void 0===s?void 0:s.startsWith("Socket.")){return void((e,t,s)=>{const n=te.get(t);(null==n?void 0:n.has(e))&&n.get(e)(s)})(r.method.replace("Socket.",""),r.id,r.data)}if(!n)return this.puppet.emit(i,a);const{callbacks:c}=this;if(n&&c.has(n)){const e=c.get(n);c.delete(n),o?e.reject(Error(o.message||o.detailMessage||o.errMsg)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(re))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},s=!0){if(s&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const n=D.default(),i=S.default({id:n,method:e,params:t});return"ping"!==e&&this.debug(`${j.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${i}`),new Promise(((e,t)=>{try{this.transport.send(i)}catch(e){t(Error(re))}this.callbacks.set(n,{resolve:e,reject:t})}))}dispose(){this.transport.close()}startHeartbeat(){"true"===process.env.UNI_APP_X&&("android"===process.env.UNI_APP_PLATFORM?this.startXAndroidHeartbeat():"ios"===process.env.UNI_APP_PLATFORM&&this.startXIosHeartbeat())}startXAndroidHeartbeat(){const e=new Map,t=oe("adbkit"),s=$.default.platform();let n="",i="";"darwin"===s?(n='dumpsys activity | grep "Run"',i="logcat -b crash | grep -C 10 io.dcloud.uniappx"):"win32"===s&&(n='dumpsys activity | findstr "Run"',i="logcat | findstr UncaughtExceptionHandler"),e.set(this.id,setInterval((async()=>{if(!this.isAlive){const o=t.createClient(),r=await o.listDevices();if(!r.length)throw Error("Device not found");const a=r[0].id,c=await o.getProperties(a);return("1"===c["ro.kernel.qemu"]||"goldfish"===c["ro.hardware"])&&"win32"===s&&(i="logcat | grep UncaughtExceptionHandler"),o.shell(a,n).then((function(e){let t,s="";e.on("data",(function(e){s+=e.toString(),t&&clearTimeout(t),t=setTimeout((()=>{s.includes("io.dcloud.uniapp")||console.log("Stop the test process.")}),50)}))})),o.shell(a,i).then((e=>{let t,s="";e.on("data",(e=>{s+=e.toString(),t&&clearTimeout(t),t=setTimeout((()=>{console.log(`crash log: ${s}`)}),50)}))})),clearInterval(e.get(this.id)),e.delete(this.id),void this.dispose()}this.send("ping"),this.isAlive=!1}),5e3))}startXIosHeartbeat(){const e=new Map;e.set(this.id,setInterval((async()=>{if(!this.isAlive)return console.log("Stop the test process."),clearInterval(e.get(this.id)),e.delete(this.id),void this.dispose();this.send("ping"),this.isAlive=!1}),5e3))}static createDevtoolConnection(e,t){return new Promise(((s,n)=>{const i=new O.default(e);i.addEventListener("open",(()=>{s(new ae(new Q(i),t,"devtool"))})),i.addEventListener("error",n)}))}static createRuntimeConnection(e,t,s){return new Promise(((n,i)=>{C.default("automator:runtime")(`${j.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new O.default.Server({port:e});x.default((async()=>{if(t.runtimeConnection)return!0}),s,1e3).catch((()=>{o.close(),i("Failed to connect to runtime, please make sure the project is running")})),o.on("connection",(function(e){C.default("automator:runtime")(`${j.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const s=new ae(new Q(e),t,"runtime");t.setRuntimeConnection(s),s.startHeartbeat(),n(s)})),t.setRuntimeServer(o)}))}} +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("fs"),e=require("path"),n=require("debug"),s=require("merge"),i=require("jsonc-parser"),o=require("licia/isRelative"),r=require("ws"),a=require("events"),c=require("licia/uuid"),p=require("licia/stringify"),l=require("licia/dateFormat"),u=require("licia/waitUntil"),h=require("os"),d=require("address"),m=require("default-gateway"),g=require("licia/isStr"),y=require("licia/getPort"),v=require("qrcode-terminal"),f=require("licia/fs"),w=require("licia/isFn"),P=require("licia/trim"),M=require("licia/startWith"),I=require("licia/isNum"),k=require("licia/sleep"),E=require("licia/isUndef"),A=require("child_process"),_=require("licia/toStr"),b=require("fs-extra");function T(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var C=T(t),U=T(e),N=T(n),O=T(o),R=T(r),S=T(c),D=T(p),j=T(l),x=T(u),$=T(h),q=T(d),L=T(m),F=T(g),H=T(y),W=T(v),X=T(f),B=T(w),V=T(P),J=T(M),G=T(I),z=T(k),Y=T(E),K=T(_);class Q extends a.EventEmitter{constructor(t){super(),this.ws=t,this.ws.addEventListener("message",(t=>{this.emit("message",t.data)})),this.ws.addEventListener("close",(()=>{this.emit("close")}))}send(t){this.ws.send(t)}close(){this.ws.close()}}const Z=new Map,tt=["onCompassChange","onThemeChange","onUserCaptureScreen","onWindowResize","onMemoryWarning","onAccelerometerChange","onKeyboardHeightChange","onNetworkStatusChange","onPushMessage","onLocationChange","onGetWifiList","onWifiConnected","onWifiConnectedWithPartialInfo","onSocketOpen","onSocketError","onSocketMessage","onSocketClose"];const et=new Map;function nt(t,e){(null==t?void 0:t.success)&&"function"==typeof(null==t?void 0:t.success)&&(e?t.success(e):t.success()),(null==t?void 0:t.complete)&&"function"==typeof(null==t?void 0:t.complete)&&(e?t.complete(e):t.complete())}function st(t,e){(null==t?void 0:t.fail)&&"function"==typeof(null==t?void 0:t.fail)&&(e?t.fail(e):t.fail()),(null==t?void 0:t.complete)&&"function"==typeof(null==t?void 0:t.complete)&&(e?t.complete(e):t.complete())}async function it(t,e){const[n,s]=function(t){return F.default(t)?[!0,[t]]:[!1,t]}(e),i=await t(s);return n?i[0]:i}function ot(t){try{return require(t)}catch(e){return require(require.resolve(t,{paths:[process.cwd()]}))}}/^win/.test(process.platform);const rt="Connection closed";class at extends a.EventEmitter{constructor(t,e,n){super(),this.puppet=e,this.namespace=n,this.callbacks=new Map,this.transport=t,this.isAlive=!0,this.id=Date.now(),this.debug=N.default("automator:protocol:"+this.namespace),this.onMessage=t=>{var e,n;if(this.isAlive=!0,"true"===process.env.UNI_APP_X&&'"pong"'===t)return;this.debug(`${j.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${t}`);const{id:s,method:i,error:o,result:r,params:a}=JSON.parse(t);if(null===(e=null==r?void 0:r.method)||void 0===e?void 0:e.startsWith("on"))return void((t,e)=>{const n=Z.get(t.method);(null==n?void 0:n.has(e))&&n.get(e)(t.data)})(r,s);if(null===(n=null==r?void 0:r.method)||void 0===n?void 0:n.startsWith("Socket.")){return void((t,e,n)=>{const s=et.get(e);(null==s?void 0:s.has(t))&&s.get(t)(n)})(r.method.replace("Socket.",""),r.id,r.data)}if(!s)return this.puppet.emit(i,a);const{callbacks:c}=this;if(s&&c.has(s)){const t=c.get(s);c.delete(s),o?t.reject(Error(o.message||o.detailMessage||o.errMsg)):t.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((t=>{t.reject(Error(rt))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(t,e={},n=!0){if(n&&this.puppet.adapter.has(t))return this.puppet.adapter.send(this,t,e);const s=S.default(),i=D.default({id:s,method:t,params:e});return"ping"!==t&&this.debug(`${j.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${i}`),new Promise(((t,e)=>{try{this.transport.send(i)}catch(t){e(Error(rt))}this.callbacks.set(s,{resolve:t,reject:e})}))}dispose(){this.transport.close()}startHeartbeat(){"true"===process.env.UNI_APP_X&&("android"===process.env.UNI_APP_PLATFORM?this.startXAndroidHeartbeat():"ios"===process.env.UNI_APP_PLATFORM&&this.startXIosHeartbeat())}startXAndroidHeartbeat(){const t=new Map,e=ot("adbkit"),n=$.default.platform();let s="",i="";"darwin"===n?(s='dumpsys activity | grep "Run"',i="logcat -b crash | grep -C 10 io.dcloud.uniappx"):"win32"===n&&(s='dumpsys activity | findstr "Run"',i="logcat | findstr UncaughtExceptionHandler"),t.set(this.id,setInterval((async()=>{if(!this.isAlive){const o=e.createClient(),r=await o.listDevices();if(!r.length)throw Error("Device not found");const a=r[0].id,c=await o.getProperties(a);return("1"===c["ro.kernel.qemu"]||"goldfish"===c["ro.hardware"])&&"win32"===n&&(i="logcat | grep UncaughtExceptionHandler"),o.shell(a,s).then((function(t){let e,n="";t.on("data",(function(t){n+=t.toString(),e&&clearTimeout(e),e=setTimeout((()=>{n.includes("io.dcloud.uniapp")||console.log("Stop the test process.")}),50)}))})),o.shell(a,i).then((t=>{let e,n="";t.on("data",(t=>{n+=t.toString(),e&&clearTimeout(e),e=setTimeout((()=>{console.log(`crash log: ${n}`)}),50)}))})),clearInterval(t.get(this.id)),t.delete(this.id),void this.dispose()}this.send("ping"),this.isAlive=!1}),5e3))}startXIosHeartbeat(){const t=new Map;t.set(this.id,setInterval((async()=>{if(!this.isAlive)return console.log("Stop the test process."),clearInterval(t.get(this.id)),t.delete(this.id),void this.dispose();this.send("ping"),this.isAlive=!1}),5e3))}static createDevtoolConnection(t,e){return new Promise(((n,s)=>{const i=new R.default(t);i.addEventListener("open",(()=>{n(new at(new Q(i),e,"devtool"))})),i.addEventListener("error",s)}))}static createRuntimeConnection(t,e,n){return new Promise(((s,i)=>{N.default("automator:runtime")(`${j.default("yyyy-mm-dd HH:MM:ss:l")} port=${t}`);const o=new R.default.Server({port:t});x.default((async()=>{if(e.runtimeConnection)return!0}),n,1e3).catch((()=>{o.close(),i("Failed to connect to runtime, please make sure the project is running")})),o.on("connection",(function(t){N.default("automator:runtime")(`${j.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const n=new at(new Q(t),e,"runtime");e.setRuntimeConnection(n),n.startHeartbeat(),s(n)})),e.setRuntimeServer(o)}))}} /*! ***************************************************************************** Copyright (c) Microsoft Corporation. @@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */function ce(e,t,s,n){var i,o=arguments.length,r=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,s):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,s,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(r=(o<3?i(r):o>3?i(t,s,r):i(t,s))||r);return o>3&&r&&Object.defineProperty(t,s,r),r}var pe;function le(e,t){const s=t.value;return t.value=async function(t){return(await(null==s?void 0:s.call(this,t)))(e)},t}function ue(e,t,s){return le(pe.RUNTIME,s)}function he(e,t,s){return le(pe.DEVTOOL,s)}!function(e){e.RUNTIME="runtime",e.DEVTOOL="devtool"}(pe||(pe={}));class de{constructor(e){this.puppet=e}invoke(e,t){return async s=>this.puppet.devtoolConnection?(s===pe.DEVTOOL?this.puppet.devtoolConnection:this.puppet.runtimeConnection).send(e,t):this.puppet.runtimeConnection.send(e,t)}on(e,t){this.puppet.on(e,t)}}class me extends de{constructor(e,t){super(e),this.id=t.elementId,this.pageId=t.pageId,this.nodeId=t.nodeId,this.videoId=t.videoId}async getData(e){return this.invokeMethod("Element.getData",e)}async setData(e){return this.invokeMethod("Element.setData",e)}async callMethod(e){return this.invokeMethod("Element.callMethod",e)}async getElement(e){return this.invokeMethod("Element.getElement",e)}async getElements(e){return this.invokeMethod("Element.getElements",e)}async getOffset(){return this.invokeMethod("Element.getOffset")}async getHTML(e){return this.invokeMethod("Element.getHTML",e)}async getAttributes(e){return this.invokeMethod("Element.getAttributes",e)}async getStyles(e){return this.invokeMethod("Element.getStyles",e)}async getDOMProperties(e){return this.invokeMethod("Element.getDOMProperties",e)}async getProperties(e){return this.invokeMethod("Element.getProperties",e)}async tap(){return this.invokeMethod("Element.tap")}async longpress(){return this.invokeMethod("Element.longpress")}async touchstart(e){return this.invokeMethod("Element.touchstart",e)}async touchmove(e){return this.invokeMethod("Element.touchmove",e)}async touchend(e){return this.invokeMethod("Element.touchend",e)}async triggerEvent(e){return this.invokeMethod("Element.triggerEvent",e)}async callFunction(e){return this.invokeMethod("Element.callFunction",e)}async callContextMethod(e){return this.invokeMethod("Element.callContextMethod",e)}invokeMethod(e,t={}){return t.elementId=this.id,t.pageId=this.pageId,this.nodeId&&(t.nodeId=this.nodeId),this.videoId&&(t.videoId=this.videoId),this.invoke(e,t)}}ce([ue],me.prototype,"getData",null),ce([ue],me.prototype,"setData",null),ce([ue],me.prototype,"callMethod",null),ce([he],me.prototype,"getElement",null),ce([he],me.prototype,"getElements",null),ce([he],me.prototype,"getOffset",null),ce([he],me.prototype,"getHTML",null),ce([he],me.prototype,"getAttributes",null),ce([he],me.prototype,"getStyles",null),ce([he],me.prototype,"getDOMProperties",null),ce([he],me.prototype,"getProperties",null),ce([he],me.prototype,"tap",null),ce([he],me.prototype,"longpress",null),ce([he],me.prototype,"touchstart",null),ce([he],me.prototype,"touchmove",null),ce([he],me.prototype,"touchend",null),ce([he],me.prototype,"triggerEvent",null),ce([he],me.prototype,"callFunction",null),ce([he],me.prototype,"callContextMethod",null);const ge=Object.prototype.hasOwnProperty,ve=Array.isArray,ye=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function fe(e,t){if(ve(e))return e;if(t&&(s=t,n=e,ge.call(s,n)))return[e];var s,n;const i=[];return e.replace(ye,(function(e,t,s,n){return i.push(s?n.replace(/\\(\\)?/g,"$1"):t||e),n})),i}function we(e,t){const s=fe(t,e);let n;for(n=s.shift();null!=n;){if(null==(e=e[n]))return;n=s.shift()}return e}const Pe=require("util"),Ie=["scrollLeft","scrollTop","scrollWidth","scrollHeight"];class Me{constructor(e,t,s){this.puppet=e,this.id=t.elementId,this.pageId=t.pageId,this.nodeId=t.nodeId||null,this.videoId=t.videoId||null,this.tagName=t.tagName,this.nvue=t.nvue,this.elementMap=s,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new me(e,t)}toJSON(){return JSON.stringify({id:this.id,tagName:this.tagName,pageId:this.pageId,nodeId:this.nodeId,videoId:this.videoId})}toString(){return this.toJSON()}[Pe.inspect.custom](){return this.toJSON()}async $(e){try{const t=await this.api.getElement({selector:e});return Me.create(this.puppet,Object.assign({},t,{pageId:this.pageId}),this.elementMap)}catch(e){return null}}async $$(e){const{elements:t}=await this.api.getElements({selector:e});return t.map((e=>Me.create(this.puppet,Object.assign({},e,{pageId:this.pageId}),this.elementMap)))}async size(){const[e,t]=await this.domProperty(["offsetWidth","offsetHeight"]);return{width:e,height:t}}async offset(){const{left:e,top:t}=await this.api.getOffset();return{left:e,top:t}}async text(){return this.domProperty("innerText")}async attribute(e){if(!L.default(e))throw Error("name must be a string");return(await this.api.getAttributes({names:[e]})).attributes[0]}async value(){return this.puppet.isX?this.domProperty("value"):this.property("value")}async property(e){if(!L.default(e))throw Error("name must be a string");if(this.puppet.checkProperty){let t=this.publicProps;if(t||(this.publicProps=t=await this._property("__propPublic")),!t[e])throw Error(`${this.tagName}.${e} not exists`)}return this.puppet.isX&&"h5"===process.env.UNI_PLATFORM&&Ie.includes(e)?await this.domProperty(e):this._property(e)}async html(){return(await this.api.getHTML({type:"inner"})).html}async outerHtml(){return(await this.api.getHTML({type:"outer"})).html}async style(e){if(!L.default(e))throw Error("name must be a string");return(await this.api.getStyles({names:[e]})).styles[0]}async tap(){return this.api.tap()}async longpress(){return this.nvue||"true"===process.env.UNI_APP_X?this.api.longpress():(await this.touchstart(),await z.default(350),this.touchend())}async trigger(e,t){const s={type:e};return Y.default(t)||(s.detail=t),this.api.triggerEvent(s)}async touchstart(e){return this.api.touchstart(e)}async touchmove(e){return this.api.touchmove(e)}async touchend(e){return this.api.touchend(e)}async domProperty(e){return ie((async e=>(await this.api.getDOMProperties({names:e})).properties),e)}_property(e){return ie((async e=>(await this.api.getProperties({names:e})).properties),e)}send(e,t){return t.elementId=this.id,t.pageId=this.pageId,this.nodeId&&(t.nodeId=this.nodeId),this.videoId&&(t.videoId=this.videoId),this.puppet.send(e,t)}async callFunction(e,...t){return(await this.api.callFunction({functionName:e,args:t})).result}static create(e,t,s){let n,i=s.get(t.elementId);if(i)return i;if(t.nodeId)n=_e;else switch(t.tagName.toLowerCase()){case"input":n=ke;break;case"textarea":n=Ee;break;case"scroll-view":n=Ae;break;case"swiper":n=Ue;break;case"movable-view":n=Te;break;case"switch":n=Ne;break;case"slider":n=be;break;case"video":n=Ce;break;default:n=Me}return i=new n(e,t,s),s.set(t.elementId,i),i}}class _e extends Me{async setData(e){return this.api.setData({data:e})}async data(e){const t={};if(e&&(t.path=e),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const s=(await this.api.getData(t)).data;return e?we(s,e):s}return(await this.api.getData(t)).data}async callMethod(e,...t){return(await this.api.callMethod({method:e,args:t})).result}}class ke extends Me{async input(e){return this.callFunction("input.input",e)}}class Ee extends Me{async input(e){return this.callFunction("textarea.input",e)}}class Ae extends Me{async scrollTo(e,t){return this.callFunction("scroll-view.scrollTo",e,t)}async property(e){return"scrollTop"===e?this.callFunction("scroll-view.scrollTop"):"scrollLeft"===e?this.callFunction("scroll-view.scrollLeft"):super.property(e)}async scrollWidth(){return this.callFunction("scroll-view.scrollWidth")}async scrollHeight(){return this.callFunction("scroll-view.scrollHeight")}}class Ue extends Me{async swipeTo(e){return this.callFunction("swiper.swipeTo",e)}}class Te extends Me{async moveTo(e,t){return this.callFunction("movable-view.moveTo",e,t)}async property(e){return"x"===e?this._property("_translateX"):"y"===e?this._property("_translateY"):super.property(e)}}class Ne extends Me{async tap(){return this.callFunction("switch.tap")}}class be extends Me{async slideTo(e){return this.callFunction("slider.slideTo",e)}}class Ce extends Me{async callContextMethod(e,...t){return await this.api.callContextMethod({method:e,args:t})}}class Re extends de{constructor(e,t){super(e),this.id=t.id}async getData(e){return this.invokeMethod("Page.getData",e)}async setData(e){return this.invokeMethod("Page.setData",e)}async callMethod(e){return this.invokeMethod("Page.callMethod",e)}async callMethodWithCallback(e){return this.invokeMethod("Page.callMethodWithCallback",e)}async getElement(e){return this.invokeMethod("Page.getElement",e)}async getElements(e){return this.invokeMethod("Page.getElements",e)}async getWindowProperties(e){return this.invokeMethod("Page.getWindowProperties",e)}invokeMethod(e,t={}){return t.pageId=this.id,this.invoke(e,t)}}ce([ue],Re.prototype,"getData",null),ce([ue],Re.prototype,"setData",null),ce([ue],Re.prototype,"callMethod",null),ce([ue],Re.prototype,"callMethodWithCallback",null),ce([he],Re.prototype,"getElement",null),ce([he],Re.prototype,"getElements",null),ce([he],Re.prototype,"getWindowProperties",null);const Oe=require("util");class De{constructor(e,t){this.puppet=e,this.id=t.id,this.path=t.path,this.query=t.query,this.elementMap=new Map,this.api=new Re(e,t)}toJSON(){return JSON.stringify({id:this.id,path:this.path,query:this.query})}toString(){return this.toJSON()}[Oe.inspect.custom](){return this.toJSON()}async waitFor(e){return G.default(e)?await z.default(e):B.default(e)?x.default(e,0,50):L.default(e)?x.default((async()=>{if("true"===process.env.UNI_APP_X){return!!await this.$(e)}return(await this.$$(e)).length>0}),0,50):void 0}async $(e){try{const t=await this.api.getElement({selector:e});return Me.create(this.puppet,Object.assign({selector:e},t,{pageId:this.id}),this.elementMap)}catch(e){return null}}async $$(e){const{elements:t}=await this.api.getElements({selector:e});return t.map((t=>Me.create(this.puppet,Object.assign({selector:e},t,{pageId:this.id}),this.elementMap)))}async data(e){const t={};if(e&&(t.path=e),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const s=(await this.api.getData(t)).data;return e?we(s,e):s}return(await this.api.getData(t)).data}async setData(e){return this.api.setData({data:e})}async size(){const[e,t]=await this.windowProperty(["document.documentElement.scrollWidth","document.documentElement.scrollHeight"]);return{width:e,height:t}}async callMethod(e,...t){return(await this.api.callMethod({method:e,args:t})).result}async callMethodWithCallback(e,...t){return await this.api.callMethodWithCallback({method:e,args:t})}async scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(e){const t=L.default(e);t&&(e=[e]);const{properties:s}=await this.api.getWindowProperties({names:e});return t?s[0]:s}static create(e,t,s){let n=s.get(t.id);return n?(n.path=t.path,n.query=t.query,n):(n=new De(e,t),s.set(t.id,n),n)}}class Se extends de{async getPageStack(){return this.invoke("App.getPageStack")}async callUniMethod(e){return this.invoke("App.callUniMethod",e)}async getCurrentPage(){return this.invoke("App.getCurrentPage")}async mockUniMethod(e){return this.invoke("App.mockUniMethod",e)}async captureScreenshotByRuntime(e){return this.invoke("App.captureScreenshot",e)}async captureScreenshotWithDeviceByRuntime(e){return this.invoke("App.captureScreenshotWithDevice",e)}async socketEmitter(e){return this.invoke("App.socketEmitter",e)}async callFunction(e){return this.invoke("App.callFunction",e)}async captureScreenshot(e){return this.invoke("App.captureScreenshot",e)}async adbCommand(e){return this.invoke("App.adbCommand",e)}async exit(){return this.invoke("App.exit")}async addBinding(e){return this.invoke("App.addBinding",e)}async enableLog(){return this.invoke("App.enableLog")}onLogAdded(e){return this.on("App.logAdded",e)}onBindingCalled(e){return this.on("App.bindingCalled",e)}onExceptionThrown(e){return this.on("App.exceptionThrown",e)}}ce([ue],Se.prototype,"getPageStack",null),ce([ue],Se.prototype,"callUniMethod",null),ce([ue],Se.prototype,"getCurrentPage",null),ce([ue],Se.prototype,"mockUniMethod",null),ce([ue],Se.prototype,"captureScreenshotByRuntime",null),ce([ue],Se.prototype,"captureScreenshotWithDeviceByRuntime",null),ce([ue],Se.prototype,"socketEmitter",null),ce([he],Se.prototype,"callFunction",null),ce([he],Se.prototype,"captureScreenshot",null),ce([he],Se.prototype,"adbCommand",null),ce([he],Se.prototype,"exit",null),ce([he],Se.prototype,"addBinding",null),ce([he],Se.prototype,"enableLog",null);class je extends de{async getInfo(){return this.invoke("Tool.getInfo")}async enableRemoteDebug(e){return this.invoke("Tool.enableRemoteDebug")}async close(){return this.invoke("Tool.close")}async getTestAccounts(){return this.invoke("Tool.getTestAccounts")}onRemoteDebugConnected(e){this.puppet.once("Tool.onRemoteDebugConnected",e),this.puppet.once("Tool.onPreviewConnected",e)}}function xe(e){return new Promise((t=>setTimeout(t,e)))}ce([he],je.prototype,"getInfo",null),ce([he],je.prototype,"enableRemoteDebug",null),ce([he],je.prototype,"close",null),ce([he],je.prototype,"getTestAccounts",null);class $e extends a.EventEmitter{constructor(e,t){super(),this.puppet=e,this.options=t,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new Se(e),this.toolApi=new je(e),this.appApi.onLogAdded((e=>{this.emit("console",e)})),this.appApi.onBindingCalled((({name:e,args:t})=>{try{const s=this.appBindings.get(e);s&&s(...t)}catch(e){}})),this.appApi.onExceptionThrown((e=>{this.emit("exception",e)}))}async pageStack(){return(await this.appApi.getPageStack()).pageStack.map((e=>De.create(this.puppet,e,this.pageMap)))}async navigateTo(e){return this.changeRoute("navigateTo",e)}async redirectTo(e){return this.changeRoute("redirectTo",e)}async navigateBack(){return this.changeRoute("navigateBack")}async reLaunch(e){return this.changeRoute("reLaunch",e)}async switchTab(e){return this.changeRoute("switchTab",e)}async currentPage(){const{id:e,path:t,query:s}=await this.appApi.getCurrentPage();return De.create(this.puppet,{id:e,path:t,query:s},this.pageMap)}async systemInfo(){return this.callUniMethod("getSystemInfoSync")}async callUniMethod(e,...t){return(await this.appApi.callUniMethod({method:e,args:t})).result}async mockUniMethod(e,t,...s){return B.default(t)||(n=t,L.default(n)&&(n=V.default(n),J.default(n,"function")||J.default(n,"() =>")))?this.appApi.mockUniMethod({method:e,functionDeclaration:t.toString(),args:s}):this.appApi.mockUniMethod({method:e,result:t});var n}async restoreUniMethod(e){return this.appApi.mockUniMethod({method:e})}async evaluate(e,...t){return(await this.appApi.callFunction({functionDeclaration:e.toString(),args:t})).result}async pageScrollTo(e){await this.callUniMethod("pageScrollTo",{scrollTop:e,duration:0})}async close(){try{await this.appApi.exit()}catch(e){}await xe(1e3),this.puppet.disposeRuntimeServer(),await this.toolApi.close(),this.disconnect()}async teardown(){return this["disconnect"===this.options.teardown?"disconnect":"close"]()}async remote(e){if(!this.puppet.devtools.remote)return console.warn(`Failed to enable remote, ${this.puppet.devtools.name} is unimplemented`);const{qrCode:t}=await this.toolApi.enableRemoteDebug({auto:e});var s;t&&await(s=t,new Promise((e=>{W.default.generate(s,{small:!0},(t=>{process.stdout.write(t),e(void 0)}))})));const n=new Promise((e=>{this.toolApi.onRemoteDebugConnected((async()=>{await xe(1e3),e(void 0)}))})),i=new Promise((e=>{this.puppet.setRemoteRuntimeConnectionCallback((()=>{e(void 0)}))}));return Promise.all([n,i])}disconnect(){this.puppet.dispose()}on(e,t){return"console"===e&&this.appApi.enableLog(),super.on(e,t),this}async exposeFunction(e,t){if(this.appBindings.has(e))throw Error(`Failed to expose function with name ${e}: already exists!`);this.appBindings.set(e,t),await this.appApi.addBinding({name:e})}async checkVersion(){}async screenshot(e){const t=this.puppet.isX&&"app-plus"===this.puppet.platform?(null==e?void 0:e.deviceShot)?"captureScreenshotWithDeviceByRuntime":"captureScreenshotByRuntime":"captureScreenshot",{data:s}=await this.appApi[t]({id:null==e?void 0:e.id,fullPage:null==e?void 0:e.fullPage,area:null==e?void 0:e.area,offsetX:null==e?void 0:e.offsetX,offsetY:null==e?void 0:e.offsetY});if(!(null==e?void 0:e.path))return s;await X.default.writeFile(e.path,s,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(e,t){if(this.puppet.isVue3&&"h5"===process.env.UNI_PLATFORM&&"navigateBack"!==e){const{__id__:s}=await this.callUniMethod(e,{url:t,isAutomatedTesting:!0}),n=Date.now();return await x.default((async()=>{if(Date.now()-n>1e4)throw Error(`${e} to ${t} failed, unable to get the correct current page`);let i;try{i=await this.currentPage()}catch(e){return!1}return i.id===s&&i}),0,1e3)}return await this.callUniMethod(e,{url:t}),await xe(1e3),await this.currentPage()}async socketEmitter(e){return this.appApi.socketEmitter(e)}async adbCommand(e){return"android"===process.env.UNI_APP_PLATFORM?await this.appApi.adbCommand(e):Error("Program.adbCommand is only supported on the app android platform")}}class qe{constructor(e){this.options=e}has(e){return!!this.options[e]}send(e,t,s){const n=this.options[t];if(!n)return Promise.reject(Error(`adapter for ${t} not found`));const i=n.reflect;return i?(n.params&&(s=n.params(s)),"function"==typeof i?i(e.send.bind(e),s):(t=i,e.send(t,s))):Promise.reject(Error(`${t}'s reflect is required`))}}const Fe=C.default("automator:puppet"),Le=".automator.json";function He(e){try{return require(e)}catch(e){}}function We(e,t,s,n){const i=function(e,t,s){let n,i;return process.env.UNI_OUTPUT_DIR?(i=b.default.join(process.env.UNI_OUTPUT_DIR,`../.automator/${t}`,Le),n=He(i)):(i=b.default.join(e,`dist/${s}/.automator/${t}`,Le),n=He(i),n||(i=b.default.join(e,`unpackage/dist/${s}/.automator/${t}`,Le),n=He(i))),Fe(`${i}=>${JSON.stringify(n)}`),n}(e,s,n);if(!i||!i.wsEndpoint)return!1;const o=require("../package.json").version;if(i.version!==o)return Fe(`unmet=>${i.version}!==${o}`),!1;const r=function(e){let t;try{const e=F.default.v4.sync();t=q.default.ip(e&&e.interface),t&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(t)||(t=void 0))}catch(e){}return"ws://"+(t||"localhost")+":"+e}(t);return Fe(`wsEndpoint=>${r}`),i.wsEndpoint===r}class Xe extends a.EventEmitter{constructor(e,t){if(super(),this.isX=!1,this.isVue3=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),t)this.target=t;else{if(this.target=null,"h5"===e)try{this.target=oe("@dcloudio/uni-h5/lib/h5/uni.automator.js")}catch(e){}this.target||(this.target=oe(`@dcloudio/uni-${"app"===e?"app-plus":e}/lib/uni.automator.js`))}if(!this.target)throw Error("puppet is not provided");this.platform=e,this.adapter=new qe(this.target.adapter||{})}setCompiler(e){this.compiler=e}setRuntimeServer(e){this.wss=e}setRemoteRuntimeConnectionCallback(e){this.remoteRuntimeConnectionCallback=e}setRuntimeConnection(e){this.runtimeConnection=e,this.remoteRuntimeConnectionCallback&&(this.remoteRuntimeConnectionCallback(),this.remoteRuntimeConnectionCallback=null)}setDevtoolConnection(e){this.devtoolConnection=e}disposeRuntimeServer(){this.wss&&this.wss.close()}disposeRuntime(){this.runtimeConnection.dispose()}disposeDevtool(){this.compiler&&this.compiler.stop(),this.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(e,t){return this.runtimeConnection.send(e,t)}validateProject(e){const t=this.target.devtools.required;return!t||!t.find((t=>!N.default.existsSync(b.default.join(e,t))))}validateDevtools(e){const t=this.target.devtools.validate;return t?t(e,this):Promise.resolve(e)}createDevtools(e,t,s){const n=this.target.devtools.create;return n?(t.timeout=s,n(e,t,this)):Promise.resolve()}shouldCompile(e,t,s,n){this.compiled=!0;const i=this.target.shouldCompile;if(i)this.compiled=i(s,n);else if(!0===s.compile)this.compiled=!0;else{if("false"===process.env.UNI_AUTOMATOR_COMPILE)return!1;this.compiled=!We(e,t,this.platform,this.mode)}return this.compiled}get checkProperty(){return"mp-weixin"===this.platform}get devtools(){return this.target.devtools}get mode(){const e=this.target.mode;return e||("production"===process.env.NODE_ENV?"build":"dev")}}const Be=C.default("automator:compiler"),Ve=/The\s+(.*)\s+directory is ready/;class Je{constructor(e){this.puppet=e,this.puppet.setCompiler(this)}compile(e){const t=this.puppet.mode,s=this.puppet.platform;let n=e.silent;const i=e.port,o=e.host,r=`${t}:${s}`,a=e.projectPath,[c,p]=this.getSpawnArgs(e,r);p.push("--auto-port"),p.push(K.default(i)),o&&(p.push("--auto-host"),p.push(o));const l={cwd:e.cliPath,env:Object.assign(Object.assign({},process.env),{NODE_ENV:"build"===t?"production":"development"})};return new Promise(((e,i)=>{const o=o=>{const r=o.toString().trim();if(!n&&console.log(r),r.includes("- Network")||r.includes("> Network")||r.includes("➜ Network")){const t=r.match(/Network:(.*)/)[1].trim();Be(`url: ${t}`),e({path:t})}else if(r.includes("DONE Build failed"))i(r);else if(r.includes("DONE Build complete")){const i=r.match(Ve);let o="";if(i&&i.length>1)o=b.default.join(a,i[1]);else{const e=this.puppet.isX&&"app-plus"===s?"app":s;o=b.default.join(a,`dist/${t}/${e}`),U.existsSync(o)||(o=b.default.join(a,`unpackage/dist/${t}/${e}`))}n=!0,this.stop(),e({path:"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW?process.env.UNI_OUTPUT_DIR:o})}};Be(`${c} ${p.join(" ")} %o`,l),this.cliProcess=E.spawn(c,p,l),this.cliProcess.on("error",(e=>{i(e)})),this.cliProcess.stdout.on("data",o),this.cliProcess.stderr.on("data",o)}))}stop(){this.cliProcess&&this.cliProcess.kill("SIGTERM")}getSpawnArgs(e,t){let s;const n=e.cliPath;try{s=require(b.default.join(n,"package.json"))}catch(e){}let i=this.puppet.isX;if(s&&(s.devDependencies&&s.devDependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),!i&&s.dependencies&&s.dependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),s.scripts&&s.scripts[t]))return[process.env.UNI_NPM_PATH||(/^win/.test(process.platform)?"npm.cmd":"npm"),["run",t,"--"]];this.puppet.isVue3=i,["android","ios"].includes(process.env.UNI_OS_NAME)&&(process.env.UNI_APP_PLATFORM=process.env.UNI_OS_NAME);let o=this.puppet.platform;if("app-plus"===this.puppet.platform&&this.puppet.isX&&(o="app"),process.env.UNI_INPUT_DIR=e.projectPath,process.env.UNI_OUTPUT_DIR=b.default.join(e.projectPath,`unpackage/dist/${this.puppet.mode}/${o}`),this.prepare(),process.env.UNI_HBUILDERX_PLUGINS||U.existsSync(b.default.resolve(n,"../about"))&&(process.env.UNI_HBUILDERX_PLUGINS=b.default.dirname(n)),i){const e="app-plus"===this.puppet.platform?"app":this.puppet.platform;return process.env.UNI_PLATFORM=e,[process.env.UNI_NODE_PATH||"node",[require.resolve("@dcloudio/vite-plugin-uni/bin/uni.js",{paths:[n]}),"-p",e]]}return[process.env.UNI_NODE_PATH||"node",[b.default.join(n,"bin/uniapp-cli.js")]]}prepare(){if(process.env.UNI_INPUT_DIR&&"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW){const e=i.parse(U.readFileSync(b.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8")),t=b.default.resolve(process.env.UNI_INPUT_DIR,"unpackage",".automator","app-webview");process.env.UNI_INPUT_DIR=b.default.resolve(t,"src"),process.env.UNI_OUTPUT_DIR=b.default.resolve(t,"unpackage","dist","dev"),U.existsSync(process.env.UNI_INPUT_DIR)&&U.emptyDirSync(process.env.UNI_INPUT_DIR),U.copySync(b.default.resolve(__dirname,"..","lib","app-webview","project"),process.env.UNI_INPUT_DIR);const s=i.parse(U.readFileSync(b.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8"));U.writeFileSync(b.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),JSON.stringify(Object.assign(Object.assign({},s),{name:e.name||"",appid:e.appid||""}),null,2))}}}const Ge=C.default("automator:launcher"),ze="true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM?12e4:24e4;class Ye{async launch(e){const{port:t,cliPath:s,timeout:i,projectPath:o}=await this.validate(e);let r={};"app"===e.platform||"app-plus"===e.platform?(r=e.app||e["app-plus"],"true"===process.env.UNI_APP_X&&r["uni-app-x"]&&(r=n.recursive(!0,r,r["uni-app-x"])),delete r["uni-app-x"]):r=e[e.platform],r||(r={}),r.projectPath=o,Ge(r),this.puppet=new Xe(e.platform,r.puppet),r=await this.puppet.validateDevtools(r);let a=this.puppet.shouldCompile(o,t,e,r),c=process.env.UNI_OUTPUT_DIR||o;if(a||this.puppet.validateProject(c)||(c=b.default.join(o,"dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(c=b.default.join(o,"unpackage/dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(a=!0))),a){this.puppet.compiled=e.compile=!0,this.compiler=new Je(this.puppet);const n=await this.compiler.compile({host:e.host,port:t,cliPath:s,projectPath:o,silent:!!e.silent});n.path&&(c=n.path)}const p=[];return p.push(this.createRuntimeConnection(t,i)),p.push(this.puppet.createDevtools(c,r,i)),new Promise(((e,s)=>{Promise.all(p).then((([s,n])=>{s&&this.puppet.setRuntimeConnection(s),n&&this.puppet.setDevtoolConnection(n),C.default("automator:program")("ready");const i=r.teardown||"disconnect";e(new $e(this.puppet,{teardown:i,port:t}))})).catch((e=>s(e)))}))}resolveCliPath(e){if(!e)return e;try{const{dependencies:t,devDependencies:s}=require(b.default.join(e,"package.json"));if(Ke(s)||Ke(t))return e}catch(e){}}resolveProjectPath(e,t){return e||(e=process.env.UNI_INPUT_DIR||process.cwd()),R.default(e)&&(e=b.default.resolve(e)),N.default.existsSync(e)||function(e){throw Error(e)}(`Project path ${e} doesn't exist`),e}async validate(e){const t=this.resolveProjectPath(e.projectPath,e);let s=process.env.UNI_CLI_PATH||e.cliPath;if(s=this.resolveCliPath(s||""),!s&&(s=this.resolveCliPath(process.cwd())),!s&&(s=this.resolveCliPath(t)),!s)throw Error("cliPath is not provided");if("false"!==process.env.UNI_APP_X){const e=this.getManifestJson(t);("true"===process.env.UNI_APP_X||"uni-app-x"in e)&&(process.env.UNI_APP_X="true",e.appid&&(process.env.UNI_APP_ID=e.appid))}process.env.UNI_AUTOMATOR_HOST&&(e.host=process.env.UNI_AUTOMATOR_HOST),process.env.UNI_AUTOMATOR_PORT&&(e.port=parseInt(process.env.UNI_AUTOMATOR_PORT));return{port:await async function(e,t){const s=await H.default(e||t);if(e&&s!==e)throw Error(`Port ${e} is in use, please specify another port`);return s}(e.port||9520),cliPath:s,timeout:e.timeout||ze,projectPath:t}}getManifestJson(e){if(e){const t=b.default.join(e,"manifest.json");if(N.default.existsSync(t))return i.parse(N.default.readFileSync(t,"utf8"))}return{}}async createRuntimeConnection(e,t){return ae.createRuntimeConnection(e,this.puppet,t)}}function Ke(e){return!!e&&!(!e["@dcloudio/vue-cli-plugin-uni"]&&!e["@dcloudio/vite-plugin-uni"])}exports.Automator=class{constructor(){this.launcher=new Ye}async launch(e){return this.launcher.launch(e)}},exports.initUni=e=>new Proxy({},{get(t,s){return"connectSocket"===s?async(...t)=>{const n=`${Date.now()}-${Math.random()}`;return t[0].id=n,await e.callUniMethod(s,...t).then((s=>{se(t[0],s),te.set(n,new Map);const i={id:n,onMessage:t=>{e.socketEmitter({id:n,method:"onMessage"}),te.get(n).set("onMessage",t)},send:t=>{e.socketEmitter({id:n,method:"send",data:t.data}).then((e=>{se(t,e)})).catch((e=>{ne(t,e)}))},close:t=>{e.socketEmitter({id:n,method:"close",code:t.code,reason:t.reason}).then((e=>{se(t,e),te.delete(n)})).catch((e=>{ne(t,e)}))},onOpen:t=>{e.socketEmitter({id:n,method:"onOpen"}),te.get(n).set("onOpen",t)},onClose:t=>{e.socketEmitter({id:n,method:"onClose"}),te.get(n).set("onClose",t)},onError:t=>{e.socketEmitter({id:n,method:"onError"}),te.get(n).set("onError",t)}};return te.get(n).set("socketTask",i),i})).catch((e=>(ne(t[0],e),null)))}:(n=s,ee.includes(n)?t=>{Z.has(s)||Z.set(s,new Map);const n=Z.get(s),i=`${Date.now()}-${Math.random()}`;n.set(i,t),e.callUniMethod(s,i)}:function(e){return e.startsWith("off")&&ee.includes(e.replace("off","on"))}(s)?async t=>{const n=s.replace("off","on");if(Z.has(n))if(t){const i=Z.get(n);i.forEach(((n,o)=>{n===t&&(i.delete(o),e.callUniMethod(s,o))}))}else Z.delete(n),e.callUniMethod(s)}:async(...t)=>await e.callUniMethod(s,...t).then((e=>(se(t[0],e),e))).catch((e=>(ne(t[0],e),e))));var n}}); +***************************************************************************** */function ct(t,e,n,s){var i,o=arguments.length,r=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(t,e,n,s);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}var pt;function lt(t,e){const n=e.value;return e.value=async function(e){return(await(null==n?void 0:n.call(this,e)))(t)},e}function ut(t,e,n){return lt(pt.RUNTIME,n)}function ht(t,e,n){return lt(pt.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(pt||(pt={}));class dt{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===pt.DEVTOOL?this.puppet.devtoolConnection:this.puppet.runtimeConnection).send(t,e):this.puppet.runtimeConnection.send(t,e)}on(t,e){this.puppet.on(t,e)}}class mt extends dt{constructor(t,e){super(t),this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId,this.videoId=e.videoId}async getData(t){return this.invokeMethod("Element.getData",t)}async setData(t){return this.invokeMethod("Element.setData",t)}async callMethod(t){return this.invokeMethod("Element.callMethod",t)}async getElement(t){return this.invokeMethod("Element.getElement",t)}async getElements(t){return this.invokeMethod("Element.getElements",t)}async getOffset(){return this.invokeMethod("Element.getOffset")}async getHTML(t){return this.invokeMethod("Element.getHTML",t)}async getAttributes(t){return this.invokeMethod("Element.getAttributes",t)}async getStyles(t){return this.invokeMethod("Element.getStyles",t)}async getDOMProperties(t){return this.invokeMethod("Element.getDOMProperties",t)}async getProperties(t){return this.invokeMethod("Element.getProperties",t)}async tap(){return this.invokeMethod("Element.tap")}async longpress(){return this.invokeMethod("Element.longpress")}async touchstart(t){return this.invokeMethod("Element.touchstart",t)}async touchmove(t){return this.invokeMethod("Element.touchmove",t)}async touchend(t){return this.invokeMethod("Element.touchend",t)}async triggerEvent(t){return this.invokeMethod("Element.triggerEvent",t)}async callFunction(t){return this.invokeMethod("Element.callFunction",t)}async callContextMethod(t){return this.invokeMethod("Element.callContextMethod",t)}invokeMethod(t,e={}){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.invoke(t,e)}}ct([ut],mt.prototype,"getData",null),ct([ut],mt.prototype,"setData",null),ct([ut],mt.prototype,"callMethod",null),ct([ht],mt.prototype,"getElement",null),ct([ht],mt.prototype,"getElements",null),ct([ht],mt.prototype,"getOffset",null),ct([ht],mt.prototype,"getHTML",null),ct([ht],mt.prototype,"getAttributes",null),ct([ht],mt.prototype,"getStyles",null),ct([ht],mt.prototype,"getDOMProperties",null),ct([ht],mt.prototype,"getProperties",null),ct([ht],mt.prototype,"tap",null),ct([ht],mt.prototype,"longpress",null),ct([ht],mt.prototype,"touchstart",null),ct([ht],mt.prototype,"touchmove",null),ct([ht],mt.prototype,"touchend",null),ct([ht],mt.prototype,"triggerEvent",null),ct([ht],mt.prototype,"callFunction",null),ct([ht],mt.prototype,"callContextMethod",null);const gt=Object.prototype.hasOwnProperty,yt=Array.isArray,vt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function ft(t,e){if(yt(t))return t;if(e&&(n=e,s=t,gt.call(n,s)))return[t];var n,s;const i=[];return t.replace(vt,(function(t,e,n,s){return i.push(n?s.replace(/\\(\\)?/g,"$1"):e||t),s})),i}function wt(t,e){const n=ft(e,t);let s;for(s=n.shift();null!=s;){if(null==(t=t[s]))return;s=n.shift()}return t}const Pt=require("util"),Mt=["scrollLeft","scrollTop","scrollWidth","scrollHeight"];class It{constructor(t,e,n){this.puppet=t,this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId||null,this.videoId=e.videoId||null,this.tagName=e.tagName,this.nvue=e.nvue,this.elementMap=n,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new mt(t,e)}toJSON(){return JSON.stringify({id:this.id,tagName:this.tagName,pageId:this.pageId,nodeId:this.nodeId,videoId:this.videoId})}toString(){return this.toJSON()}[Pt.inspect.custom](){return this.toJSON()}async $(t){try{const e=await this.api.getElement({selector:t});return It.create(this.puppet,Object.assign({},e,{pageId:this.pageId}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map((t=>It.create(this.puppet,Object.assign({},t,{pageId:this.pageId}),this.elementMap)))}async size(){const[t,e]=await this.domProperty(["offsetWidth","offsetHeight"]);return{width:t,height:e}}async offset(){const{left:t,top:e}=await this.api.getOffset();return{left:t,top:e}}async text(){return this.domProperty("innerText")}async attribute(t){if(!F.default(t))throw Error("name must be a string");return(await this.api.getAttributes({names:[t]})).attributes[0]}async value(){return this.puppet.isX?this.domProperty("value"):this.property("value")}async property(t){if(!F.default(t))throw Error("name must be a string");if(this.puppet.checkProperty){let e=this.publicProps;if(e||(this.publicProps=e=await this._property("__propPublic")),!e[t])throw Error(`${this.tagName}.${t} not exists`)}return this.puppet.isX&&"h5"===process.env.UNI_PLATFORM&&Mt.includes(t)?await this.domProperty(t):this._property(t)}async html(){return(await this.api.getHTML({type:"inner"})).html}async outerHtml(){return(await this.api.getHTML({type:"outer"})).html}async style(t){if(!F.default(t))throw Error("name must be a string");return(await this.api.getStyles({names:[t]})).styles[0]}async tap(){return this.api.tap()}async longpress(){return this.nvue||"true"===process.env.UNI_APP_X?this.api.longpress():(await this.touchstart(),await z.default(350),this.touchend())}async trigger(t,e){const n={type:t};return Y.default(e)||(n.detail=e),this.api.triggerEvent(n)}async touchstart(t){return this.api.touchstart(t)}async touchmove(t){return this.api.touchmove(t)}async touchend(t){return this.api.touchend(t)}async domProperty(t){return it((async t=>(await this.api.getDOMProperties({names:t})).properties),t)}_property(t){return it((async t=>(await this.api.getProperties({names:t})).properties),t)}send(t,e){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.puppet.send(t,e)}async callFunction(t,...e){return(await this.api.callFunction({functionName:t,args:e})).result}static create(t,e,n){let s,i=n.get(e.elementId);if(i)return i;if(e.nodeId)s=kt;else switch(e.tagName.toLowerCase()){case"input":s=Et;break;case"textarea":s=At;break;case"scroll-view":s=_t;break;case"swiper":s=bt;break;case"movable-view":s=Tt;break;case"switch":s=Ct;break;case"slider":s=Ut;break;case"video":s=Nt;break;default:s=It}return i=new s(t,e,n),n.set(e.elementId,i),i}}class kt extends It{async setData(t){return this.api.setData({data:t})}async data(t){const e={};if(t&&(e.path=t),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const n=(await this.api.getData(e)).data;return t?wt(n,t):n}return(await this.api.getData(e)).data}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}}class Et extends It{async input(t){return this.callFunction("input.input",t)}}class At extends It{async input(t){return this.callFunction("textarea.input",t)}}class _t extends It{async scrollTo(t,e){return this.callFunction("scroll-view.scrollTo",t,e)}async property(t){return"scrollTop"===t?this.callFunction("scroll-view.scrollTop"):"scrollLeft"===t?this.callFunction("scroll-view.scrollLeft"):super.property(t)}async scrollWidth(){return this.callFunction("scroll-view.scrollWidth")}async scrollHeight(){return this.callFunction("scroll-view.scrollHeight")}}class bt extends It{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class Tt extends It{async moveTo(t,e){return this.callFunction("movable-view.moveTo",t,e)}async property(t){return"x"===t?this._property("_translateX"):"y"===t?this._property("_translateY"):super.property(t)}}class Ct extends It{async tap(){return this.callFunction("switch.tap")}}class Ut extends It{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class Nt extends It{async callContextMethod(t,...e){return await this.api.callContextMethod({method:t,args:e})}}class Ot extends dt{constructor(t,e){super(t),this.id=e.id}async getData(t){return this.invokeMethod("Page.getData",t)}async setData(t){return this.invokeMethod("Page.setData",t)}async callMethod(t){return this.invokeMethod("Page.callMethod",t)}async callMethodWithCallback(t){return this.invokeMethod("Page.callMethodWithCallback",t)}async getElement(t){return this.invokeMethod("Page.getElement",t)}async getElements(t){return this.invokeMethod("Page.getElements",t)}async getWindowProperties(t){return this.invokeMethod("Page.getWindowProperties",t)}invokeMethod(t,e={}){return e.pageId=this.id,this.invoke(t,e)}}ct([ut],Ot.prototype,"getData",null),ct([ut],Ot.prototype,"setData",null),ct([ut],Ot.prototype,"callMethod",null),ct([ut],Ot.prototype,"callMethodWithCallback",null),ct([ht],Ot.prototype,"getElement",null),ct([ht],Ot.prototype,"getElements",null),ct([ht],Ot.prototype,"getWindowProperties",null);const Rt=require("util");class St{constructor(t,e){this.puppet=t,this.id=e.id,this.path=e.path,this.query=e.query,this.elementMap=new Map,this.api=new Ot(t,e)}toJSON(){return JSON.stringify({id:this.id,path:this.path,query:this.query})}toString(){return this.toJSON()}[Rt.inspect.custom](){return this.toJSON()}async waitFor(t){return G.default(t)?await z.default(t):B.default(t)?x.default(t,0,50):F.default(t)?x.default((async()=>{if("true"===process.env.UNI_APP_X){return!!await this.$(t)}return(await this.$$(t)).length>0}),0,50):void 0}async $(t){try{const e=await this.api.getElement({selector:t});return It.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map((e=>It.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)))}async data(t){const e={};if(t&&(e.path=t),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const n=(await this.api.getData(e)).data;return t?wt(n,t):n}return(await this.api.getData(e)).data}async setData(t){return this.api.setData({data:t})}async size(){const[t,e]=await this.windowProperty(["document.documentElement.scrollWidth","document.documentElement.scrollHeight"]);return{width:t,height:e}}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}async callMethodWithCallback(t,...e){return await this.api.callMethodWithCallback({method:t,args:e})}async scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(t){const e=F.default(t);e&&(t=[t]);const{properties:n}=await this.api.getWindowProperties({names:t});return e?n[0]:n}static create(t,e,n){let s=n.get(e.id);return s?(s.path=e.path,s.query=e.query,s):(s=new St(t,e),n.set(e.id,s),s)}}class Dt extends dt{async getPageStack(){return this.invoke("App.getPageStack")}async callUniMethod(t){return this.invoke("App.callUniMethod",t)}async getCurrentPage(){return this.invoke("App.getCurrentPage")}async mockUniMethod(t){return this.invoke("App.mockUniMethod",t)}async captureScreenshotByRuntime(t){return this.invoke("App.captureScreenshot",t)}async captureScreenshotWithDeviceByRuntime(t){return this.invoke("App.captureScreenshotWithDevice",t)}async socketEmitter(t){return this.invoke("App.socketEmitter",t)}async callFunction(t){return this.invoke("App.callFunction",t)}async captureScreenshot(t){return this.invoke("App.captureScreenshot",t)}async adbCommand(t){return this.invoke("App.adbCommand",t)}async exit(){return this.invoke("App.exit")}async addBinding(t){return this.invoke("App.addBinding",t)}async enableLog(){return this.invoke("App.enableLog")}onLogAdded(t){return this.on("App.logAdded",t)}onBindingCalled(t){return this.on("App.bindingCalled",t)}onExceptionThrown(t){return this.on("App.exceptionThrown",t)}}ct([ut],Dt.prototype,"getPageStack",null),ct([ut],Dt.prototype,"callUniMethod",null),ct([ut],Dt.prototype,"getCurrentPage",null),ct([ut],Dt.prototype,"mockUniMethod",null),ct([ut],Dt.prototype,"captureScreenshotByRuntime",null),ct([ut],Dt.prototype,"captureScreenshotWithDeviceByRuntime",null),ct([ut],Dt.prototype,"socketEmitter",null),ct([ht],Dt.prototype,"callFunction",null),ct([ht],Dt.prototype,"captureScreenshot",null),ct([ht],Dt.prototype,"adbCommand",null),ct([ht],Dt.prototype,"exit",null),ct([ht],Dt.prototype,"addBinding",null),ct([ht],Dt.prototype,"enableLog",null);class jt extends dt{async getInfo(){return this.invoke("Tool.getInfo")}async enableRemoteDebug(t){return this.invoke("Tool.enableRemoteDebug")}async close(){return this.invoke("Tool.close")}async getTestAccounts(){return this.invoke("Tool.getTestAccounts")}onRemoteDebugConnected(t){this.puppet.once("Tool.onRemoteDebugConnected",t),this.puppet.once("Tool.onPreviewConnected",t)}}function xt(t){return new Promise((e=>setTimeout(e,t)))}ct([ht],jt.prototype,"getInfo",null),ct([ht],jt.prototype,"enableRemoteDebug",null),ct([ht],jt.prototype,"close",null),ct([ht],jt.prototype,"getTestAccounts",null);class $t extends a.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new Dt(t),this.toolApi=new jt(t),this.appApi.onLogAdded((t=>{this.emit("console",t)})),this.appApi.onBindingCalled((({name:t,args:e})=>{try{const n=this.appBindings.get(t);n&&n(...e)}catch(t){}})),this.appApi.onExceptionThrown((t=>{this.emit("exception",t)}))}async pageStack(){return(await this.appApi.getPageStack()).pageStack.map((t=>St.create(this.puppet,t,this.pageMap)))}async navigateTo(t){return this.changeRoute("navigateTo",t)}async redirectTo(t){return this.changeRoute("redirectTo",t)}async navigateBack(){return this.changeRoute("navigateBack")}async reLaunch(t){return this.changeRoute("reLaunch",t)}async switchTab(t){return this.changeRoute("switchTab",t)}async currentPage(){const{id:t,path:e,query:n}=await this.appApi.getCurrentPage();return St.create(this.puppet,{id:t,path:e,query:n},this.pageMap)}async systemInfo(){return this.callUniMethod("getSystemInfoSync")}async callUniMethod(t,...e){return(await this.appApi.callUniMethod({method:t,args:e})).result}async mockUniMethod(t,e,...n){return B.default(e)||(s=e,F.default(s)&&(s=V.default(s),J.default(s,"function")||J.default(s,"() =>")))?this.appApi.mockUniMethod({method:t,functionDeclaration:e.toString(),args:n}):this.appApi.mockUniMethod({method:t,result:e});var s}async restoreUniMethod(t){return this.appApi.mockUniMethod({method:t})}async evaluate(t,...e){return(await this.appApi.callFunction({functionDeclaration:t.toString(),args:e})).result}async pageScrollTo(t){await this.callUniMethod("pageScrollTo",{scrollTop:t,duration:0})}async close(){try{await this.appApi.exit()}catch(t){}await xt(1e3),this.puppet.disposeRuntimeServer(),await this.toolApi.close(),this.disconnect()}async teardown(){return this["disconnect"===this.options.teardown?"disconnect":"close"]()}async remote(t){if(!this.puppet.devtools.remote)return console.warn(`Failed to enable remote, ${this.puppet.devtools.name} is unimplemented`);const{qrCode:e}=await this.toolApi.enableRemoteDebug({auto:t});var n;e&&await(n=e,new Promise((t=>{W.default.generate(n,{small:!0},(e=>{process.stdout.write(e),t(void 0)}))})));const s=new Promise((t=>{this.toolApi.onRemoteDebugConnected((async()=>{await xt(1e3),t(void 0)}))})),i=new Promise((t=>{this.puppet.setRemoteRuntimeConnectionCallback((()=>{t(void 0)}))}));return Promise.all([s,i])}disconnect(){this.puppet.dispose()}on(t,e){return"console"===t&&this.appApi.enableLog(),super.on(t,e),this}async exposeFunction(t,e){if(this.appBindings.has(t))throw Error(`Failed to expose function with name ${t}: already exists!`);this.appBindings.set(t,e),await this.appApi.addBinding({name:t})}async checkVersion(){}async screenshot(t){const e=this.puppet.isX&&"app-plus"===this.puppet.platform?(null==t?void 0:t.deviceShot)?"captureScreenshotWithDeviceByRuntime":"captureScreenshotByRuntime":"captureScreenshot",{data:n}=await this.appApi[e]({id:null==t?void 0:t.id,fullPage:null==t?void 0:t.fullPage,area:null==t?void 0:t.area,offsetX:null==t?void 0:t.offsetX,offsetY:null==t?void 0:t.offsetY});if(!(null==t?void 0:t.path))return n;await X.default.writeFile(t.path,n,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(t,e){if(this.puppet.isVue3&&"h5"===process.env.UNI_PLATFORM&&"navigateBack"!==t){const{__id__:n}=await this.callUniMethod(t,{url:e,isAutomatedTesting:!0}),s=Date.now();return await x.default((async()=>{if(Date.now()-s>1e4)throw Error(`${t} to ${e} failed, unable to get the correct current page`);let i;try{i=await this.currentPage()}catch(t){return!1}return i.id===n&&i}),0,1e3)}return await this.callUniMethod(t,{url:e}),await xt(1e3),await this.currentPage()}async socketEmitter(t){return this.appApi.socketEmitter(t)}async adbCommand(t){return"android"===process.env.UNI_APP_PLATFORM?await this.appApi.adbCommand(t):Error("Program.adbCommand is only supported on the app android platform")}}class qt{constructor(t){this.options=t}has(t){return!!this.options[t]}send(t,e,n){const s=this.options[e];if(!s)return Promise.reject(Error(`adapter for ${e} not found`));const i=s.reflect;return i?(s.params&&(n=s.params(n)),"function"==typeof i?i(t.send.bind(t),n):(e=i,t.send(e,n))):Promise.reject(Error(`${e}'s reflect is required`))}}const Lt=N.default("automator:puppet"),Ft=".automator.json";function Ht(t){try{return require(t)}catch(t){}}function Wt(t,e,n,s){const i=function(t,e,n){let s,i;return process.env.UNI_OUTPUT_DIR?(i=U.default.join(process.env.UNI_OUTPUT_DIR,`../.automator/${e}`,Ft),s=Ht(i)):(i=U.default.join(t,`dist/${n}/.automator/${e}`,Ft),s=Ht(i),s||(i=U.default.join(t,`unpackage/dist/${n}/.automator/${e}`,Ft),s=Ht(i))),Lt(`${i}=>${JSON.stringify(s)}`),s}(t,n,s);if(!i||!i.wsEndpoint)return!1;const o=require("../package.json").version;if(i.version!==o)return Lt(`unmet=>${i.version}!==${o}`),!1;const r=function(t){let e;try{const t=L.default.v4.sync();e=q.default.ip(t&&t.interface),e&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(e)||(e=void 0))}catch(t){}return"ws://"+(e||"localhost")+":"+t}(e);return Lt(`wsEndpoint=>${r}`),i.wsEndpoint===r}class Xt extends a.EventEmitter{constructor(t,e){if(super(),this.isX=!1,this.isVue3=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),e)this.target=e;else{if(this.target=null,"h5"===t)try{this.target=ot("@dcloudio/uni-h5/lib/h5/uni.automator.js")}catch(t){}this.target||(this.target=ot(`@dcloudio/uni-${"app"===t?"app-plus":t}/lib/uni.automator.js`))}if(!this.target)throw Error("puppet is not provided");this.platform=t,this.adapter=new qt(this.target.adapter||{})}setCompiler(t){this.compiler=t}setRuntimeServer(t){this.wss=t}setRemoteRuntimeConnectionCallback(t){this.remoteRuntimeConnectionCallback=t}setRuntimeConnection(t){this.runtimeConnection=t,this.remoteRuntimeConnectionCallback&&(this.remoteRuntimeConnectionCallback(),this.remoteRuntimeConnectionCallback=null)}setDevtoolConnection(t){this.devtoolConnection=t}disposeRuntimeServer(){this.wss&&this.wss.close()}disposeRuntime(){this.runtimeConnection.dispose()}disposeDevtool(){this.compiler&&this.compiler.stop(),this.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(t,e){return this.runtimeConnection.send(t,e)}validateProject(t){const e=this.target.devtools.required;return!e||!e.find((e=>!C.default.existsSync(U.default.join(t,e))))}validateDevtools(t){const e=this.target.devtools.validate;return e?e(t,this):Promise.resolve(t)}createDevtools(t,e,n){const s=this.target.devtools.create;return s?(e.timeout=n,s(t,e,this)):Promise.resolve()}shouldCompile(t,e,n,s){this.compiled=!0;const i=this.target.shouldCompile;if(i)this.compiled=i(n,s);else if(!0===n.compile)this.compiled=!0;else{if("false"===process.env.UNI_AUTOMATOR_COMPILE)return!1;this.compiled=!Wt(t,e,this.platform,this.mode)}return this.compiled}beforeCompile(){this.target.beforeCompile&&this.target.beforeCompile()}afterCompile(){this.target.afterCompile&&this.target.afterCompile()}get checkProperty(){return"mp-weixin"===this.platform}get devtools(){return this.target.devtools}get mode(){const t=this.target.mode;return t||("production"===process.env.NODE_ENV?"build":"dev")}}const Bt=N.default("automator:compiler"),Vt=/The\s+(.*)\s+directory is ready/;class Jt{constructor(t){this.puppet=t,this.puppet.setCompiler(this)}compile(t){const e=this.puppet.mode,n=this.puppet.platform;let s=t.silent;const i=t.port,o=t.host,r=`${e}:${n}`,a=t.projectPath,[c,p]=this.getSpawnArgs(t,r);p.push("--auto-port"),p.push(K.default(i)),o&&(p.push("--auto-host"),p.push(o));const l={cwd:t.cliPath,env:Object.assign(Object.assign({},process.env),{NODE_ENV:"build"===e?"production":"development"})};return new Promise(((t,i)=>{const o=o=>{const r=o.toString().trim();if(!s&&console.log(r),r.includes("- Network")||r.includes("> Network")||r.includes("➜ Network")){const e=r.match(/Network:(.*)/)[1].trim();Bt(`url: ${e}`),t({path:e})}else if(r.includes("DONE Build failed"))i(r);else if(r.includes("DONE Build complete")){const i=r.match(Vt);let o="";if(i&&i.length>1)o=U.default.join(a,i[1]);else{const t=this.puppet.isX&&"app-plus"===n?"app":n;o=U.default.join(a,`dist/${e}/${t}`),b.existsSync(o)||(o=U.default.join(a,`unpackage/dist/${e}/${t}`))}this.puppet.afterCompile(),s=!0,this.stop(),t({path:"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW?process.env.UNI_OUTPUT_DIR:o})}};Bt(`${c} ${p.join(" ")} %o`,l),this.cliProcess=A.spawn(c,p,l),this.cliProcess.on("error",(t=>{i(t)})),this.cliProcess.stdout.on("data",o),this.cliProcess.stderr.on("data",o)}))}stop(){this.cliProcess&&this.cliProcess.kill("SIGTERM")}getSpawnArgs(t,e){let n;const s=t.cliPath;try{n=require(U.default.join(s,"package.json"))}catch(t){}let i=this.puppet.isX;if(n&&(n.devDependencies&&n.devDependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),!i&&n.dependencies&&n.dependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),n.scripts&&n.scripts[e]))return[process.env.UNI_NPM_PATH||(/^win/.test(process.platform)?"npm.cmd":"npm"),["run",e,"--"]];this.puppet.isVue3=i,["android","ios"].includes(process.env.UNI_OS_NAME)&&(process.env.UNI_APP_PLATFORM=process.env.UNI_OS_NAME);let o=this.puppet.platform;if("app-plus"===this.puppet.platform&&this.puppet.isX&&(o="app"),process.env.UNI_INPUT_DIR=t.projectPath,process.env.UNI_OUTPUT_DIR=U.default.join(t.projectPath,`unpackage/dist/${this.puppet.mode}/${o}`),process.env.UNI_HBUILDERX_PLUGINS||b.existsSync(U.default.resolve(s,"../about"))&&(process.env.UNI_HBUILDERX_PLUGINS=U.default.dirname(s)),this.puppet.beforeCompile(),i){const t="app-plus"===this.puppet.platform?"app":this.puppet.platform;return process.env.UNI_PLATFORM=t,[process.env.UNI_NODE_PATH||"node",[require.resolve("@dcloudio/vite-plugin-uni/bin/uni.js",{paths:[s]}),"-p",t]]}return[process.env.UNI_NODE_PATH||"node",[U.default.join(s,"bin/uniapp-cli.js")]]}}const Gt=N.default("automator:launcher"),zt="true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM?12e4:24e4;class Yt{async launch(t){const{port:e,cliPath:n,timeout:i,projectPath:o}=await this.validate(t);let r={};"app"===t.platform||"app-plus"===t.platform?(r=t.app||t["app-plus"],"true"===process.env.UNI_APP_X&&r["uni-app-x"]&&(r=s.recursive(!0,r,r["uni-app-x"])),delete r["uni-app-x"]):r=t[t.platform],r||(r={}),r.projectPath=o,Gt(r),this.puppet=new Xt(t.platform,r.puppet),r=await this.puppet.validateDevtools(r);let a=this.puppet.shouldCompile(o,e,t,r),c=process.env.UNI_OUTPUT_DIR||o;if(a||this.puppet.validateProject(c)||(c=U.default.join(o,"dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(c=U.default.join(o,"unpackage/dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(a=!0))),a){this.puppet.compiled=t.compile=!0,this.compiler=new Jt(this.puppet);const s=await this.compiler.compile({host:t.host,port:e,cliPath:n,projectPath:o,silent:!!t.silent});s.path&&(c=s.path)}const p=[];return p.push(this.createRuntimeConnection(e,i)),p.push(this.puppet.createDevtools(c,r,i)),new Promise(((t,n)=>{Promise.all(p).then((([n,s])=>{n&&this.puppet.setRuntimeConnection(n),s&&this.puppet.setDevtoolConnection(s),N.default("automator:program")("ready");const i=r.teardown||"disconnect";t(new $t(this.puppet,{teardown:i,port:e}))})).catch((t=>n(t)))}))}resolveCliPath(t){if(!t)return t;try{const{dependencies:e,devDependencies:n}=require(U.default.join(t,"package.json"));if(Kt(n)||Kt(e))return t}catch(t){}}resolveProjectPath(t,e){return t||(t=process.env.UNI_INPUT_DIR||process.cwd()),O.default(t)&&(t=U.default.resolve(t)),C.default.existsSync(t)||function(t){throw Error(t)}(`Project path ${t} doesn't exist`),t}async validate(t){const e=this.resolveProjectPath(t.projectPath,t);let n=process.env.UNI_CLI_PATH||t.cliPath;if(n=this.resolveCliPath(n||""),!n&&(n=this.resolveCliPath(process.cwd())),!n&&(n=this.resolveCliPath(e)),!n)throw Error("cliPath is not provided");if("false"!==process.env.UNI_APP_X){const t=this.getManifestJson(e);("true"===process.env.UNI_APP_X||"uni-app-x"in t)&&(process.env.UNI_APP_X="true",t.appid&&(process.env.UNI_APP_ID=t.appid))}process.env.UNI_AUTOMATOR_HOST&&(t.host=process.env.UNI_AUTOMATOR_HOST),process.env.UNI_AUTOMATOR_PORT&&(t.port=parseInt(process.env.UNI_AUTOMATOR_PORT));return{port:await async function(t,e){const n=await H.default(t||e);if(t&&n!==t)throw Error(`Port ${t} is in use, please specify another port`);return n}(t.port||9520),cliPath:n,timeout:t.timeout||zt,projectPath:e}}getManifestJson(t){if(t){const e=U.default.join(t,"manifest.json");if(C.default.existsSync(e))return i.parse(C.default.readFileSync(e,"utf8"))}return{}}async createRuntimeConnection(t,e){return at.createRuntimeConnection(t,this.puppet,e)}}function Kt(t){return!!t&&!(!t["@dcloudio/vue-cli-plugin-uni"]&&!t["@dcloudio/vite-plugin-uni"])}exports.Automator=class{constructor(){this.launcher=new Yt}async launch(t){return this.launcher.launch(t)}},exports.initUni=t=>new Proxy({},{get(e,n){return"connectSocket"===n?async(...e)=>{const s=`${Date.now()}-${Math.random()}`;return e[0].id=s,await t.callUniMethod(n,...e).then((n=>{nt(e[0],n),et.set(s,new Map);const i={id:s,onMessage:e=>{t.socketEmitter({id:s,method:"onMessage"}),et.get(s).set("onMessage",e)},send:e=>{t.socketEmitter({id:s,method:"send",data:e.data}).then((t=>{nt(e,t)})).catch((t=>{st(e,t)}))},close:e=>{t.socketEmitter({id:s,method:"close",code:e.code,reason:e.reason}).then((t=>{nt(e,t),et.delete(s)})).catch((t=>{st(e,t)}))},onOpen:e=>{t.socketEmitter({id:s,method:"onOpen"}),et.get(s).set("onOpen",e)},onClose:e=>{t.socketEmitter({id:s,method:"onClose"}),et.get(s).set("onClose",e)},onError:e=>{t.socketEmitter({id:s,method:"onError"}),et.get(s).set("onError",e)}};return et.get(s).set("socketTask",i),i})).catch((t=>(st(e[0],t),null)))}:(s=n,tt.includes(s)?e=>{Z.has(n)||Z.set(n,new Map);const s=Z.get(n),i=`${Date.now()}-${Math.random()}`;s.set(i,e),t.callUniMethod(n,i)}:function(t){return t.startsWith("off")&&tt.includes(t.replace("off","on"))}(n)?async e=>{const s=n.replace("off","on");if(Z.has(s))if(e){const i=Z.get(s);i.forEach(((s,o)=>{s===e&&(i.delete(o),t.callUniMethod(n,o))}))}else Z.delete(s),t.callUniMethod(n)}:async(...e)=>await t.callUniMethod(n,...e).then((t=>(nt(e[0],t),t))).catch((t=>(st(e[0],t),t))));var s}}); diff --git a/packages/uni-h5/dist/automator.js b/packages/uni-h5/dist/automator.js index 5716867000aad2f2b7023ca0a9353b3b1c2ed457..34cecbbd7c23f742007a908800e31a7df012e8c4 100644 --- a/packages/uni-h5/dist/automator.js +++ b/packages/uni-h5/dist/automator.js @@ -12,4 +12,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -var e=function(){return e=Object.assign||function(e){for(var n,t=1,r=arguments.length;t]*>)(]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1":""===e?"":0!==e.indexOf("0)return R(e({method:r.replace("Socket","")},o[0])).then((function(e){return n(e)})).catch((function(e){return i(e)}));if(!uni[r])return i(Error("uni."+r+" not exists"));if(G(r))return n({result:uni[r].apply(uni,o)});var p=[Object.assign({},o[0]||{},{success:function(e){setTimeout((function(){n({result:e})}),"pageScrollTo"===r?350:0)},fail:function(e){i(Error(e.errMsg.replace(r+":fail ","")))}})];uni[r].apply(uni,p)}else(u=o[0].id,a=o[0].url,new Promise((function(e,n){var t=uni.connectSocket({url:a,success:function(){e({result:{errMsg:"connectSocket:ok"}})},fail:function(){n({result:{errMsg:"connectSocket:fail"}})}});L.set(u,{instance:t,isOpend:!1}),t.onOpen((function(e){L.get(u).isOpend=!0,L.get(u).openData=e}))}))).then((function(e){return n(e)})).catch((function(e){return i(e)}))}))},mockUniMethod:function(e){var n=e.method;if(!uni[n])throw Error("uni."+n+" not exists");if(!function(e){return!z.test(e)}(n))throw Error("You can't mock uni."+n);var t,r=e.result,o=e.functionDeclaration;return s(r)&&s(o)?(F[n]&&(uni[n]=F[n],delete F[n]),Promise.resolve()):(t=s(o)?G(n)?function(){return r}:function(e){setTimeout((function(){r.errMsg&&-1!==r.errMsg.indexOf(":fail")?e.fail&&e.fail(r):e.success&&e.success(r),e.complete&&e.complete(r)}),4)}:function(){for(var n=[],r=0;r]*>)(]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1":""===e?"":0!==e.indexOf("0)return R(e({method:r.replace("Socket","")},o[0])).then((function(e){return n(e)})).catch((function(e){return i(e)}));if(!uni[r])return i(Error("uni."+r+" not exists"));if(G(r))return n({result:uni[r].apply(uni,o)});var p=[Object.assign({},o[0]||{},{success:function(e){setTimeout((function(){n({result:e})}),"pageScrollTo"===r?350:0)},fail:function(e){i(Error(e.errMsg.replace(r+":fail ","")))}})];uni[r].apply(uni,p)}else(u=o[0].id,a=o[0].url,new Promise((function(e,n){var t=uni.connectSocket({url:a,success:function(){e({result:{errMsg:"connectSocket:ok"}})},fail:function(){n({result:{errMsg:"connectSocket:fail"}})}});L.set(u,{instance:t,isOpend:!1}),t.onOpen((function(e){L.get(u).isOpend=!0,L.get(u).openData=e}))}))).then((function(e){return n(e)})).catch((function(e){return i(e)}))}))},mockUniMethod:function(e){var n=e.method;if(!uni[n])throw Error("uni."+n+" not exists");if(!function(e){return!z.test(e)}(n))throw Error("You can't mock uni."+n);var t,r=e.result,o=e.functionDeclaration;return s(r)&&s(o)?(F[n]&&(uni[n]=F[n],delete F[n]),Promise.resolve()):(t=s(o)?G(n)?function(){return r}:function(e){setTimeout((function(){r.errMsg&&-1!==r.errMsg.indexOf(":fail")?e.fail&&e.fail(r):e.success&&e.success(r),e.complete&&e.complete(r)}),4)}:function(){for(var n=[],r=0;r0)return firstSocketTaskEmitter(__assign({method:method.replace("Socket","")},args[0])).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}));if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}else(id=args[0].id,url=args[0].url,new Promise((function(resolve,reject){var socketTask=uni.connectSocket({url:url,success:function(){resolve({result:{errMsg:"connectSocket:ok"}})},fail:function(){reject({result:{errMsg:"connectSocket:fail"}})}});socketInstanceMap.set(id,{instance:socketTask,isOpend:!1}),socketTask.onOpen((function(data){socketInstanceMap.get(id).isOpend=!0,socketInstanceMap.get(id).openData=data}))}))).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}))}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(var args=[],_i=0;_i0)return firstSocketTaskEmitter(__assign({method:method.replace("Socket","")},args[0])).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}));if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}else(id=args[0].id,url=args[0].url,new Promise((function(resolve,reject){var socketTask=uni.connectSocket({url:url,success:function(){resolve({result:{errMsg:"connectSocket:ok"}})},fail:function(){reject({result:{errMsg:"connectSocket:fail"}})}});socketInstanceMap.set(id,{instance:socketTask,isOpend:!1}),socketTask.onOpen((function(data){socketInstanceMap.get(id).isOpend=!0,socketInstanceMap.get(id).openData=data}))}))).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}))}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(var args=[],_i=0;_i0)return firstSocketTaskEmitter(__assign({method:method.replace("Socket","")},args[0])).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}));if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}else(id=args[0].id,url=args[0].url,new Promise((function(resolve,reject){var socketTask=uni.connectSocket({url:url,success:function(){resolve({result:{errMsg:"connectSocket:ok"}})},fail:function(){reject({result:{errMsg:"connectSocket:fail"}})}});socketInstanceMap.set(id,{instance:socketTask,isOpend:!1}),socketTask.onOpen((function(data){socketInstanceMap.get(id).isOpend=!0,socketInstanceMap.get(id).openData=data}))}))).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}))}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(var args=[],_i=0;_i0)return firstSocketTaskEmitter(__assign({method:method.replace("Socket","")},args[0])).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}));if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}else(id=args[0].id,url=args[0].url,new Promise((function(resolve,reject){var socketTask=uni.connectSocket({url:url,success:function(){resolve({result:{errMsg:"connectSocket:ok"}})},fail:function(){reject({result:{errMsg:"connectSocket:fail"}})}});socketInstanceMap.set(id,{instance:socketTask,isOpend:!1}),socketTask.onOpen((function(data){socketInstanceMap.get(id).isOpend=!0,socketInstanceMap.get(id).openData=data}))}))).then((function(res){return resolve(res)})).catch((function(err){return reject(err)}))}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(var args=[],_i=0;_i