From 368bf48d339d97a7d92bc5f5d00796be846179d3 Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Sun, 26 Apr 2020 17:26:18 +0800 Subject: [PATCH] feat(app-plus): automator --- packages/uni-app-plus/lib/uni.automator.js | 2 +- packages/uni-automator/dist/index.js | 2 +- packages/uni-automator/package.json | 3 ++- packages/uni-mp-baidu/lib/uni.automator.js | 2 +- packages/uni-mp-weixin/lib/uni.automator.js | 2 +- packages/uni-quickapp-light/dist/index.js | 2 +- .../packages/webpack-app-plus-plugin/index.js | 2 +- packages/vue-cli-plugin-uni/commands/build.js | 2 +- 8 files changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/uni-app-plus/lib/uni.automator.js b/packages/uni-app-plus/lib/uni.automator.js index 84a2343f4..8613397c9 100644 --- a/packages/uni-app-plus/lib/uni.automator.js +++ b/packages/uni-app-plus/lib/uni.automator.js @@ -1 +1 @@ -"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("debug")),o=e(require("postcss-selector-parser"));function n(e){e.walk(e=>{if("tag"===e.type){const t=e.value;e.value="page"===t?"body":"uni-"+t}})}const c=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const s=t("automator:devtool");const r={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>{}},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(e,t)=>{}}};!function(e){c.forEach(t=>{e[t]=function(e){return{reflect:async(t,o)=>t(e,o,!1),params:e=>(e.selector&&(e.selector=o(n).processSync(e.selector)),e)}}(t)})}(r);const a={devtools:{name:"App",paths:[],validate:async function(e){return e.options=e.options||{},e},create:async function(e,t,o){s("createDevtools")}},adapter:r};module.exports=a; +"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("fs")),i=t(require("debug")),s=t(require("postcss-selector-parser")),a=require("path"),r=require("util"),n=t(require("licia/dateFormat"));function c(t){t.walk(t=>{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}})}const o=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const l=require("adbkit"),h=i("automator:adb"),d=r.promisify(e.readdir),u=r.promisify(e.stat);class p{constructor(t){this.device={id:""},this.device.id=t.id,this.apk=t.executablePath,this.appid=t.appid||"HBuilder",this.package=t.package||"io.dcloud.HBuilder",this.client=l.createClient()}async init(){if(!this.device.id){const t=await this.client.listDevices();if(!t.length)throw Error("Device id is not provided");this.device.id=t[0].id}this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),h(`${n("yyyy-mm-dd HH:MM:ss:l")} init ${this.device.id} ${this.sdcard}`)}version(){return this.shell(this.COMMAND_VERSION).then(t=>{const e=t.match(/versionName=(.*)/);return e&&e.length>1?e[1]:""})}install(){return h(`${n("yyyy-mm-dd HH:MM:ss:l")} install ${this.apk}`),this.client.install(this.device.id,this.apk).then(()=>this.init())}push(t){return async function t(e){const i=await d(e);return(await Promise.all(i.map(async i=>{const s=a.resolve(e,i);return(await u(s)).isDirectory()?t(s):s}))).reduce((t,e)=>t.concat(e),[])}(t).then(e=>{const i=e.map(e=>{const i=a.join(this.DIR_WWW,a.relative(t,e));return h(`${n("yyyy-mm-dd HH:MM:ss:l")} push ${e} ${i}`),this.client.push(this.device.id,e,i)});return Promise.all(i)}).then(t=>!0)}start(){return this.exit().then(()=>this.shell(this.COMMAND_START))}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(){return this.client.screencap(this.device.id).then(t=>new Promise(e=>{const i=[];t.on("data",(function(t){i.push(t)})),t.on("end",(function(){e(Buffer.concat(i).toString("base64"))}))}))}shouldPush(){return this.client.stat(this.device.id,this.FILE_APP_SERVICE).then(()=>!1).catch(()=>!0)}shell(t){return h(`${n("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.client.shell(this.device.id,t).then(l.util.readAll).then(t=>{const e=t.toString();return h(`${n("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e})}get DIR_WWW(){return`${this.sdcard}/Android/data/${this.package}/apps/${this.appid}/www/`}get FILE_APP_SERVICE(){return`${this.sdcard}/Android/data/${this.package}/apps/${this.appid}/www/app-service.js`}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}/io.dcloud.PandoraEntry --es ${this.appid} --ez needUpdateApp false --ez reload true`}}const m=i("automator:devtool");let y,f=!1;const g={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>y.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(t,e)=>{const i=await y.captureScreenshot(e);return m("App.captureScreenshot "+i.length),{data:i}}}};!function(t){o.forEach(e=>{t[e]=function(t){return{reflect:async(e,i)=>e(t,i,!1),params:t=>(t.selector&&(t.selector=s(c).processSync(t.selector)),t)}}(e)})}(g);const v={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,i){if(t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),y=function(t,e){return new p(e)}(t.platform,t),await y.init(),!await y.version()){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!e.existsSync(t.executablePath))throw Error(t.executablePath+" not exists");f=!0}return t},create:async function(t,e,i){f&&await y.install(),(i.compiled||await y.shouldPush())&&await y.push(t),await y.start()}},adapter:g};module.exports=v; diff --git a/packages/uni-automator/dist/index.js b/packages/uni-automator/dist/index.js index eac77e9d2..eb1ab784b 100644 --- a/packages/uni-automator/dist/index.js +++ b/packages/uni-automator/dist/index.js @@ -13,4 +13,4 @@ MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -function I(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 D;function T(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 A(t,e,n){return T(D.RUNTIME,n)}function x(t,e,n){return T(D.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(D||(D={}));class R{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===D.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 q extends R{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 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)}}I([A],q.prototype,"getData",null),I([A],q.prototype,"setData",null),I([A],q.prototype,"callMethod",null),I([x],q.prototype,"getElement",null),I([x],q.prototype,"getElements",null),I([x],q.prototype,"getOffset",null),I([x],q.prototype,"getHTML",null),I([x],q.prototype,"getAttributes",null),I([x],q.prototype,"getStyles",null),I([x],q.prototype,"getDOMProperties",null),I([x],q.prototype,"getProperties",null),I([x],q.prototype,"tap",null),I([x],q.prototype,"touchstart",null),I([x],q.prototype,"touchmove",null),I([x],q.prototype,"touchend",null),I([x],q.prototype,"triggerEvent",null),I([x],q.prototype,"callFunction",null),I([x],q.prototype,"callContextMethod",null);class j{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.elementMap=n,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new q(t,e)}async $(t){try{const e=await this.api.getElement({selector:t});return j.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=>j.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(){return this.api.getOffset()}async text(){return this.domProperty("innerText")}async attribute(t){if(!m(t))throw Error("name must be a string");return(await this.api.getAttributes({names:[t]})).attributes[0]}async value(){return this.property("value")}async property(t){if(!m(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._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(!m(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 await this.touchstart(),await v(350),this.touchend()}async trigger(t,e){const n={type:t};return w(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 C(async t=>(await this.api.getDOMProperties({names:t})).properties,t)}_property(t){return C(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=S;else switch(e.tagName){case"input":s=$;break;case"textarea":s=F;break;case"scroll-view":s=O;break;case"swiper":s=L;break;case"movable-view":s=U;break;case"switch":s=H;break;case"slider":s=N;break;case"video":s=B;break;default:s=j}return i=new s(t,e,n),n.set(e.elementId,i),i}}class S extends j{async setData(t){return this.api.setData({data:t})}async data(t){const e={};return t&&(e.path=t),(await this.api.getData(e)).data}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}}class $ extends j{async input(t){return this.callFunction("input.input",t)}}class F extends j{async input(t){return this.callFunction("textarea.input",t)}}class O extends j{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 L extends j{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class U extends j{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 H extends j{async tap(){return this.callFunction("switch.tap")}}class N extends j{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class B extends j{async callContextMethod(t,...e){return this.api.callContextMethod({method:t,args:e})}}class _ extends R{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 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)}}I([A],_.prototype,"getData",null),I([A],_.prototype,"setData",null),I([A],_.prototype,"callMethod",null),I([x],_.prototype,"getElement",null),I([x],_.prototype,"getElements",null),I([x],_.prototype,"getWindowProperties",null);class W{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 _(t,e)}async waitFor(t){return y(t)?await v(t):h(t)?l(t):m(t)?l(async()=>(await this.$$(t)).length>0):void 0}async $(t){try{const e=await this.api.getElement({selector:t});return j.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=>j.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap))}async data(t){const e={};return t&&(e.path=t),(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 scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(t){const e=m(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=new W(t,e),n.set(e.id,s),s)}}class V extends R{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 callFunction(t){return this.invoke("App.callFunction",t)}async captureScreenshot(t){return this.invoke("App.captureScreenshot",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)}}I([A],V.prototype,"getPageStack",null),I([A],V.prototype,"callUniMethod",null),I([A],V.prototype,"getCurrentPage",null),I([x],V.prototype,"mockUniMethod",null),I([x],V.prototype,"callFunction",null),I([x],V.prototype,"captureScreenshot",null),I([x],V.prototype,"exit",null),I([x],V.prototype,"addBinding",null),I([x],V.prototype,"enableLog",null);class z extends R{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 G(t){return new Promise(e=>setTimeout(e,t))}I([x],z.prototype,"getInfo",null),I([x],z.prototype,"enableRemoteDebug",null),I([x],z.prototype,"close",null),I([x],z.prototype,"getTestAccounts",null);class J extends r.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new V(t),this.toolApi=new z(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=>W.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 W.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 h(e)||m(s=e)&&(s=d(s),g(s,"function")||g(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 G(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=>{b.generate(n,{small:!0},e=>{process.stdout.write(e),t()})}));const s=new Promise(t=>{this.toolApi.onRemoteDebugConnected(async()=>{await G(1e3),t()})}),i=new Promise(t=>{this.puppet.setRemoteRuntimeConnectionCallback(()=>{t()})});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{data:e}=await this.appApi.captureScreenshot({fullPage:null==t?void 0:t.fullPage});if(!(null==t?void 0:t.path))return e;await u.writeFile(t.path,e,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(t,e){return await this.callUniMethod(t,{url:e}),await G(3e3),this.currentPage()}}class X{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"))}}class Y extends r.EventEmitter{constructor(t,e){if(super(),this.target=e||("h5"===t?require("@dcloudio/uni-h5/lib/h5/uni.automator.js"):require(`@dcloudio/uni-${t}/lib/uni.automator.js`)),!this.target)throw Error("puppet is not provided");this.platform=t,this.adapter=new X(this.target.adapter||{})}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.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(t,e){return this.runtimeConnection.send(t,e)}validateProject(t){const s=this.target.devtools.required;return!s||!s.find(s=>!e.existsSync(n.join(t,s)))}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){const n=this.target.shouldCompile;return n?n(t,e):!1!==t.compile}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 K=s("automator:compiler"),Q=/The\s+(.*)\s+directory is ready/;class Z{constructor(t){this.puppet=t}compile(t){const e=this.puppet.mode,s=this.puppet.platform;let i=t.silent;const o=t.port,r=t.host,a=process.env.UNI_NPM_PATH||"npm",c=`${e}:${s}`,p=t.projectPath,l=["run",c,"--","--auto-port",P(o)];r&&(l.push("--auto-host"),l.push(r));const u={cwd:t.cliPath||t.projectPath,env:process.env};return new Promise((t,o)=>{const r=function(o){const r=o.toString().trim();if(!i&&console.log(r),r.includes("App running at:"))t({path:""});else if(r.includes("DONE Build complete")){let o=`unpackage/dist/${e}/${s}`;const a=r.match(Q);a&&a.length>1&&(o=a[1]),i=!0,c.kill("SIGTERM"),t({path:n.join(p,o)})}};K(`${a} ${l.join(" ")}`);const c=M.spawn(a,l,u);c.on("error",(function(t){o(t)})),c.stdout.on("data",r),c.stderr.on("data",r)})}}class tt{async launch(t){let e=t[t.platform]||{};this.puppet=new Y(t.platform,e.puppet);const{port:n,cliPath:i,timeout:o,projectPath:r}=await this.validate(t);e=await this.puppet.validateDevtools(e);let a=r;if(this.puppet.shouldCompile(t,e)){this.compiler=new Z(this.puppet);const e=await this.compiler.compile({host:t.host,port:n,cliPath:i,projectPath:r,silent:!!t.silent});e.path&&(a=e.path)}const c=[];return c.push(this.createRuntimeConnection(n,o)),c.push(this.puppet.createDevtools(a,e,o)),new Promise((t,n)=>{Promise.all(c).then(([n,i])=>{n&&this.puppet.setRuntimeConnection(n),i&&this.puppet.setDevtoolConnection(i),s("automator:program")("ready");const o=e.teardown||"disconnect";t(new J(this.puppet,{teardown:o}))}).catch(t=>n(t))})}resolveCliPath(t){if(!t)return t;try{const e=require(n.join(t,"package.json"));if(e.devDependencies&&e.devDependencies["@dcloudio/vue-cli-plugin-uni"])return t}catch(t){}throw Error(`Cli ${t} doesn't exist`)}resolveProjectPath(t,s){if(t||(t=process.cwd()),i(t)&&(t=n.resolve(t)),e.existsSync(t)||function(t){throw Error(t)}(`Project path ${t} doesn't exist`),!1===s.compile&&!this.puppet.validateProject(t)){const e=n.join(t,"dist/"+this.puppet.mode+"/"+this.puppet.platform);if(this.puppet.validateProject(e))return e;s.compile=!0}return t}async validate(t){const e=this.resolveProjectPath(t.projectPath,t);let n=t.cliPath;return!1!==t.compile&&(n=this.resolveCliPath(t.cliPath||""),!n&&(n=this.resolveCliPath(e))),{port:await async function(t,e){const n=await f(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||1e5,projectPath:e}}async createRuntimeConnection(t,e){return E.createRuntimeConnection(t,this.puppet,e)}}module.exports=class{constructor(){this.launcher=new tt}async launch(t){return this.launcher.launch(t)}}; +function I(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 D;function T(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 A(t,e,n){return T(D.RUNTIME,n)}function x(t,e,n){return T(D.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(D||(D={}));class R{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===D.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 q extends R{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 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)}}I([A],q.prototype,"getData",null),I([A],q.prototype,"setData",null),I([A],q.prototype,"callMethod",null),I([x],q.prototype,"getElement",null),I([x],q.prototype,"getElements",null),I([x],q.prototype,"getOffset",null),I([x],q.prototype,"getHTML",null),I([x],q.prototype,"getAttributes",null),I([x],q.prototype,"getStyles",null),I([x],q.prototype,"getDOMProperties",null),I([x],q.prototype,"getProperties",null),I([x],q.prototype,"tap",null),I([x],q.prototype,"touchstart",null),I([x],q.prototype,"touchmove",null),I([x],q.prototype,"touchend",null),I([x],q.prototype,"triggerEvent",null),I([x],q.prototype,"callFunction",null),I([x],q.prototype,"callContextMethod",null);class j{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.elementMap=n,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new q(t,e)}async $(t){try{const e=await this.api.getElement({selector:t});return j.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=>j.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(){return this.api.getOffset()}async text(){return this.domProperty("innerText")}async attribute(t){if(!m(t))throw Error("name must be a string");return(await this.api.getAttributes({names:[t]})).attributes[0]}async value(){return this.property("value")}async property(t){if(!m(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._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(!m(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 await this.touchstart(),await v(350),this.touchend()}async trigger(t,e){const n={type:t};return w(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 C(async t=>(await this.api.getDOMProperties({names:t})).properties,t)}_property(t){return C(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=S;else switch(e.tagName){case"input":s=$;break;case"textarea":s=F;break;case"scroll-view":s=O;break;case"swiper":s=L;break;case"movable-view":s=U;break;case"switch":s=H;break;case"slider":s=N;break;case"video":s=B;break;default:s=j}return i=new s(t,e,n),n.set(e.elementId,i),i}}class S extends j{async setData(t){return this.api.setData({data:t})}async data(t){const e={};return t&&(e.path=t),(await this.api.getData(e)).data}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}}class $ extends j{async input(t){return this.callFunction("input.input",t)}}class F extends j{async input(t){return this.callFunction("textarea.input",t)}}class O extends j{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 L extends j{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class U extends j{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 H extends j{async tap(){return this.callFunction("switch.tap")}}class N extends j{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class B extends j{async callContextMethod(t,...e){return this.api.callContextMethod({method:t,args:e})}}class _ extends R{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 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)}}I([A],_.prototype,"getData",null),I([A],_.prototype,"setData",null),I([A],_.prototype,"callMethod",null),I([x],_.prototype,"getElement",null),I([x],_.prototype,"getElements",null),I([x],_.prototype,"getWindowProperties",null);class W{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 _(t,e)}async waitFor(t){return y(t)?await v(t):h(t)?l(t):m(t)?l(async()=>(await this.$$(t)).length>0):void 0}async $(t){try{const e=await this.api.getElement({selector:t});return j.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=>j.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap))}async data(t){const e={};return t&&(e.path=t),(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 scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(t){const e=m(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=new W(t,e),n.set(e.id,s),s)}}class V extends R{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 callFunction(t){return this.invoke("App.callFunction",t)}async captureScreenshot(t){return this.invoke("App.captureScreenshot",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)}}I([A],V.prototype,"getPageStack",null),I([A],V.prototype,"callUniMethod",null),I([A],V.prototype,"getCurrentPage",null),I([x],V.prototype,"mockUniMethod",null),I([x],V.prototype,"callFunction",null),I([x],V.prototype,"captureScreenshot",null),I([x],V.prototype,"exit",null),I([x],V.prototype,"addBinding",null),I([x],V.prototype,"enableLog",null);class z extends R{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 G(t){return new Promise(e=>setTimeout(e,t))}I([x],z.prototype,"getInfo",null),I([x],z.prototype,"enableRemoteDebug",null),I([x],z.prototype,"close",null),I([x],z.prototype,"getTestAccounts",null);class J extends r.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new V(t),this.toolApi=new z(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=>W.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 W.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 h(e)||m(s=e)&&(s=d(s),g(s,"function")||g(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 G(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=>{b.generate(n,{small:!0},e=>{process.stdout.write(e),t()})}));const s=new Promise(t=>{this.toolApi.onRemoteDebugConnected(async()=>{await G(1e3),t()})}),i=new Promise(t=>{this.puppet.setRemoteRuntimeConnectionCallback(()=>{t()})});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{data:e}=await this.appApi.captureScreenshot({fullPage:null==t?void 0:t.fullPage});if(!(null==t?void 0:t.path))return e;await u.writeFile(t.path,e,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(t,e){return await this.callUniMethod(t,{url:e}),await G(3e3),this.currentPage()}}class X{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"))}}class Y extends r.EventEmitter{constructor(t,e){if(super(),this.target=e||("h5"===t?require("@dcloudio/uni-h5/lib/h5/uni.automator.js"):require(`@dcloudio/uni-${t}/lib/uni.automator.js`)),!this.target)throw Error("puppet is not provided");this.platform=t,this.adapter=new X(this.target.adapter||{})}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.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(t,e){return this.runtimeConnection.send(t,e)}validateProject(t){const s=this.target.devtools.required;return!s||!s.find(s=>!e.existsSync(n.join(t,s)))}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){this.compiled=!0;const n=this.target.shouldCompile;return this.compiled=n?n(t,e):!1!==t.compile,this.compiled}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 K=s("automator:compiler"),Q=/The\s+(.*)\s+directory is ready/;class Z{constructor(t){this.puppet=t}compile(t){const e=this.puppet.mode,s=this.puppet.platform;let i=t.silent;const o=t.port,r=t.host,a=process.env.UNI_NPM_PATH||"npm",c=`${e}:${s}`,p=t.projectPath,l=["run",c,"--","--auto-port",P(o)];r&&(l.push("--auto-host"),l.push(r));const u={cwd:t.cliPath||t.projectPath,env:process.env};return new Promise((t,o)=>{const r=function(o){const r=o.toString().trim();if(!i&&console.log(r),r.includes("App running at:"))t({path:""});else if(r.includes("DONE Build complete")){let o=`unpackage/dist/${e}/${s}`;const a=r.match(Q);a&&a.length>1&&(o=a[1]),i=!0,c.kill("SIGTERM"),t({path:n.join(p,o)})}};K(`${a} ${l.join(" ")}`);const c=M.spawn(a,l,u);c.on("error",(function(t){o(t)})),c.stdout.on("data",r),c.stderr.on("data",r)})}}class tt{async launch(t){let e=t[t.platform]||{};this.puppet=new Y(t.platform,e.puppet);const{port:n,cliPath:i,timeout:o,projectPath:r}=await this.validate(t);e=await this.puppet.validateDevtools(e);let a=r;if(this.puppet.shouldCompile(t,e)){this.compiler=new Z(this.puppet);const e=await this.compiler.compile({host:t.host,port:n,cliPath:i,projectPath:r,silent:!!t.silent});e.path&&(a=e.path)}const c=[];return c.push(this.createRuntimeConnection(n,o)),c.push(this.puppet.createDevtools(a,e,o)),new Promise((t,n)=>{Promise.all(c).then(([n,i])=>{n&&this.puppet.setRuntimeConnection(n),i&&this.puppet.setDevtoolConnection(i),s("automator:program")("ready");const o=e.teardown||"disconnect";t(new J(this.puppet,{teardown:o}))}).catch(t=>n(t))})}resolveCliPath(t){if(!t)return t;try{const e=require(n.join(t,"package.json"));if(e.devDependencies&&e.devDependencies["@dcloudio/vue-cli-plugin-uni"])return t}catch(t){}throw Error(`Cli ${t} doesn't exist`)}resolveProjectPath(t,s){if(t||(t=process.cwd()),i(t)&&(t=n.resolve(t)),e.existsSync(t)||function(t){throw Error(t)}(`Project path ${t} doesn't exist`),!1===s.compile&&!this.puppet.validateProject(t)){const e=n.join(t,"dist/"+this.puppet.mode+"/"+this.puppet.platform);if(this.puppet.validateProject(e))return e;s.compile=!0}return t}async validate(t){const e=this.resolveProjectPath(t.projectPath,t);let n=t.cliPath;return!1!==t.compile&&(n=this.resolveCliPath(t.cliPath||""),!n&&(n=this.resolveCliPath(e))),{port:await async function(t,e){const n=await f(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||1e5,projectPath:e}}async createRuntimeConnection(t,e){return E.createRuntimeConnection(t,this.puppet,e)}}module.exports=class{constructor(){this.launcher=new tt}async launch(t){return this.launcher.launch(t)}}; diff --git a/packages/uni-automator/package.json b/packages/uni-automator/package.json index 09b8b83b5..e37881b24 100644 --- a/packages/uni-automator/package.json +++ b/packages/uni-automator/package.json @@ -13,7 +13,8 @@ ], "author": "fxy060608", "license": "Apache-2.0", - "dependencies": { + "dependencies": { + "adbkit": "^2.11.1", "debug": "^4.1.1", "jimp": "^0.10.1", "licia": "^1.21.0", diff --git a/packages/uni-mp-baidu/lib/uni.automator.js b/packages/uni-mp-baidu/lib/uni.automator.js index d00f62395..3365168d1 100644 --- a/packages/uni-mp-baidu/lib/uni.automator.js +++ b/packages/uni-mp-baidu/lib/uni.automator.js @@ -1 +1 @@ -"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("os")),r=e(require("path")),s=e(require("debug")),a=e(require("licia/isWindows")),n=e(require("fs")),o=e(require("child_process")),i=e(require("licia/sleep")),c=e(require("licia/toStr")),l=e(require("licia/waitUntil")),p=e(require("licia/concat")),u=e(require("licia/getPort")),m=e(require("licia/dateFormat"));require("jimp"),require("licia/isStr");var d=e(require("ws")),h=require("events"),f=e(require("licia/uuid")),g=e(require("licia/stringify"));const w=/(^[a-z][a-z0-9-]*)/i,y=/^navigator/i,E=/^swan-nav$/i;var b;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(b||(b={}));const v={[b.SELECTOR]:[{test:y,processor:e=>e.replace(y,"nav")},{test:w,processor:e=>"swan-"+e}],[b.TAGNAME]:[{test:E,processor:e=>e.replace(E,"swan-navigator")},{test:w,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},j=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},P=j(b.SELECTOR),q=j(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader");class M extends h.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()}}class C extends h.EventEmitter{constructor(e,t,r){super(),this.puppet=t,this.namespace=r,this.callbacks=new Map,this.transport=e,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:s,result:a,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(r,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),s?e.reject(Error(s.message)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const s=f(),a=g({id:s,method:e,params:t});return this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${a}`),new Promise((e,t)=>{try{this.transport.send(a)}catch(e){t(Error("Connection closed"))}this.callbacks.set(s,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,s)=>{const a=new d(e);a.addEventListener("open",()=>{r(new C(new M(a),t,"devtool"))}),a.addEventListener("error",s)})}static createRuntimeConnection(e,t,r){return new Promise((a,n)=>{s("automator:runtime")(`${m("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new d.Server({port:e});l(async()=>{if(t.runtimeConnection)return!0},r,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),o.on("connection",(function(e){s("automator:runtime")(m("yyyy-mm-dd HH:MM:ss:l")+" connected");const r=new C(new M(e),t,"runtime");t.setRuntimeConnection(r),a(r)})),t.setRuntimeServer(o)})}}const $=s("automator:devtool");async function S(e,t,r){const{port:s,cliPath:a,timeout:n,cwd:u="",account:d="",args:h=[],launch:f=!0}=t;let g=!1,w=!1;if(!1!==f){const t={detached:!0,stdio:"ignore"};u&&(t.cwd=u);let r=p(h,["--auto",e,"--auto-port",c(s)]);d&&(r=p(r,["--auto-account",d]));try{$("%s %o %o",a,r,t);const e=o.spawn(a,r,t);e.on("error",e=>{g=!0}),e.on("exit",()=>{setTimeout(()=>{w=!0},15e3)}),e.unref()}catch(e){g=!1}}else setTimeout(()=>{w=!0},15e3);const y=await l(async()=>{try{if(g||w)return!0;return await async function(e,t){let r;try{r=await C.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+s},r)}catch(e){}},n,1e3);if(g)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(w)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),$(m("yyyy-mm-dd HH:MM:ss:l")+" connected"),y}const A=[];["","-rc"].forEach(e=>{a?(A.push(r.join(t.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),A.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):A.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)});const T={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:A,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let s=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{s=await async function(e,t){const r=await u(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await u(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,t,r){const a=await S(e,t,r);return s("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:(r=t.selector,r.split(" ").map(e=>P(e)).join(" "))}))).map(e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:q(t.tagName)}})};var r}},"Page.getWindowProperties":{reflect:async(e,t)=>{const r=t.names.map(e=>e.replace("document.documentElement.","")),s=(await e("smartapp.element.getBySelector",{properties:r,selector:"html"}))[0];return{properties:r.map(e=>s.properties[e])}}},"Element.getHTML":{reflect:async(e,t)=>{const r=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:r}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:r}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return r.forEach(e=>{e.nodeId=e.id}),{elements:r}}},"Element.getAttributes":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{attributes:r}},params:O},"Element.getStyles":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getComputedStyle",Object.assign({style:s},t)));return{styles:r}},params:O},"Element.getDOMProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getProperty",Object.assign({property:s},t)));return{properties:r}},params:O},"Element.getProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{properties:r}},params:O},"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:O},"Element.tap":{reflect:"smartapp.element.touch",params:O}}};module.exports=T; +"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("os")),r=e(require("path")),s=e(require("debug")),a=e(require("licia/isWindows")),n=e(require("fs")),o=e(require("child_process")),i=e(require("licia/sleep")),c=e(require("licia/toStr")),l=e(require("licia/waitUntil")),p=e(require("licia/concat")),u=e(require("licia/getPort")),m=e(require("licia/dateFormat"));require("jimp"),require("licia/isStr");var d=e(require("ws")),h=require("events"),f=e(require("licia/uuid")),g=e(require("licia/stringify"));const w=/(^[a-z][a-z0-9-]*)/i,y=/^navigator/i,E=/^swan-nav$/i;var b;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(b||(b={}));const v={[b.SELECTOR]:[{test:y,processor:e=>e.replace(y,"nav")},{test:w,processor:e=>"swan-"+e}],[b.TAGNAME]:[{test:E,processor:e=>e.replace(E,"swan-navigator")},{test:w,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},j=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},P=j(b.SELECTOR),q=j(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader");class M extends h.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()}}class C extends h.EventEmitter{constructor(e,t,r){super(),this.puppet=t,this.namespace=r,this.callbacks=new Map,this.transport=e,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:s,result:a,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(r,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),s?e.reject(Error(s.message)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const s=f(),a=g({id:s,method:e,params:t});return this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${a}`),new Promise((e,t)=>{try{this.transport.send(a)}catch(e){t(Error("Connection closed"))}this.callbacks.set(s,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,s)=>{const a=new d(e);a.addEventListener("open",()=>{r(new C(new M(a),t,"devtool"))}),a.addEventListener("error",s)})}static createRuntimeConnection(e,t,r){return new Promise((a,n)=>{s("automator:runtime")(`${m("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new d.Server({port:e});l(async()=>{if(t.runtimeConnection)return!0},r,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),o.on("connection",(function(e){s("automator:runtime")(m("yyyy-mm-dd HH:MM:ss:l")+" connected");const r=new C(new M(e),t,"runtime");t.setRuntimeConnection(r),a(r)})),t.setRuntimeServer(o)})}}const $=s("automator:devtool");async function S(e,t,r){const{port:s,cliPath:a,timeout:n,cwd:u="",account:d="",args:h=[],launch:f=!0}=t;let g=!1,w=!1;if(!1!==f){const t={stdio:"ignore"};u&&(t.cwd=u);let r=p(h,[]);r=p(r,["--auto"]),r=p(r,[e,"--auto-port",c(s)]),d&&(r=p(r,["--auto-account",d]));try{$("%s %o %o",a,r,t);const e=o.spawn(a,r,t);e.on("error",e=>{g=!0}),e.on("exit",()=>{setTimeout(()=>{w=!0},15e3)}),e.unref()}catch(e){g=!1}}else setTimeout(()=>{w=!0},15e3);const y=await l(async()=>{try{if(g||w)return!0;return await async function(e,t){let r;try{r=await C.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+s},r)}catch(e){}},n,1e3);if(g)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(w)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),$(m("yyyy-mm-dd HH:MM:ss:l")+" connected"),y}const A=[];["","-rc"].forEach(e=>{a?(A.push(r.join(t.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),A.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):A.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)});const T={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:A,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let s=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{s=await async function(e,t){const r=await u(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await u(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,t,r){const a=await S(e,t,r);return s("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:(r=t.selector,r.split(" ").map(e=>P(e)).join(" "))}))).map(e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:q(t.tagName)}})};var r}},"Page.getWindowProperties":{reflect:async(e,t)=>{const r=t.names.map(e=>e.replace("document.documentElement.","")),s=(await e("smartapp.element.getBySelector",{properties:r,selector:"html"}))[0];return{properties:r.map(e=>s.properties[e])}}},"Element.getHTML":{reflect:async(e,t)=>{const r=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:r}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:r}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return r.forEach(e=>{e.nodeId=e.id}),{elements:r}}},"Element.getAttributes":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{attributes:r}},params:O},"Element.getStyles":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getComputedStyle",Object.assign({style:s},t)));return{styles:r}},params:O},"Element.getDOMProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getProperty",Object.assign({property:s},t)));return{properties:r}},params:O},"Element.getProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{properties:r}},params:O},"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:O},"Element.tap":{reflect:"smartapp.element.touch",params:O}}};module.exports=T; diff --git a/packages/uni-mp-weixin/lib/uni.automator.js b/packages/uni-mp-weixin/lib/uni.automator.js index 8155c30af..b3ec1beb8 100644 --- a/packages/uni-mp-weixin/lib/uni.automator.js +++ b/packages/uni-mp-weixin/lib/uni.automator.js @@ -1 +1 @@ -"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("debug")),r=e(require("licia/isWindows")),n=e(require("jimp"));require("licia/isStr");var o=e(require("licia/getPort")),s=e(require("fs")),i=e(require("child_process")),a=e(require("licia/sleep")),c=e(require("licia/toStr")),l=e(require("licia/waitUntil")),u=e(require("licia/concat")),d=e(require("licia/dateFormat")),p=e(require("ws")),h=require("events"),m=e(require("licia/uuid")),w=e(require("licia/stringify"));require("qrcode-terminal");const f=require("qrcode-reader");class y extends h.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()}}class g extends h.EventEmitter{constructor(e,r,n){super(),this.puppet=r,this.namespace=n,this.callbacks=new Map,this.transport=e,this.debug=t("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${d("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:n,result:o,params:s}=JSON.parse(e);if(!t)return this.puppet.emit(r,s);const{callbacks:i}=this;if(t&&i.has(t)){const e=i.get(t);i.delete(t),n?e.reject(Error(n.message)):e.resolve(o)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const n=m(),o=w({id:n,method:e,params:t});return this.debug(`${d("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${o}`),new Promise((e,t)=>{try{this.transport.send(o)}catch(e){t(Error("Connection closed"))}this.callbacks.set(n,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,n)=>{const o=new p(e);o.addEventListener("open",()=>{r(new g(new y(o),t,"devtool"))}),o.addEventListener("error",n)})}static createRuntimeConnection(e,r,n){return new Promise((o,s)=>{t("automator:runtime")(`${d("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const i=new p.Server({port:e});l(async()=>{if(r.runtimeConnection)return!0},n,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),i.on("connection",(function(e){t("automator:runtime")(d("yyyy-mm-dd HH:MM:ss:l")+" connected");const n=new g(new y(e),r,"runtime");r.setRuntimeConnection(n),o(n)})),r.setRuntimeServer(i)})}}const v=t("automator:devtool");async function b(e,t,r){const{port:n,cliPath:o,timeout:s,cwd:p="",account:h="",args:m=[],launch:w=!0}=t;let f=!1,y=!1;if(!1!==w){const t={detached:!0,stdio:"ignore"};p&&(t.cwd=p);let r=u(m,["--auto",e,"--auto-port",c(n)]);h&&(r=u(r,["--auto-account",h]));try{v("%s %o %o",o,r,t);const e=i.spawn(o,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{y=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{y=!0},15e3);const b=await l(async()=>{try{if(f||y)return!0;return await async function(e,t){let r;try{r=await g.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+n},r)}catch(e){}},s,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(y)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await a(5e3),v(d("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const E={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[r?"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 r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(s.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let n=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{n=await async function(e,t){const r=await o(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(n)}catch(t){e.launch=!1}else{n===await o(n)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:n,cliPath:r})},async create(e,r,n){const o=await b(e,r,n);return t("automator:devtool")("initRuntimeAutomator"),o.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]}),o}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:r}=await e("Tool.enableRemoteDebug",t,!1);return r&&(r=await function(e){const t=new Buffer(e,"base64");return new Promise(async(e,r)=>{const o=await n.read(t),s=new f;s.callback=function(t,n){if(t)return r(t);e(n.result)},s.decode(o.bitmap)})}(r)),{qrCode:r}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(r=t.functionDeclaration,"}"===r[r.length-1]?r.replace("{","{\nvar uni = wx;\n"):r.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var r}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=E; +"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("debug")),r=e(require("licia/isWindows")),n=e(require("jimp"));require("licia/isStr");var o=e(require("licia/getPort")),s=e(require("fs")),i=e(require("child_process")),a=e(require("licia/sleep")),c=e(require("licia/toStr")),l=e(require("licia/waitUntil")),u=e(require("licia/concat")),d=e(require("licia/dateFormat")),p=e(require("ws")),h=require("events"),m=e(require("licia/uuid")),w=e(require("licia/stringify"));require("qrcode-terminal");const f=require("qrcode-reader");class y extends h.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()}}class g extends h.EventEmitter{constructor(e,r,n){super(),this.puppet=r,this.namespace=n,this.callbacks=new Map,this.transport=e,this.debug=t("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${d("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:n,result:o,params:s}=JSON.parse(e);if(!t)return this.puppet.emit(r,s);const{callbacks:i}=this;if(t&&i.has(t)){const e=i.get(t);i.delete(t),n?e.reject(Error(n.message)):e.resolve(o)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const n=m(),o=w({id:n,method:e,params:t});return this.debug(`${d("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${o}`),new Promise((e,t)=>{try{this.transport.send(o)}catch(e){t(Error("Connection closed"))}this.callbacks.set(n,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,n)=>{const o=new p(e);o.addEventListener("open",()=>{r(new g(new y(o),t,"devtool"))}),o.addEventListener("error",n)})}static createRuntimeConnection(e,r,n){return new Promise((o,s)=>{t("automator:runtime")(`${d("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const i=new p.Server({port:e});l(async()=>{if(r.runtimeConnection)return!0},n,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),i.on("connection",(function(e){t("automator:runtime")(d("yyyy-mm-dd HH:MM:ss:l")+" connected");const n=new g(new y(e),r,"runtime");r.setRuntimeConnection(n),o(n)})),r.setRuntimeServer(i)})}}const v=t("automator:devtool");async function b(e,t,r){const{port:n,cliPath:o,timeout:s,cwd:p="",account:h="",args:m=[],launch:w=!0}=t;let f=!1,y=!1;if(!1!==w){const t={stdio:"ignore",detached:!0};p&&(t.cwd=p);let r=u(m,[]);r=u(r,["auto","--project"]),r=u(r,[e,"--auto-port",c(n)]),h&&(r=u(r,["--auto-account",h]));try{v("%s %o %o",o,r,t);const e=i.spawn(o,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{y=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{y=!0},15e3);const b=await l(async()=>{try{if(f||y)return!0;return await async function(e,t){let r;try{r=await g.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+n},r)}catch(e){}},s,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(y)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await a(5e3),v(d("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const E={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[r?"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 r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(s.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let n=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{n=await async function(e,t){const r=await o(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(n)}catch(t){e.launch=!1}else{n===await o(n)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:n,cliPath:r})},async create(e,r,n){const o=await b(e,r,n);return t("automator:devtool")("initRuntimeAutomator"),o.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]}),o}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:r}=await e("Tool.enableRemoteDebug",t,!1);return r&&(r=await function(e){const t=new Buffer(e,"base64");return new Promise(async(e,r)=>{const o=await n.read(t),s=new f;s.callback=function(t,n){if(t)return r(t);e(n.result)},s.decode(o.bitmap)})}(r)),{qrCode:r}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(r=t.functionDeclaration,"}"===r[r.length-1]?r.replace("{","{\nvar uni = wx;\n"):r.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var r}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=E; diff --git a/packages/uni-quickapp-light/dist/index.js b/packages/uni-quickapp-light/dist/index.js index 5ede2af66..34ce0a82d 100644 --- a/packages/uni-quickapp-light/dist/index.js +++ b/packages/uni-quickapp-light/dist/index.js @@ -1206,7 +1206,7 @@ function parseBaseApp (vm, { return appOptions } -const mocks = ['nodeId', 'componentName']; +const mocks = ['nodeId', 'componentName' ,'_componentId']; function isPage () { return !this.ownerId diff --git a/packages/vue-cli-plugin-hbuilderx/packages/webpack-app-plus-plugin/index.js b/packages/vue-cli-plugin-hbuilderx/packages/webpack-app-plus-plugin/index.js index bde37c939..7c2d41b93 100644 --- a/packages/vue-cli-plugin-hbuilderx/packages/webpack-app-plus-plugin/index.js +++ b/packages/vue-cli-plugin-hbuilderx/packages/webpack-app-plus-plugin/index.js @@ -87,7 +87,7 @@ class WebpackAppPlusPlugin { done(`Build complete. FILES:` + JSON.stringify(changedFiles)) } } else { - done(`Build complete. Watching for changes...`) + !process.env.UNI_AUTOMATOR_WS_ENDPOINT && done(`Build complete. Watching for changes...`) } isFirst = false } else { diff --git a/packages/vue-cli-plugin-uni/commands/build.js b/packages/vue-cli-plugin-uni/commands/build.js index 470a2171c..c1d0dbe3f 100644 --- a/packages/vue-cli-plugin-uni/commands/build.js +++ b/packages/vue-cli-plugin-uni/commands/build.js @@ -154,7 +154,7 @@ async function build (args, api, options) { return reject('Build failed with errors.') } - if (!args.silent && process.env.UNI_PLATFORM !== 'app-plus') { + if (!args.silent && (process.env.UNI_PLATFORM !== 'app-plus' || process.env.UNI_AUTOMATOR_WS_ENDPOINT)) { const targetDirShort = path.relative( api.service.context, process.env.UNI_OUTPUT_DIR -- GitLab