EASYAIuniappNewUI/node_modules/@dcloudio/uni-mp-weixin/lib/uni.automator.js
2025-02-08 18:50:38 +08:00

2 lines
7.8 KiB
JavaScript

"use strict";var e=require("debug"),t=require("licia/isWindows"),o=require("licia/getPort"),r=require("qrcode-reader"),s=require("fs"),n=require("child_process"),a=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"),h=require("licia/uuid"),f=require("licia/stringify"),m=require("os");function w(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var v=w(e),g=w(t),y=w(o),b=w(r),E=w(s),q=w(n),M=w(a),P=w(i),A=w(c),H=w(l),C=w(u),$=w(d),j=w(h),x=w(f),k=w(m);/^win/.test(process.platform);class S 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 T=new Map,D=new Map,I="Connection closed";class R extends p.EventEmitter{constructor(e,t,o){super(),this.puppet=t,this.namespace=o,this.callbacks=new Map,this.transport=e,this.isAlive=!0,this.id=Date.now(),this.debug=v.default("automator:protocol:"+this.namespace),this.onMessage=e=>{var t,o;if(this.isAlive=!0,"true"===process.env.UNI_APP_X&&'"pong"'===e)return;this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:r,method:s,error:n,result:a,params:i}=JSON.parse(e);if(null===(t=null==a?void 0:a.method)||void 0===t?void 0:t.startsWith("on"))return void((e,t)=>{const o=T.get(e.method);(null==o?void 0:o.has(t))&&o.get(t)(e.data)})(a,r);if(null===(o=null==a?void 0:a.method)||void 0===o?void 0:o.startsWith("Socket.")){return void((e,t,o)=>{const r=D.get(t);(null==r?void 0:r.has(e))&&r.get(e)(o)})(a.method.replace("Socket.",""),a.id,a.data)}if(!r)return this.puppet.emit(s,i);const{callbacks:c}=this;if(r&&c.has(r)){const e=c.get(r);c.delete(r),n?e.reject(Error(n.message||n.detailMessage||n.errMsg)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(I))}))},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 r=j.default(),s=x.default({id:r,method:e,params:t});return"ping"!==e&&this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${s}`),new Promise(((e,t)=>{try{this.transport.send(s)}catch(e){t(Error(I))}this.callbacks.set(r,{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=function(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}("adbkit"),o=k.default.platform();let r="",s="";"darwin"===o?(r='dumpsys activity | grep "Run"',s="logcat -b crash | grep -C 10 io.dcloud.uniappx"):"win32"===o&&(r='dumpsys activity | findstr "Run"',s="logcat | findstr UncaughtExceptionHandler"),e.set(this.id,setInterval((async()=>{if(!this.isAlive){const n=t.createClient(),a=await n.listDevices();if(!a.length)throw Error("Device not found");const i=a[0].id,c=await n.getProperties(i);return("1"===c["ro.kernel.qemu"]||"goldfish"===c["ro.hardware"])&&"win32"===o&&(s="logcat | grep UncaughtExceptionHandler"),n.shell(i,r).then((function(e){let t,o="";e.on("data",(function(e){o+=e.toString(),t&&clearTimeout(t),t=setTimeout((()=>{o.includes("io.dcloud.uniapp")||(console.log("ADBCommandAppIsLaunch",r),console.log("ADBCommandAppIsLaunch res",o),console.log("Stop the test process."))}),50)}))})),n.shell(i,s).then((e=>{let t,o="";e.on("data",(e=>{o+=e.toString(),t&&clearTimeout(t),t=setTimeout((()=>{console.log(`crash log: ${o}`)}),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(((o,r)=>{const s=new $.default(e);s.addEventListener("open",(()=>{o(new R(new S(s),t,"devtool"))})),s.addEventListener("error",r)}))}static createRuntimeConnection(e,t,o){return new Promise(((r,s)=>{v.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new $.default.Server({port:e});A.default((async()=>{if(t.runtimeConnection)return!0}),o,1e3).catch((()=>{n.close(),s("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){v.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const o=new R(new S(e),t,"runtime");t.setRuntimeConnection(o),o.startHeartbeat(),r(o)})),t.setRuntimeServer(n)}))}}const F=v.default("automator:devtool");async function L(e,t,o){const{port:r,cliPath:s,timeout:n,cwd:a="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,d=!1;if(!1!==l){const t={stdio:"ignore",detached:!0};a&&(t.cwd=a);let o=H.default(c,[]);o=H.default(o,["auto","--project"]),o=H.default(o,[e,"--auto-port",P.default(r)]),i&&(o=H.default(o,["--auto-account",i]));try{F("%s %o %o",s,o,t);const e=q.default.spawn(s,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 A.default((async()=>{try{if(u||d)return!0;const e=await async function(e,t){let o;try{o=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 o}({wsEndpoint:`ws://127.0.0.1:${r}`},o);return e}catch(e){}}),n,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 M.default(5e3),F(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}const _={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[g.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(E.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let r=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{r=await async function(e,t){const o=await y.default(e||t);if(e&&o!==e)throw Error(`Port ${e} is in use, please specify another port`);return o}(r)}catch(t){e.launch=!1}else{r===await y.default(r)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:r,cliPath:o})},async create(e,t,o){const r=await L(e,t,o);return o.compiled?v.default("automator:devtool")("Waiting for runtime automator"):(v.default("automator:devtool")("initRuntimeAutomator"),r.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),r}},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 r=await require("jimp").read(t),s=new b.default;s.callback=function(t,r){if(t)return o(t);e(r.result)},s.decode(r.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=_;