提交 42e56a72 编写于 作者: DCloud-WZF's avatar DCloud-WZF 💬

wip(uts): automator uni api

上级 97a83a8f
此差异已折叠。
var CALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){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)}))},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&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(params){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/png;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}),{wholeContent:!!params.fullPage})}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))},callMethodWithCallback:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="callMethodWithCallback:fail, Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="callMethodWithCallback:fail, page."+params.method+" not exists",_a),callback=params.args[params.args.length-1];callMethod(getPageVm(params.pageId),params.method,params.args).catch((function(type){callback({errMsg:err[type]})}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},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 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&&!fn)return data.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];return params.args.push((function(result){null!==result&&(data.result=result),send(data)})),void fn(params)}fn(params).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)}}swan.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url: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")}))},setTimeout((function(){swan.$$initRuntimeAutomator()}),500);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
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.
***************************************************************************** */
var CALL_METHOD_ERROR,__assign=function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t},__assign.apply(this,arguments)},hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],onApisEventMap=new Map,ON_APIS=["onCompassChange","onThemeChange","onUserCaptureScreen","onWindowResize","onMemoryWarning","onAccelerometerChange","onKeyboardHeightChange","onNetworkStatusChange","onPushMessage","onLocationChange","onGetWifiList","onWifiConnected","onWifiConnectedWithPartialInfo"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){if(ON_APIS.includes(method)){onApisEventMap.has(method)||onApisEventMap.set(method,new Map);var uuid_1=args[0],callback=function(res){send({id:uuid_1,result:__assign({method:method},res)})};return onApisEventMap.get(method).set(uuid_1,callback),uni[method](callback),resolve({result:null})}if(method.startsWith("off")&&ON_APIS.includes(method.replace("off","on"))){var onMethod=method.replace("off","on");if(onApisEventMap.has(onMethod)){var uuid=args[0];if(void 0!==uuid){callback=onApisEventMap.get(onMethod).get(uuid);uni[method](callback),onApisEventMap.get(onMethod).delete(uuid)}else{onApisEventMap.get(onMethod).forEach((function(callback){uni[method](callback)})),onApisEventMap.delete(onMethod)}}return resolve({result:null})}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)}))},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&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(params){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/png;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}),{wholeContent:!!params.fullPage})}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))},callMethodWithCallback:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="callMethodWithCallback:fail, Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="callMethodWithCallback:fail, page."+params.method+" not exists",_a),callback=params.args[params.args.length-1];callMethod(getPageVm(params.pageId),params.method,params.args).catch((function(type){callback({errMsg:err[type]})}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},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 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&&!fn)return data.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];return params.args.push((function(result){null!==result&&(data.result=result),send(data)})),void fn(params)}fn(params).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)}}swan.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url: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")}))},setTimeout((function(){swan.$$initRuntimeAutomator()}),500);export{send};
"use strict";var e=require("os"),t=require("path"),s=require("debug"),a=require("licia/isWindows"),r=require("fs"),n=require("child_process"),o=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/getPort"),p=require("licia/dateFormat"),m=require("ws"),d=require("events"),f=require("licia/uuid"),h=require("licia/stringify");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=g(e),y=g(t),E=g(s),b=g(a),v=g(r),P=g(n),j=g(o),O=g(i),$=g(c),M=g(l),q=g(u),C=g(p),A=g(m),S=g(f),T=g(h);const L=/(^[a-z][a-z0-9-]*)/i,H=/^navigator/i,R=/^swan-nav$/i;var N;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(N||(N={}));const k={[N.SELECTOR]:[{test:H,processor:e=>e.replace(H,"nav")},{test:L,processor:e=>`swan-${e}`}],[N.TAGNAME]:[{test:R,processor:e=>e.replace(R,"swan-navigator")},{test:L,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},x=e=>t=>{const s=(k[e]||[]).filter((e=>e.test.test(t)));for(const e of s)t=e.processor(t);return t},D=x(N.SELECTOR),F=x(N.TAGNAME),I=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});/^win/.test(process.platform);class B extends d.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 G="Connection closed";class W extends d.EventEmitter{constructor(e,t,s){super(),this.puppet=t,this.namespace=s,this.callbacks=new Map,this.transport=e,this.debug=E.default("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:s,error:a,result:r,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(s,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),a?e.reject(Error(a.message||a.detailMessage)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(G))}))},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 a=S.default(),r=T.default({id:a,method:e,params:t});return this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),new Promise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(G))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((s,a)=>{const r=new A.default(e);r.addEventListener("open",(()=>{s(new W(new B(r),t,"devtool"))})),r.addEventListener("error",a)}))}static createRuntimeConnection(e,t,s){return new Promise(((a,r)=>{E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new A.default.Server({port:e});$.default((async()=>{if(t.runtimeConnection)return!0}),s,1e3).catch((()=>{n.close(),r("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const s=new W(new B(e),t,"runtime");t.setRuntimeConnection(s),a(s)})),t.setRuntimeServer(n)}))}}const z=E.default("automator:devtool");async function J(e,t,s){const{port:a,cliPath:r,timeout:n,cwd:o="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,p=!1;if(!1!==l){const t={stdio:"ignore"};o&&(t.cwd=o);let s=M.default(c,[]);s=M.default(s,["--auto"]),s=M.default(s,[e,"--auto-port",O.default(a)]),i&&(s=M.default(s,["--auto-account",i]));try{z("%s %o %o",r,s,t);const e=P.default.spawn(r,s,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{p=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{p=!0}),15e3);const m=await $.default((async()=>{try{if(u||p)return!0;const e=await async function(e,t){let s;try{s=await W.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return s}({wsEndpoint:`ws://127.0.0.1:${a}`},s);return e}catch(e){}}),n,1e3);if(u)throw Error(`Failed to launch ${s.devtools.name}, please make sure cliPath is correctly specified`);if(p)throw Error(`Failed to launch ${s.devtools.name} , please make sure http port is open`);return await j.default(5e3),z(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`),m}const U=[];["","-rc"].forEach((e=>{b.default?(U.push(y.default.join(w.default.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),U.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):U.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)}));const V={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:U,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const s=function(e,t){const s=t.devtools.paths.slice(0);e&&s.unshift(e);for(const e of s)if(v.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let a=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=await async function(e,t){const s=await q.default(e||t);if(e&&s!==e)throw Error(`Port ${e} is in use, please specify another port`);return s}(a)}catch(t){e.launch=!1}else{a===await q.default(a)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:a,cliPath:s})},async create(e,t,s){const a=await J(e,t,s);return s.compiled?E.default("automator:devtool")("Waiting for runtime automator"):(E.default("automator:devtool")("initRuntimeAutomator"),a.send("smartapp.swan",{api:"$$initRuntimeAutomator",params:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async e=>({qrCode:(await e("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(await e("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(await e("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(s=t.selector,s.split(" ").map((e=>D(e))).join(" "))}))).map((e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:F(t.tagName)}}))};var s}},"Page.getWindowProperties":{reflect:async(e,t)=>{const s=t.names.map((e=>e.replace("document.documentElement.",""))),a=(await e("smartapp.element.getBySelector",{properties:s,selector:"html"}))[0];return{properties:s.map((e=>a.properties[e]))}}},"Element.getHTML":{reflect:async(e,t)=>{const s=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:s}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:s}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return s.forEach((e=>{e.nodeId=e.id})),{elements:s}}},"Element.getAttributes":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{attributes:s}},params:I},"Element.getStyles":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getComputedStyle",Object.assign({style:a},t)));return{styles:s}},params:I},"Element.getDOMProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getProperty",Object.assign({property:a},t)));return{properties:s}},params:I},"Element.getProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{properties:s}},params:I},"Element.getOffset":{reflect:async(e,t)=>({left:await e("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:await e("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:I},"Element.tap":{reflect:"smartapp.element.touch",params:I}}};module.exports=V;
"use strict";var e=require("os"),t=require("path"),s=require("debug"),a=require("licia/isWindows"),r=require("fs"),n=require("child_process"),o=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/getPort"),p=require("licia/dateFormat"),m=require("ws"),d=require("events"),f=require("licia/uuid"),h=require("licia/stringify");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=g(e),y=g(t),E=g(s),v=g(a),b=g(r),P=g(n),j=g(o),M=g(i),O=g(c),$=g(l),q=g(u),C=g(p),A=g(m),S=g(f),T=g(h);const L=/(^[a-z][a-z0-9-]*)/i,H=/^navigator/i,R=/^swan-nav$/i;var N;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(N||(N={}));const k={[N.SELECTOR]:[{test:H,processor:e=>e.replace(H,"nav")},{test:L,processor:e=>`swan-${e}`}],[N.TAGNAME]:[{test:R,processor:e=>e.replace(R,"swan-navigator")},{test:L,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},x=e=>t=>{const s=(k[e]||[]).filter((e=>e.test.test(t)));for(const e of s)t=e.processor(t);return t},D=x(N.SELECTOR),F=x(N.TAGNAME),I=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});/^win/.test(process.platform);class W extends d.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 B=new Map,G="Connection closed";class z extends d.EventEmitter{constructor(e,t,s){super(),this.puppet=t,this.namespace=s,this.callbacks=new Map,this.transport=e,this.debug=E.default("automator:protocol:"+this.namespace),this.onMessage=e=>{var t;this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:s,method:a,error:r,result:n,params:o}=JSON.parse(e);if(null===(t=null==n?void 0:n.method)||void 0===t?void 0:t.startsWith("on"))return void((e,t,s)=>{const a=B.get(e);a.has(t)&&a.get(t)(s)})(n.method,s,n);if(!s)return this.puppet.emit(a,o);const{callbacks:i}=this;if(s&&i.has(s)){const e=i.get(s);i.delete(s),r?e.reject(Error(r.message||r.detailMessage)):e.resolve(n)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(G))}))},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 a=S.default(),r=T.default({id:a,method:e,params:t});return this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),new Promise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(G))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((s,a)=>{const r=new A.default(e);r.addEventListener("open",(()=>{s(new z(new W(r),t,"devtool"))})),r.addEventListener("error",a)}))}static createRuntimeConnection(e,t,s){return new Promise(((a,r)=>{E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new A.default.Server({port:e});O.default((async()=>{if(t.runtimeConnection)return!0}),s,1e3).catch((()=>{n.close(),r("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const s=new z(new W(e),t,"runtime");t.setRuntimeConnection(s),a(s)})),t.setRuntimeServer(n)}))}}const J=E.default("automator:devtool");async function U(e,t,s){const{port:a,cliPath:r,timeout:n,cwd:o="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,p=!1;if(!1!==l){const t={stdio:"ignore"};o&&(t.cwd=o);let s=$.default(c,[]);s=$.default(s,["--auto"]),s=$.default(s,[e,"--auto-port",M.default(a)]),i&&(s=$.default(s,["--auto-account",i]));try{J("%s %o %o",r,s,t);const e=P.default.spawn(r,s,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{p=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{p=!0}),15e3);const m=await O.default((async()=>{try{if(u||p)return!0;const e=await async function(e,t){let s;try{s=await z.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return s}({wsEndpoint:`ws://127.0.0.1:${a}`},s);return e}catch(e){}}),n,1e3);if(u)throw Error(`Failed to launch ${s.devtools.name}, please make sure cliPath is correctly specified`);if(p)throw Error(`Failed to launch ${s.devtools.name} , please make sure http port is open`);return await j.default(5e3),J(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`),m}const V=[];["","-rc"].forEach((e=>{v.default?(V.push(y.default.join(w.default.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),V.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):V.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)}));const _={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:V,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const s=function(e,t){const s=t.devtools.paths.slice(0);e&&s.unshift(e);for(const e of s)if(b.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let a=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=await async function(e,t){const s=await q.default(e||t);if(e&&s!==e)throw Error(`Port ${e} is in use, please specify another port`);return s}(a)}catch(t){e.launch=!1}else{a===await q.default(a)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:a,cliPath:s})},async create(e,t,s){const a=await U(e,t,s);return s.compiled?E.default("automator:devtool")("Waiting for runtime automator"):(E.default("automator:devtool")("initRuntimeAutomator"),a.send("smartapp.swan",{api:"$$initRuntimeAutomator",params:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async e=>({qrCode:(await e("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(await e("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(await e("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(s=t.selector,s.split(" ").map((e=>D(e))).join(" "))}))).map((e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:F(t.tagName)}}))};var s}},"Page.getWindowProperties":{reflect:async(e,t)=>{const s=t.names.map((e=>e.replace("document.documentElement.",""))),a=(await e("smartapp.element.getBySelector",{properties:s,selector:"html"}))[0];return{properties:s.map((e=>a.properties[e]))}}},"Element.getHTML":{reflect:async(e,t)=>{const s=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:s}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:s}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return s.forEach((e=>{e.nodeId=e.id})),{elements:s}}},"Element.getAttributes":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{attributes:s}},params:I},"Element.getStyles":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getComputedStyle",Object.assign({style:a},t)));return{styles:s}},params:I},"Element.getDOMProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getProperty",Object.assign({property:a},t)));return{properties:s}},params:I},"Element.getProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{properties:s}},params:I},"Element.getOffset":{reflect:async(e,t)=>({left:await e("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:await e("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:I},"Element.tap":{reflect:"smartapp.element.touch",params:I}}};module.exports=_;
var CALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){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)}))},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&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(params){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/png;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}),{wholeContent:!!params.fullPage})}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))},callMethodWithCallback:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="callMethodWithCallback:fail, Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="callMethodWithCallback:fail, page."+params.method+" not exists",_a),callback=params.args[params.args.length-1];callMethod(getPageVm(params.pageId),params.method,params.args).catch((function(type){callback({errMsg:err[type]})}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},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 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&&!fn)return data.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];return params.args.push((function(result){null!==result&&(data.result=result),send(data)})),void fn(params)}fn(params).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)}}wx.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url: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")}))},setTimeout((function(){wx.$$initRuntimeAutomator()}),500);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
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.
***************************************************************************** */
var CALL_METHOD_ERROR,__assign=function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t},__assign.apply(this,arguments)},hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],onApisEventMap=new Map,ON_APIS=["onCompassChange","onThemeChange","onUserCaptureScreen","onWindowResize","onMemoryWarning","onAccelerometerChange","onKeyboardHeightChange","onNetworkStatusChange","onPushMessage","onLocationChange","onGetWifiList","onWifiConnected","onWifiConnectedWithPartialInfo"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){if(ON_APIS.includes(method)){onApisEventMap.has(method)||onApisEventMap.set(method,new Map);var uuid_1=args[0],callback=function(res){send({id:uuid_1,result:__assign({method:method},res)})};return onApisEventMap.get(method).set(uuid_1,callback),uni[method](callback),resolve({result:null})}if(method.startsWith("off")&&ON_APIS.includes(method.replace("off","on"))){var onMethod=method.replace("off","on");if(onApisEventMap.has(onMethod)){var uuid=args[0];if(void 0!==uuid){callback=onApisEventMap.get(onMethod).get(uuid);uni[method](callback),onApisEventMap.get(onMethod).delete(uuid)}else{onApisEventMap.get(onMethod).forEach((function(callback){uni[method](callback)})),onApisEventMap.delete(onMethod)}}return resolve({result:null})}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)}))},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&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(params){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/png;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}),{wholeContent:!!params.fullPage})}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))},callMethodWithCallback:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="callMethodWithCallback:fail, Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="callMethodWithCallback:fail, page."+params.method+" not exists",_a),callback=params.args[params.args.length-1];callMethod(getPageVm(params.pageId),params.method,params.args).catch((function(type){callback({errMsg:err[type]})}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},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 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&&!fn)return data.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];return params.args.push((function(result){null!==result&&(data.result=result),send(data)})),void fn(params)}fn(params).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)}}wx.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url: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")}))},setTimeout((function(){wx.$$initRuntimeAutomator()}),500);export{send};
"use strict";var e=require("debug"),t=require("licia/isWindows"),a=require("licia/getPort"),o=require("qrcode-reader"),r=require("fs"),n=require("child_process"),s=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/dateFormat"),d=require("ws"),p=require("events"),f=require("licia/uuid"),m=require("licia/stringify");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=h(e),y=h(t),g=h(a),v=h(o),b=h(r),E=h(n),q=h(s),M=h(i),j=h(c),$=h(l),P=h(u),C=h(d),x=h(f),H=h(m);/^win/.test(process.platform);class k extends p.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 F="Connection closed";class R extends p.EventEmitter{constructor(e,t,a){super(),this.puppet=t,this.namespace=a,this.callbacks=new Map,this.transport=e,this.debug=w.default("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:a,error:o,result:r,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(a,n);const{callbacks:s}=this;if(t&&s.has(t)){const e=s.get(t);s.delete(t),o?e.reject(Error(o.message||o.detailMessage)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(F))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},a=!0){if(a&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const o=x.default(),r=H.default({id:o,method:e,params:t});return this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),new Promise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(F))}this.callbacks.set(o,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((a,o)=>{const r=new C.default(e);r.addEventListener("open",(()=>{a(new R(new k(r),t,"devtool"))})),r.addEventListener("error",o)}))}static createRuntimeConnection(e,t,a){return new Promise(((o,r)=>{w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new C.default.Server({port:e});j.default((async()=>{if(t.runtimeConnection)return!0}),a,1e3).catch((()=>{n.close(),r("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const a=new R(new k(e),t,"runtime");t.setRuntimeConnection(a),o(a)})),t.setRuntimeServer(n)}))}}const D=w.default("automator:devtool");async function S(e,t,a){const{port:o,cliPath:r,timeout:n,cwd:s="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,d=!1;if(!1!==l){const t={stdio:"ignore",detached:!0};s&&(t.cwd=s);let a=$.default(c,[]);a=$.default(a,["auto","--project"]),a=$.default(a,[e,"--auto-port",M.default(o)]),i&&(a=$.default(a,["--auto-account",i]));try{D("%s %o %o",r,a,t);const e=E.default.spawn(r,a,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{d=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{d=!0}),15e3);const p=await j.default((async()=>{try{if(u||d)return!0;const e=await async function(e,t){let a;try{a=await R.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return a}({wsEndpoint:`ws://127.0.0.1:${o}`},a);return e}catch(e){}}),n,1e3);if(u)throw Error(`Failed to launch ${a.devtools.name}, please make sure cliPath is correctly specified`);if(d)throw Error(`Failed to launch ${a.devtools.name} , please make sure http port is open`);return await q.default(5e3),D(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}const T={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[y.default?"C:/Program Files (x86)/Tencent/微信web开发者工具/cli.bat":"/Applications/wechatwebdevtools.app/Contents/MacOS/cli"],required:["project.config.json","app.json","app.js"],defaultPort:9420,validate:async function(e,t){const a=function(e,t){const a=t.devtools.paths.slice(0);e&&a.unshift(e);for(const e of a)if(b.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let o=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{o=await async function(e,t){const a=await g.default(e||t);if(e&&a!==e)throw Error(`Port ${e} is in use, please specify another port`);return a}(o)}catch(t){e.launch=!1}else{o===await g.default(o)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:o,cliPath:a})},async create(e,t,a){const o=await S(e,t,a);return a.compiled?w.default("automator:devtool")("Waiting for runtime automator"):(w.default("automator:devtool")("initRuntimeAutomator"),o.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),o}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:a}=await e("Tool.enableRemoteDebug",t,!1);return a&&(a=await function(e){const t=new Buffer(e,"base64");return new Promise((async(e,a)=>{const o=await require("jimp").read(t),r=new v.default;r.callback=function(t,o){if(t)return a(t);e(o.result)},r.decode(o.bitmap)}))}(a)),{qrCode:a}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(a=t.functionDeclaration,"}"===a[a.length-1]?a.replace("{","{\nvar uni = wx;\n"):a.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var a}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=T;
"use strict";var e=require("debug"),t=require("licia/isWindows"),o=require("licia/getPort"),a=require("qrcode-reader"),n=require("fs"),r=require("child_process"),s=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/dateFormat"),d=require("ws"),p=require("events"),f=require("licia/uuid"),m=require("licia/stringify");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=h(e),y=h(t),v=h(o),g=h(a),b=h(n),E=h(r),q=h(s),M=h(i),j=h(c),$=h(l),P=h(u),C=h(d),x=h(f),H=h(m);/^win/.test(process.platform);class k extends p.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 F=new Map,R="Connection closed";class D extends p.EventEmitter{constructor(e,t,o){super(),this.puppet=t,this.namespace=o,this.callbacks=new Map,this.transport=e,this.debug=w.default("automator:protocol:"+this.namespace),this.onMessage=e=>{var t;this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:o,method:a,error:n,result:r,params:s}=JSON.parse(e);if(null===(t=null==r?void 0:r.method)||void 0===t?void 0:t.startsWith("on"))return void((e,t,o)=>{const a=F.get(e);a.has(t)&&a.get(t)(o)})(r.method,o,r);if(!o)return this.puppet.emit(a,s);const{callbacks:i}=this;if(o&&i.has(o)){const e=i.get(o);i.delete(o),n?e.reject(Error(n.message||n.detailMessage)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(R))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},o=!0){if(o&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const a=x.default(),n=H.default({id:a,method:e,params:t});return this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${n}`),new Promise(((e,t)=>{try{this.transport.send(n)}catch(e){t(Error(R))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((o,a)=>{const n=new C.default(e);n.addEventListener("open",(()=>{o(new D(new k(n),t,"devtool"))})),n.addEventListener("error",a)}))}static createRuntimeConnection(e,t,o){return new Promise(((a,n)=>{w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const r=new C.default.Server({port:e});j.default((async()=>{if(t.runtimeConnection)return!0}),o,1e3).catch((()=>{r.close(),n("Failed to connect to runtime, please make sure the project is running")})),r.on("connection",(function(e){w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const o=new D(new k(e),t,"runtime");t.setRuntimeConnection(o),a(o)})),t.setRuntimeServer(r)}))}}const S=w.default("automator:devtool");async function T(e,t,o){const{port:a,cliPath:n,timeout:r,cwd:s="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,d=!1;if(!1!==l){const t={stdio:"ignore",detached:!0};s&&(t.cwd=s);let o=$.default(c,[]);o=$.default(o,["auto","--project"]),o=$.default(o,[e,"--auto-port",M.default(a)]),i&&(o=$.default(o,["--auto-account",i]));try{S("%s %o %o",n,o,t);const e=E.default.spawn(n,o,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{d=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{d=!0}),15e3);const p=await j.default((async()=>{try{if(u||d)return!0;const e=await async function(e,t){let o;try{o=await D.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return o}({wsEndpoint:`ws://127.0.0.1:${a}`},o);return e}catch(e){}}),r,1e3);if(u)throw Error(`Failed to launch ${o.devtools.name}, please make sure cliPath is correctly specified`);if(d)throw Error(`Failed to launch ${o.devtools.name} , please make sure http port is open`);return await q.default(5e3),S(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}const A={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[y.default?"C:/Program Files (x86)/Tencent/微信web开发者工具/cli.bat":"/Applications/wechatwebdevtools.app/Contents/MacOS/cli"],required:["project.config.json","app.json","app.js"],defaultPort:9420,validate:async function(e,t){const o=function(e,t){const o=t.devtools.paths.slice(0);e&&o.unshift(e);for(const e of o)if(b.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let a=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=await async function(e,t){const o=await v.default(e||t);if(e&&o!==e)throw Error(`Port ${e} is in use, please specify another port`);return o}(a)}catch(t){e.launch=!1}else{a===await v.default(a)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:a,cliPath:o})},async create(e,t,o){const a=await T(e,t,o);return o.compiled?w.default("automator:devtool")("Waiting for runtime automator"):(w.default("automator:devtool")("initRuntimeAutomator"),a.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:o}=await e("Tool.enableRemoteDebug",t,!1);return o&&(o=await function(e){const t=new Buffer(e,"base64");return new Promise((async(e,o)=>{const a=await require("jimp").read(t),n=new g.default;n.callback=function(t,a){if(t)return o(t);e(a.result)},n.decode(a.bitmap)}))}(o)),{qrCode:o}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(o=t.functionDeclaration,"}"===o[o.length-1]?o.replace("{","{\nvar uni = wx;\n"):o.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var o}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=A;
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册