Files
fitness_walk_nwnu/node_modules/@dcloudio/uni-mp-baidu/lib/uni.automator.js
T
2026-09-08 20:28:54 +08:00

2 lines
11 KiB
JavaScript

"use strict";var e=require("os"),t=require("path"),s=require("debug"),a=require("licia/isWindows"),r=require("fs"),o=require("child_process"),n=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/getPort"),d=require("licia/dateFormat"),p=require("ws"),m=require("events"),h=require("licia/uuid"),f=require("licia/stringify");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=g(e),y=g(t),v=g(s),E=g(a),b=g(r),P=g(o),A=g(n),C=g(i),M=g(c),O=g(l),j=g(u),T=g(d),$=g(p),S=g(h),q=g(f);const H=/(^[a-z][a-z0-9-]*)/i,I=/^navigator/i,L=/^swan-nav$/i;var N;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(N||(N={}));const R={[N.SELECTOR]:[{test:I,processor:e=>e.replace(I,"nav")},{test:H,processor:e=>`swan-${e}`}],[N.TAGNAME]:[{test:L,processor:e=>e.replace(L,"swan-navigator")},{test:H,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},x=e=>t=>{const s=(R[e]||[]).filter((e=>e.test.test(t)));for(const e of s)t=e.processor(t);return t},k=x(N.SELECTOR),_=x(N.TAGNAME),D=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});/^win/.test(process.platform);class U extends m.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,t){this.ws.send(e,t)}close(){this.ws.close()}}const F=new Map,B=new Map,W="Connection closed";class X extends m.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.exConnectionClosed=!1,this.debug=v.default("automator:protocol:"+this.namespace),this.onMessage=e=>{var t,s,a;if(this.isAlive=!0,"true"===process.env.UNI_APP_X&&'"pong"'===e)return;const{id:r,method:o,error:n,result:i,params:c}=JSON.parse(e);if((null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.length)>10240){let e=JSON.stringify({id:r,method:o,error:n,result:Object.assign(Object.assign({},i),{data:i.data.substring(0,30)+"...<more>"}),params:c});this.debug(`${T.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`)}else this.debug(`${T.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);if(null===(s=null==i?void 0:i.method)||void 0===s?void 0:s.startsWith("on"))return void((e,t)=>{const s=F.get(e.method);(null==s?void 0:s.has(t))&&s.get(t)(e.data)})(i,r);if(null===(a=null==i?void 0:i.method)||void 0===a?void 0:a.startsWith("Socket.")){return void((e,t,s)=>{const a=B.get(t);(null==a?void 0:a.has(e))&&a.get(e)(s)})(i.method.replace("Socket.",""),i.id,i.data)}if(!r)return this.puppet.emit(o,c);const{callbacks:l}=this;if(r&&l.has(r)){const e=l.get(r);l.delete(r),n?e.reject(Error(n.message||n.detailMessage||n.errMsg)):e.resolve(i)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(W))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}isBroken(){return!!this.exConnectionClosed}send(e,t={},s=!0){if(s&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);if(this.exConnectionClosed)throw this.exConnectionClosed;const a=S.default(),r=q.default({id:a,method:e,params:t});return"ping"!==e&&this.debug(`${T.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),new Promise(((e,t)=>{try{this.transport.send(r,(e=>{e&&t(Error(W))}))}catch(e){t(Error(W))}this.callbacks.set(a,{resolve:e,reject:t})})).catch((e=>{throw e.message===W&&(this.exConnectionClosed=e),e}))}dispose(){this.callbacks.clear(),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"),s=w.default.platform();let a="",r="";"darwin"===s?(a='ps | grep "u0_a"',r="logcat -b crash | grep -C 10 io.dcloud.uniappx"):"win32"===s&&(a='dumpsys activity | findstr "Run"',r="logcat | findstr UncaughtExceptionHandler"),e.set(this.id,setInterval((async()=>{if(!this.isAlive){const o=t.createClient(),n=await o.listDevices();if(!n.length)throw Error("Device not found");const i=n[0].id,c=await o.getProperties(i);return("1"===c["ro.kernel.qemu"]||"goldfish"===c["ro.hardware"])&&"win32"===s&&(r="logcat | grep UncaughtExceptionHandler"),o.shell(i,a).then((function(e){let t,s="";e.on("data",(function(e){s+=e.toString(),t&&clearTimeout(t),t=setTimeout((()=>{s.includes("io.dcloud.uniapp")||(o.shell(i,"screencap -p /sdcard/uni-automator-screenshot-when-uniapp-un-active.png"),console.log("ADBCommandAppIsLaunch",a),console.log("ADBCommandAppIsLaunch res",s),console.log("Stop the test process."))}),50)}))})),o.shell(i,r).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").catch((e=>{})),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").catch((e=>{})),this.isAlive=!1}),5e3))}static createDevtoolConnection(e,t){return new Promise(((s,a)=>{const r=new $.default(e);r.addEventListener("open",(()=>{s(new X(new U(r),t,"devtool"))})),r.addEventListener("error",a)}))}static createRuntimeConnection(e,t,s){return new Promise(((a,r)=>{v.default("automator:runtime")(`${T.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new $.default.Server({port:e});M.default((async()=>{if(t.runtimeConnection)return!0}),s,1e3).catch((()=>{o.close(),r("Failed to connect to runtime, please make sure the project is running")})),o.on("connection",(function(e){v.default("automator:runtime")(`${T.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const s=new X(new U(e),t,"runtime");t.setRuntimeConnection(s),process.env.UNI_AUTOMATOR_NEED_RESTART_BETWEEN_TEST?global.socketConnected=!0:s.startHeartbeat(),a(s)})),t.setRuntimeServer(o)}))}}const G=v.default("automator:devtool");async function z(e,t,s){const{port:a,cliPath:r,timeout:o,cwd:n="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,d=!1;if(!1!==l){const t={stdio:"ignore"};n&&(t.cwd=n);let s=O.default(c,[]);s=O.default(s,["--auto"]),s=O.default(s,[e,"--auto-port",C.default(a)]),i&&(s=O.default(s,["--auto-account",i]));try{G("%s %o %o",r,s,t);const e=P.default.spawn(r,s,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 M.default((async()=>{try{if(u||d)return!0;const e=await async function(e,t){let s;try{s=await X.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){}}),o,1e3);if(u)throw Error(`Failed to launch ${s.devtools.name}, please make sure cliPath is correctly specified`);if(d)throw Error(`Failed to launch ${s.devtools.name} , please make sure http port is open`);return await A.default(5e3),G(`${T.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}const J=[];["","-rc"].forEach((e=>{E.default?(J.push(y.default.join(w.default.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),J.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):J.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)}));const V={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:J,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 j.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 j.default(a)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:a,cliPath:s})},async create(e,t,s){const a=await z(e,t,s);return s.compiled?v.default("automator:devtool")("Waiting for runtime automator"):(v.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.start":{reflect:async()=>Promise.resolve()},"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=>k(e))).join(" "))}))).map((e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:_(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:D},"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:D},"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:D},"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:D},"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:D},"Element.tap":{reflect:"smartapp.element.touch",params:D}}};module.exports=V;