aiot-toolkit 1.0.18-aspect-beta.7 → 1.0.18-aspect-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -122,9 +122,13 @@ module.exports = function genWebpackConf(launchOptions, mode) {
122
122
  if (globalConfig.aspectTemplate.isAspect) {
123
123
  BUILD_DIR = path.resolve(globalConfig.aspectTemplate.outputPath, path.basename(cwd))
124
124
  DIST_DIR = path.resolve(globalConfig.aspectTemplate.outputPath, '')
125
+ // 清理 BUILD_DIR
126
+ cleanup(BUILD_DIR)
125
127
  } else {
126
128
  BUILD_DIR = path.resolve(cwd, globalConfig.outputPath)
127
129
  DIST_DIR = launchOptions.setPreviewPkgPath || path.resolve(cwd, globalConfig.releasePath)
130
+ // 清理 BUILD_DIR DIST_DIR
131
+ cleanup(BUILD_DIR, DIST_DIR)
128
132
  }
129
133
 
130
134
  // 打包配置文件
@@ -139,7 +143,7 @@ module.exports = function genWebpackConf(launchOptions, mode) {
139
143
  validateProject(manifestFile, SRC_DIR)
140
144
 
141
145
  // 清理 BUILD_DIR DIST_DIR
142
- cleanup(BUILD_DIR, DIST_DIR)
146
+ // cleanup(BUILD_DIR, DIST_DIR)
143
147
 
144
148
  // 将aspect文件夹的config.json文件复制到build文件夹
145
149
  if (globalConfig.aspectTemplate.isAspect && !globalConfig.aspectTemplate.isApp) {
@@ -1,2 +1,2 @@
1
- "use strict";var _config=_interopRequireDefault(require("@aiot-toolkit/shared-utils/config"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const webpack=require("webpack"),{setCustomConfig:setCustomConfig,colorconsole:colorconsole,getProjectJson:getProjectJson,getManifest:getManifest}=require("@aiot-toolkit/shared-utils"),genWebpackConf=require("../../gen-webpack-conf"),{summaryErrors:summaryErrors,summaryWarnings:summaryWarnings,getAspectEntries:getAspectEntries,cleanOrCreateDir:cleanOrCreateDir}=require("./utils"),{devicePackRpk:devicePackRpk}=require("@aiot-toolkit/packager/lib/common/ziputil"),{validateConfigJson:validateConfigJson}=require("../../gen-webpack-conf/validate"),path=require("path");let appName,watching=null;function showVersion(){const e=require("../../package.json").version,t=require("@babel/core/package.json").version,o=require("webpack/package.json").version;colorconsole.info(`aiot-toolkit: ${e}; babel: ${t}; webpack: ${o};`)}async function aspectProjectCompiler(e,t,o,a={}){let r=getManifest();appName=r.package||"demo";const{entries:c,deviceAspects:n,routerObj:i}=getAspectEntries(_config.default.aspectTemplate.projectPath,r);validateConfigJson(c),cleanOrCreateDir(_config.default.aspectTemplate.outputPath),cleanOrCreateDir(_config.default.aspectTemplate.distPath);const s=_config.default.aspectTemplate.outputPath;let p;_config.default.aspectTemplate.outputPath=path.join(s,appName);const l=[];c.forEach((r=>{_config.default.sourceRoot="./src",_config.default.aspectTemplate.isApp="app"===r,_config.default.aspectTemplate.isApp&&(_config.default.sourceRoot=""),a.cwd=path.join(_config.default.aspectTemplate.projectPath,r),p=singleCompiler(e,t,o,a),l.push(p)}));let u=await Promise.all(l);return await devicePackRpk(c,n,i,appName),u}function singleCompiler(e,t,o,a={}){const r=a.onerror;return new Promise(((c,n)=>{function i(e,t){if(e&&(r&&r(e),colorconsole.error(e)),t){if(t.hasErrors()||t.hasWarnings()){const e=summaryErrors(t),o=summaryWarnings(t);r&&r(e),colorconsole.error(e),colorconsole.warn(o)}t.hasErrors()&&(process.exitCode=1)}}colorconsole.attach(a.log),setCustomConfig(a.cwd),process.env.NODE_PLATFORM=e,process.env.NODE_PHASE=t;const s="prod"===t?"production":"development";try{const e=genWebpackConf(a,s);if(o){const t=webpack(e);watching=t.watch({aggregateTimeout:300},((e,t)=>{i(e,t),c({compileError:e,stats:t,watching:watching})}))}else webpack(e,((e,t)=>{i(e,t),c({compileError:e,stats:t})}))}catch(e){n(e)}}))}showVersion(),module.exports.compile=async function(e,t,o,a={}){var r;let c;return"distributed"===(null===(r=getProjectJson())||void 0===r?void 0:r.projectType)?(_config.default.aspectTemplate.isAspect=!0,c=await aspectProjectCompiler(e,t,o,a)):c=await singleCompiler(e,t,o,a),c},module.exports.stopWatch=function(){return new Promise((e=>{watching?watching.close((()=>{watching=null,e({stopWatchError:null})})):e({stopWatchError:"no watching"})}))};
1
+ "use strict";var _config=_interopRequireDefault(require("@aiot-toolkit/shared-utils/config"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const webpack=require("webpack"),{setCustomConfig:setCustomConfig,colorconsole:colorconsole,getProjectJson:getProjectJson,getManifest:getManifest}=require("@aiot-toolkit/shared-utils"),genWebpackConf=require("../../gen-webpack-conf"),{summaryErrors:summaryErrors,summaryWarnings:summaryWarnings,getAspectEntries:getAspectEntries,cleanOrCreateDir:cleanOrCreateDir}=require("./utils"),{devicePackRpk:devicePackRpk}=require("@aiot-toolkit/packager/lib/common/ziputil"),{validateConfigJson:validateConfigJson}=require("../../gen-webpack-conf/validate"),path=require("path");let appName,watching=null;function showVersion(){const e=require("../../package.json").version,o=require("@babel/core/package.json").version,t=require("webpack/package.json").version;colorconsole.info(`aiot-toolkit: ${e}; babel: ${o}; webpack: ${t};`)}async function aspectProjectCompiler(e,o,t,r={}){let a=getManifest();appName=a.package||"demo";const{entries:c,deviceAspects:i,routerObj:n}=getAspectEntries(_config.default.aspectTemplate.projectPath,a);validateConfigJson(c),cleanOrCreateDir(_config.default.aspectTemplate.outputPath),cleanOrCreateDir(_config.default.aspectTemplate.distPath);const s=_config.default.aspectTemplate.outputPath;_config.default.aspectTemplate.outputPath=path.join(s,appName);try{for(let a of c)_config.default.sourceRoot="./src",_config.default.aspectTemplate.isApp="app"===a,_config.default.aspectTemplate.isApp&&(_config.default.sourceRoot=""),r.cwd=path.join(_config.default.aspectTemplate.projectPath,a),await singleCompiler(e,o,t,r);return await devicePackRpk(c,i,n,appName),Promise.resolve()}catch(e){console.log(`aspectProjectCompiler error ${e}`)}}function singleCompiler(e,o,t,r={}){const a=r.onerror;return new Promise(((c,i)=>{function n(e,o){if(e&&(a&&a(e),colorconsole.error(e)),o){if(o.hasErrors()||o.hasWarnings()){const e=summaryErrors(o),t=summaryWarnings(o);a&&a(e),colorconsole.error(e),colorconsole.warn(t)}o.hasErrors()&&(process.exitCode=1)}}colorconsole.attach(r.log),setCustomConfig(r.cwd),process.env.NODE_PLATFORM=e,process.env.NODE_PHASE=o;const s="prod"===o?"production":"development";try{const e=genWebpackConf(r,s);if(t){const o=webpack(e);watching=o.watch({aggregateTimeout:300},((e,o)=>{n(e,o),c({compileError:e,stats:o,watching:watching})}))}else webpack(e,((e,o)=>{n(e,o),c({compileError:e,stats:o})}))}catch(e){console.log(`singleCompiler error ${e}`)}}))}showVersion(),module.exports.compile=async function(e,o,t,r={}){var a;let c;return"distributed"===(null===(a=getProjectJson())||void 0===a?void 0:a.projectType)?(_config.default.aspectTemplate.isAspect=!0,c=await aspectProjectCompiler(e,o,t,r)):c=await singleCompiler(e,o,t,r),c},module.exports.stopWatch=function(){return new Promise((e=>{watching?watching.close((()=>{watching=null,e({stopWatchError:null})})):e({stopWatchError:"no watching"})}))};
2
2
  //# sourceMappingURL=compile.js.map
@@ -1,2 +1,2 @@
1
- "use strict";function ownKeys(e,r){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),o.push.apply(o,t)}return o}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(o),!0).forEach((function(r){_defineProperty(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):ownKeys(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function _defineProperty(e,r,o){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}function _toPropertyKey(e){var r=_toPrimitive(e,"string");return"symbol"==typeof r?r:String(r)}function _toPrimitive(e,r){if("object"!=typeof e||null===e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var t=o.call(e,r||"default");if("object"!=typeof t)return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}const path=require("path"),fs=require("fs"),chalk=require("chalk"),inquirer=require("inquirer"),adbCommander=require("adb-commander"),{launchServer:launchServer}=require("@aiot-toolkit/server"),{compile:compile}=require("./compile"),{colorconsole:colorconsole}=require("@aiot-toolkit/shared-utils"),{downloadFile:downloadFile,getQuickappDebuggerUrl:getQuickappDebuggerUrl,getQuickappPreviewUrl:getQuickappPreviewUrl,sendReq:sendReq,getClients:getClients,checkQuickappDir:checkQuickappDir,getCardContent:getCardContent}=require("./utils"),{recordClient:recordClient,clearProjectRecord:clearProjectRecord}=require("@aiot-toolkit/shared-utils/lib/record-client"),{clientRecordPath:clientRecordPath}=require("@aiot-toolkit/shared-utils/config"),ipRegExp=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,CLIENT_PORT=39517;async function connectDevice(e=""){try{const r="Yes, connect a new wifi device";if(!e){if((await inquirer.prompt([{name:"type",type:"list",message:"(USB devices will automatically connect) Choose whether to connect to a new wifi device, and fill in its IP address later:",choices:[r,"Skip, keep connected device"]}])).type!==r)return Promise.resolve();e=(await inquirer.prompt([{name:"ip",message:'Please enter the IP address of the device under wifi(eg:192.168.1.1),make sure that the computer and the device are under the same wifi。If you need to enter multiple IPs, please separate them with ",":',default:null}])).ip}if(0===e.length)return colorconsole.info("Since no ip address is entered, the connected device will be connected"),Promise.resolve();const o=e.trim().split(","),t=o.filter((e=>!ipRegExp.test(e)));if(!t||!t.length){const e=Array.from(o,(e=>adbCommander.exeCommand(`adb connect ${e}:5555`).then((({result:r,err:o})=>((o||r.indexOf("failed")>=0)&&(colorconsole.error(`wifi connection ip: The device with ip of "${e}" failed`),process.exit()),colorconsole.info(`wifi connection ip: The device with ip of "${e}" succeeded`),recordClient(clientRecordPath,{ip:e,port:CLIENT_PORT}),Promise.resolve())))));return Promise.all(e).then((()=>(colorconsole.log("All new WIFI devices are connected"),Promise.resolve()))).catch((()=>{process.exit()}))}t.map((e=>{colorconsole.error(`ip: ${e} is invalid IP`)})),process.exit()}catch(e){return Promise.reject(new Error(`Error connecting to the device, error message:${e.message}`))}}async function getConnectDevices(e=!0){try{return adbCommander.deviceList().then((({deviceList:r,err:o})=>{if(o){const e="Error getting connection information of adb device";colorconsole.throw(e,o)}if(r.length>0)return e&&colorconsole.info(`Devices connected via adb: ${chalk.yellow(r.join(", "))}.`),Promise.resolve(r);{const e="No device is currently connected, please check the following preparations in turn:\n 1. Whether the device is started;\n 2. Whether in the same LAN WI-FI;\n 3. Whether the device can be connected to the computer via USB;";colorconsole.throw(e)}}))}catch(e){return Promise.reject(new Error(e.message))}}async function downloadApk(e,r){let o="";const{apkVersion:t}=e;o=r?getQuickappDebuggerUrl(t):getQuickappPreviewUrl(t);const n=path.basename(o),i=path.join(__dirname,"./apk/",n);return fs.existsSync(i)?(colorconsole.log("The installation package has been downloaded, now use the cache file to install"),i):downloadFile(o,n).then((e=>(colorconsole.info(e),i))).catch((e=>{colorconsole.error("Failed to download the installation package",e),process.exit()}))}async function installApk(e,r=[],o,t,n){const{forceInstall:i=!1}=e;try{const e=Array.from(r,(e=>adbCommander.isInstalled(e,t).then((async({isInstalled:r,err:c})=>(c&&colorconsole.error(`Failed to install application "${chalk.yellow(n)}" on "${chalk.yellow(e)}" device, error message:${JSON.stringify(c)} `),!1===r||i?(await adbCommander.uninstall(e,t),colorconsole.log(`Start to install application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}" : `),adbCommander.install(e,o).then((({result:r,err:o})=>o?(colorconsole.error(`Failed to install application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}", please troubleshoot and try again `),Promise.reject(new Error(`Failed to install application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}", please troubleshoot and try again `))):adbCommander.isInstalled(e,t).then((({isInstalled:r,err:o})=>{if(!0===r)return colorconsole.info(`Successfully installed application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}" `),Promise.resolve()}))))):(colorconsole.warn(`Application "${chalk.yellow(n)}" has been installed on device "${chalk.yellow(e)}", so the installation did not continue this time`),Promise.resolve()))))));return Promise.all(e).then((()=>(colorconsole.log("All devices installed"),Promise.resolve()))).catch((()=>{process.exit()}))}catch(e){return Promise.reject(e)}}async function startServer(e){const{address:r}=await launchServer(_objectSpread({clearRecords:!0},e));return await compile("native","dev",!0,e),r}async function installdbg(e,r=!0){try{const{ip:o}=e;r&&await connectDevice(o);const t=await getConnectDevices(r),n=await queryDevice(t,"Install Quickapp debugger"),i=await downloadApk(e,!0);return await installApk(e,n,i,"org.hapjs.debugger","Quickapp debugger"),Promise.resolve("All devices successfully installed the Quickapp debugger")}catch(e){return Promise.reject(new Error(`Failed to install debugger, error message:${e.message}`))}}async function installmkp(e,r=!0){try{const{ip:o}=e;r&&await connectDevice(o);const t=await getConnectDevices(r),n=await queryDevice(t,"Install the Quickapp preview version"),i=await downloadApk(e);return await installApk(e,n,i,"org.hapjs.mockup","Quickapp preview version"),Promise.resolve("All devices successfully installed the Quickapp preview version")}catch(e){return Promise.reject(new Error(`Failed to install the preview version of Quickapp, error message:${e.message}`))}}async function queryDevice(e,r=""){if(!e||0===e.length)return void colorconsole.error("No device is connected yet, please confirm and try again");const o="All connected devices",t=(await inquirer.prompt([{name:"device",type:"list",message:`Please select the device that needs to execute command "${r}":`,choices:[...e,o]}])).device;return t===o?e:[t]}async function startDebugger(e=[],r){colorconsole.info("Starting the debugger for the connected device...");const o=Array.from(e,(e=>adbCommander.exeCommand(`adb -s ${e} shell am start -n "org.hapjs.debugger/.MainActivity" ${r}`).then((({err:r})=>r?(colorconsole.error(`Failed to start "Quickapp Debugger" on device "${chalk.yellow(e)}", please troubleshoot and try again`),Promise.reject(new Error(JSON.stringify(r)))):(colorconsole.info(`Successfully start "Quickapp Debugger" on device "${chalk.yellow(e)}" `),Promise.resolve())))));return Promise.all(o).then((()=>(colorconsole.info("The debuggers of all devices have started up"),Promise.resolve()))).catch((()=>{process.exit()}))}async function runapp(e,r=!0,o=!0){try{e.log&&colorconsole.attach(e.log);const{debugMode:t=!1,cardMode:n=!1}=e;let i="",c="",a="";const s=process.cwd();let l=e.includeStaticResources?"":"src";if(checkQuickappDir(s,l),n){colorconsole.warn('Please enable the "self-start" and "associated start" permissions of the Quickapp debugger and preview engine in the Android system');const e=getCardContent(s);if(e){const r=Object.keys(e);if(r.length>1){const o=await inquirer.prompt([{name:"cardName",type:"list",message:"Please select a card for debugging:",choices:r}]);c=e[o.cardName].path||`/${o.cardName}`}else c=e[r[0]].path||`/${r[0]}`;a+=`-e cardMode true -e cardPath ${c}`}}clearProjectRecord(clientRecordPath),i=await startServer(e),a+=` -e path ${i}`,i||(colorconsole.error("Failed to start local Quickapp service, please troubleshoot and try again"),process.exit()),o&&await connectDevice();const d=await getConnectDevices(r);d&&0!==d.length||(colorconsole.error("No connected devices available!!"),process.exit()),await startDebugger(d,a),setTimeout((async()=>{const e=await getClients();e||(colorconsole.error("No connected devices available!!"),process.exit());for(let r of e){const{sn:e,ip:o}=r;if("127.0.0.1"===o&&e.includes(":5555"))continue;const n=e&&e.length>0?e:o,i=()=>{colorconsole.error(`Error when device "${n}" gets the list of running platforms, request again after 3s delay`),setTimeout((()=>{c()}),3e3)},c=async()=>{let e=await sendReq(r,"/availablePlatforms");e||i(),e=JSON.parse(e);const{availablePlatforms:c}=e;if(c){let e;if(0===c.length)return void colorconsole.error(`Quickapp Engine is not installed on device ${o}`);if(1===c.length)e=c[0].pkg;else if(c.length>1){const r=await inquirer.prompt([{name:"name",type:"list",message:`Multiple Quickapp engines are detected on device "${n}", please select the operating platform:`,choices:c}]);c.forEach((o=>{o.name===r.name&&(e=o.pkg)}))}"OK"===await sendReq(r,"/platform",{selectedPlatform:e})&&sendReq(r,"/update",{debug:t})}else i()};await c()}}),3e3)}catch(e){return Promise.reject(new Error(`Error running RPK on the device, error message:${e.message}`))}}async function installAndRun(e){try{const r=process.cwd();checkQuickappDir(r),await installdbg(e),await installmkp(e,!1),await runapp(Object.assign({},e,{enableServerWatch:!0}),!1,!1)}catch(e){return Promise.reject(new Error(`One-click debugging error, error message:${e.message}`))}}async function getAvailablePlatform(e){try{const{ip:r,port:o,sn:t}=e;r&&ipRegExp.test(r)||(colorconsole.error("Did not pass in the correct ip address, eg: --ip 127.0.0.1"),process.exit()),o||(colorconsole.error("Did not pass in the correct port address,eg: --port 39517"),process.exit()),t||(colorconsole.error('Did not pass in the correct device serial number,view the serial number of the connected device through the "adb devices" command \n If it is a device connected via wifi, the format is "ip address:5555"'),process.exit());let n={ip:r,port:o};const i=()=>{colorconsole.error("Error when the device gets running platforms,request again after 3s delay"),setTimeout((()=>{c()}),3e3)},c=async()=>{let e=await sendReq(n,"/availablePlatforms");if(e)if(e=JSON.parse(e),e.availablePlatforms){const r=e.availablePlatforms;colorconsole.info(`The Quickapp engine list of device "${t}" is:${r.join(", ")}`)}else i();else i()};adbCommander.exeCommand(`adb -s ${t} shell am start -n "org.hapjs.debugger/.MainActivity"`).then((({err:e})=>{e&&(colorconsole.error("The debugger does not start normally, please check if it is installed"),process.exit()),colorconsole.info(`The debugger successfully runs on device "${chalk.yellow(t)}"`),colorconsole.info(`Device "${t}" is getting the list of fast application engines...`),c()}))}catch(e){colorconsole.error(`Error getting the list of Quickapp engines on the device, error message:${e.message}`)}}async function getAllConnectedDevices(e){try{return adbCommander.deviceList().then((({deviceList:e,err:r})=>{if(!r)return Promise.resolve(e);colorconsole.throw(r)}))}catch(e){return Promise.reject(new Error(`Error getting the array of all connected devices, error message:${e.message}`))}}module.exports={installAndRun:installAndRun,installdbg:installdbg,installmkp:installmkp,runapp:runapp,getAvailablePlatform:getAvailablePlatform,getAllConnectedDevices:getAllConnectedDevices};
1
+ "use strict";function ownKeys(e,r){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),o.push.apply(o,t)}return o}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(o),!0).forEach((function(r){_defineProperty(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):ownKeys(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function _defineProperty(e,r,o){return r in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}const path=require("path"),fs=require("fs"),chalk=require("chalk"),inquirer=require("inquirer"),adbCommander=require("adb-commander"),{launchServer:launchServer}=require("@aiot-toolkit/server"),{compile:compile}=require("./compile"),{colorconsole:colorconsole}=require("@aiot-toolkit/shared-utils"),{downloadFile:downloadFile,getQuickappDebuggerUrl:getQuickappDebuggerUrl,getQuickappPreviewUrl:getQuickappPreviewUrl,sendReq:sendReq,getClients:getClients,checkQuickappDir:checkQuickappDir,getCardContent:getCardContent}=require("./utils"),{recordClient:recordClient,clearProjectRecord:clearProjectRecord}=require("@aiot-toolkit/shared-utils/lib/record-client"),{clientRecordPath:clientRecordPath}=require("@aiot-toolkit/shared-utils/config"),ipRegExp=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,CLIENT_PORT=39517;async function connectDevice(e=""){try{const r="Yes, connect a new wifi device";if(!e){if((await inquirer.prompt([{name:"type",type:"list",message:"(USB devices will automatically connect) Choose whether to connect to a new wifi device, and fill in its IP address later:",choices:[r,"Skip, keep connected device"]}])).type!==r)return Promise.resolve();e=(await inquirer.prompt([{name:"ip",message:'Please enter the IP address of the device under wifi(eg:192.168.1.1),make sure that the computer and the device are under the same wifi。If you need to enter multiple IPs, please separate them with ",":',default:null}])).ip}if(0===e.length)return colorconsole.info("Since no ip address is entered, the connected device will be connected"),Promise.resolve();const o=e.trim().split(","),t=o.filter((e=>!ipRegExp.test(e)));if(!t||!t.length){const e=Array.from(o,(e=>adbCommander.exeCommand(`adb connect ${e}:5555`).then((({result:r,err:o})=>((o||r.indexOf("failed")>=0)&&(colorconsole.error(`wifi connection ip: The device with ip of "${e}" failed`),process.exit()),colorconsole.info(`wifi connection ip: The device with ip of "${e}" succeeded`),recordClient(clientRecordPath,{ip:e,port:39517}),Promise.resolve())))));return Promise.all(e).then((()=>(colorconsole.log("All new WIFI devices are connected"),Promise.resolve()))).catch((()=>{process.exit()}))}t.map((e=>{colorconsole.error(`ip: ${e} is invalid IP`)})),process.exit()}catch(e){return Promise.reject(new Error(`Error connecting to the device, error message:${e.message}`))}}async function getConnectDevices(e=!0){try{return adbCommander.deviceList().then((({deviceList:r,err:o})=>{if(o){const e="Error getting connection information of adb device";colorconsole.throw(e,o)}if(r.length>0)return e&&colorconsole.info(`Devices connected via adb: ${chalk.yellow(r.join(", "))}.`),Promise.resolve(r);{const e="No device is currently connected, please check the following preparations in turn:\n 1. Whether the device is started;\n 2. Whether in the same LAN WI-FI;\n 3. Whether the device can be connected to the computer via USB;";colorconsole.throw(e)}}))}catch(e){return Promise.reject(new Error(e.message))}}async function downloadApk(e,r){let o="";const{apkVersion:t}=e;o=r?getQuickappDebuggerUrl(t):getQuickappPreviewUrl(t);const n=path.basename(o),i=path.join(__dirname,"./apk/",n);return fs.existsSync(i)?(colorconsole.log("The installation package has been downloaded, now use the cache file to install"),i):downloadFile(o,n).then((e=>(colorconsole.info(e),i))).catch((e=>{colorconsole.error("Failed to download the installation package",e),process.exit()}))}async function installApk(e,r=[],o,t,n){const{forceInstall:i=!1}=e;try{const e=Array.from(r,(e=>adbCommander.isInstalled(e,t).then((async({isInstalled:r,err:c})=>(c&&colorconsole.error(`Failed to install application "${chalk.yellow(n)}" on "${chalk.yellow(e)}" device, error message:${JSON.stringify(c)} `),!1===r||i?(await adbCommander.uninstall(e,t),colorconsole.log(`Start to install application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}" : `),adbCommander.install(e,o).then((({result:r,err:o})=>o?(colorconsole.error(`Failed to install application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}", please troubleshoot and try again `),Promise.reject(new Error(`Failed to install application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}", please troubleshoot and try again `))):adbCommander.isInstalled(e,t).then((({isInstalled:r,err:o})=>{if(!0===r)return colorconsole.info(`Successfully installed application "${chalk.yellow(n)}" on device "${chalk.yellow(e)}" `),Promise.resolve()}))))):(colorconsole.warn(`Application "${chalk.yellow(n)}" has been installed on device "${chalk.yellow(e)}", so the installation did not continue this time`),Promise.resolve()))))));return Promise.all(e).then((()=>(colorconsole.log("All devices installed"),Promise.resolve()))).catch((()=>{process.exit()}))}catch(e){return Promise.reject(e)}}async function startServer(e){const{address:r}=await launchServer(_objectSpread({clearRecords:!0},e));return await compile("native","dev",!0,e),r}async function installdbg(e,r=!0){try{const{ip:o}=e;r&&await connectDevice(o);const t=await getConnectDevices(r),n=await queryDevice(t,"Install Quickapp debugger"),i=await downloadApk(e,!0);return await installApk(e,n,i,"org.hapjs.debugger","Quickapp debugger"),Promise.resolve("All devices successfully installed the Quickapp debugger")}catch(e){return Promise.reject(new Error(`Failed to install debugger, error message:${e.message}`))}}async function installmkp(e,r=!0){try{const{ip:o}=e;r&&await connectDevice(o);const t=await getConnectDevices(r),n=await queryDevice(t,"Install the Quickapp preview version"),i=await downloadApk(e);return await installApk(e,n,i,"org.hapjs.mockup","Quickapp preview version"),Promise.resolve("All devices successfully installed the Quickapp preview version")}catch(e){return Promise.reject(new Error(`Failed to install the preview version of Quickapp, error message:${e.message}`))}}async function queryDevice(e,r=""){if(!e||0===e.length)return void colorconsole.error("No device is connected yet, please confirm and try again");const o="All connected devices",t=(await inquirer.prompt([{name:"device",type:"list",message:`Please select the device that needs to execute command "${r}":`,choices:[...e,o]}])).device;return t===o?e:[t]}async function startDebugger(e=[],r){colorconsole.info("Starting the debugger for the connected device...");const o=Array.from(e,(e=>adbCommander.exeCommand(`adb -s ${e} shell am start -n "org.hapjs.debugger/.MainActivity" ${r}`).then((({err:r})=>r?(colorconsole.error(`Failed to start "Quickapp Debugger" on device "${chalk.yellow(e)}", please troubleshoot and try again`),Promise.reject(new Error(JSON.stringify(r)))):(colorconsole.info(`Successfully start "Quickapp Debugger" on device "${chalk.yellow(e)}" `),Promise.resolve())))));return Promise.all(o).then((()=>(colorconsole.info("The debuggers of all devices have started up"),Promise.resolve()))).catch((()=>{process.exit()}))}async function runapp(e,r=!0,o=!0){try{e.log&&colorconsole.attach(e.log);const{debugMode:t=!1,cardMode:n=!1}=e;let i="",c="",a="";const s=process.cwd();let l=e.includeStaticResources?"":"src";if(checkQuickappDir(s,l),n){colorconsole.warn('Please enable the "self-start" and "associated start" permissions of the Quickapp debugger and preview engine in the Android system');const e=getCardContent(s);if(e){const r=Object.keys(e);if(r.length>1){const o=await inquirer.prompt([{name:"cardName",type:"list",message:"Please select a card for debugging:",choices:r}]);c=e[o.cardName].path||`/${o.cardName}`}else c=e[r[0]].path||`/${r[0]}`;a+=`-e cardMode true -e cardPath ${c}`}}clearProjectRecord(clientRecordPath),i=await startServer(e),a+=` -e path ${i}`,i||(colorconsole.error("Failed to start local Quickapp service, please troubleshoot and try again"),process.exit()),o&&await connectDevice();const d=await getConnectDevices(r);d&&0!==d.length||(colorconsole.error("No connected devices available!!"),process.exit()),await startDebugger(d,a),setTimeout((async()=>{const e=await getClients();e||(colorconsole.error("No connected devices available!!"),process.exit());for(let r of e){const{sn:e,ip:o}=r;if("127.0.0.1"===o&&e.includes(":5555"))continue;const n=e&&e.length>0?e:o,i=()=>{colorconsole.error(`Error when device "${n}" gets the list of running platforms, request again after 3s delay`),setTimeout((()=>{c()}),3e3)},c=async()=>{let e=await sendReq(r,"/availablePlatforms");e||i(),e=JSON.parse(e);const{availablePlatforms:c}=e;if(c){let e;if(0===c.length)return void colorconsole.error(`Quickapp Engine is not installed on device ${o}`);if(1===c.length)e=c[0].pkg;else if(c.length>1){const r=await inquirer.prompt([{name:"name",type:"list",message:`Multiple Quickapp engines are detected on device "${n}", please select the operating platform:`,choices:c}]);c.forEach((o=>{o.name===r.name&&(e=o.pkg)}))}"OK"===await sendReq(r,"/platform",{selectedPlatform:e})&&sendReq(r,"/update",{debug:t})}else i()};await c()}}),3e3)}catch(e){return Promise.reject(new Error(`Error running RPK on the device, error message:${e.message}`))}}async function installAndRun(e){try{const r=process.cwd();checkQuickappDir(r),await installdbg(e),await installmkp(e,!1),await runapp(Object.assign({},e,{enableServerWatch:!0}),!1,!1)}catch(e){return Promise.reject(new Error(`One-click debugging error, error message:${e.message}`))}}async function getAvailablePlatform(e){try{const{ip:r,port:o,sn:t}=e;r&&ipRegExp.test(r)||(colorconsole.error("Did not pass in the correct ip address, eg: --ip 127.0.0.1"),process.exit()),o||(colorconsole.error("Did not pass in the correct port address,eg: --port 39517"),process.exit()),t||(colorconsole.error('Did not pass in the correct device serial number,view the serial number of the connected device through the "adb devices" command \n If it is a device connected via wifi, the format is "ip address:5555"'),process.exit());let n={ip:r,port:o};const i=()=>{colorconsole.error("Error when the device gets running platforms,request again after 3s delay"),setTimeout((()=>{c()}),3e3)},c=async()=>{let e=await sendReq(n,"/availablePlatforms");if(e)if(e=JSON.parse(e),e.availablePlatforms){const r=e.availablePlatforms;colorconsole.info(`The Quickapp engine list of device "${t}" is:${r.join(", ")}`)}else i();else i()};adbCommander.exeCommand(`adb -s ${t} shell am start -n "org.hapjs.debugger/.MainActivity"`).then((({err:e})=>{e&&(colorconsole.error("The debugger does not start normally, please check if it is installed"),process.exit()),colorconsole.info(`The debugger successfully runs on device "${chalk.yellow(t)}"`),colorconsole.info(`Device "${t}" is getting the list of fast application engines...`),c()}))}catch(e){colorconsole.error(`Error getting the list of Quickapp engines on the device, error message:${e.message}`)}}async function getAllConnectedDevices(e){try{return adbCommander.deviceList().then((({deviceList:e,err:r})=>{if(!r)return Promise.resolve(e);colorconsole.throw(r)}))}catch(e){return Promise.reject(new Error(`Error getting the array of all connected devices, error message:${e.message}`))}}module.exports={installAndRun:installAndRun,installdbg:installdbg,installmkp:installmkp,runapp:runapp,getAvailablePlatform:getAvailablePlatform,getAllConnectedDevices:getAllConnectedDevices};
2
2
  //# sourceMappingURL=debug.js.map
@@ -1,2 +1,2 @@
1
- "use strict";var _path=_interopRequireDefault(require("path")),_fsExtra=_interopRequireDefault(require("fs-extra")),_glob=_interopRequireDefault(require("glob")),_inquirer=_interopRequireDefault(require("inquirer")),_chalk=_interopRequireDefault(require("chalk")),_sharedUtils=require("@aiot-toolkit/shared-utils"),_template=_interopRequireDefault(require("@aiot-toolkit/dsl-xvm/lib/template")),_template2=_interopRequireDefault(require("@aiot-toolkit/dsl-vue/lib/template")),_utils=require("@aiot-toolkit/compiler/lib/utils");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const allSupportedDeviceArray=["phone","tv","car","watch","tv-h5"],allSupportedDevicesString=allSupportedDeviceArray.join(",");async function generate(e,t){""===e&&(e="HelloWorld");const a=await _inquirer.default.prompt([{type:"input",name:"name",message:"Init your project",default:e}]),r=_path.default.join(process.cwd(),a.name);try{await createProject(a.name,r,t)}catch(a){_sharedUtils.colorconsole.error(a.message),a.message.match(/Please pick a new name/)&&await generate(e,t)}}async function createProject(e,t,a={}){if(_fsExtra.default.existsSync(t))throw new Error(`"${t}" exists! Please pick a new name.`);if(!(0,_sharedUtils.mkdirsSync)(t))throw new Error('failed to created folder "'+t+'"!.');const{dsl:r,deviceType:l,templateType:i,web:o,minaH5:n,minaTv:s}=a;let p="";if(i&&!l)throw new Error("there is no deviceType specified");p=(0,_utils.hyphenedToCamelCase)(`${l}-${i}`);let u=["phone"];if(s&&(u=["tv-quickapp"]),n&&(u=["tv-h5"]),l&&l.length>0){const e=l.split(",");let t=new Set,a=new Set;e.map((e=>{e=e.toLowerCase();allSupportedDeviceArray.includes(e)||a.add(e),t.add(e)})),u=Array.from(t),a.size>0&&(_sharedUtils.colorconsole.warn(`These device types have not been officially supported by Quickapp: "${Array.from(a).join(",")}"`),_sharedUtils.colorconsole.warn(`Now Quickapp officially supports device types: "${allSupportedDevicesString}"`))}let c=null,d=null;if("vue"===r)c=_template2.default.app.demo,d=_template2.default.app.deviceJsonTemplate;else c=o?_template.default.app.webDemo:n?_template.default.app.minaH5Demo:s?_template.default.app.minaTvDemo:p&&_template.default.app[p]?_template.default.app[p]:u.includes("watch")?_template.default.app.velaDemo:_template.default.app.demo,d=_template.default.app.deviceJsonTemplate;const f=_path.default.resolve(__dirname,c);await copyFiles(t,f,{_gitignore:".gitignore"});const _={appName:e,toolkitVersion:require("../../package.json").version};(n?["package.json","manifest.json"]:["src/manifest.json","package.json"]).map((e=>_path.default.join(t,e))).forEach((e=>{let t=_fsExtra.default.readFileSync(e,"utf-8");if(t=(0,_sharedUtils.renderString)(t,_),e.includes("manifest.json")){let e=JSON.parse(t.toString());e.deviceTypeList=u,t=JSON.stringify(e,null,2)}_fsExtra.default.writeFileSync(e,t)})),n||u.map((a=>{const r=`config-${a}.json`,l=_path.default.join(d,r);let i="{}";_fsExtra.default.existsSync(l)&&(i=_fsExtra.default.readFileSync(l,"utf-8")),console.log(`${e}/src/${r} created`),_fsExtra.default.writeFileSync(_path.default.join(t,`src/config-${a}.json`),i)}))}function copyFiles(e,t,a){const r=_path.default.join(t,"**/{*,.*}"),l=_glob.default.sync(r,{nodir:!0,dot:!0}).map((r=>new Promise((l=>{const i=_path.default.relative(t,r),o=_path.default.join(e,a[i]||i);_fsExtra.default.existsSync(o)?l(_chalk.default.yellow(`${(0,_sharedUtils.relateCwd)(o)} already existed.`)):(l(`${(0,_sharedUtils.relateCwd)(o)} created.`),_fsExtra.default.copySync(r,o))}))));return Promise.all(l).then((e=>{console.log(e.join("\n"))}))}module.exports=generate;
1
+ "use strict";var _path=_interopRequireDefault(require("path")),_fsExtra=_interopRequireDefault(require("fs-extra")),_glob=_interopRequireDefault(require("glob")),_inquirer=_interopRequireDefault(require("inquirer")),_chalk=_interopRequireDefault(require("chalk")),_sharedUtils=require("@aiot-toolkit/shared-utils"),_template=_interopRequireDefault(require("@aiot-toolkit/dsl-xvm/lib/template")),_template2=_interopRequireDefault(require("@aiot-toolkit/dsl-vue/lib/template")),_utils=require("@aiot-toolkit/compiler/lib/utils");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const multiDeviceType="xapp",multiDeviceTypeDemo="xappDemo",allSupportedDeviceArray=["phone","tv","car","watch","tv-h5","xapp"],allSupportedDevicesString=allSupportedDeviceArray.join(",");async function generate(e,t){""===e&&(e="HelloWorld");const a=await _inquirer.default.prompt([{type:"input",name:"name",message:"Init your project",default:e}]),i=_path.default.join(process.cwd(),a.name);try{await createProject(a.name,i,t)}catch(a){_sharedUtils.colorconsole.error(a.message),a.message.match(/Please pick a new name/)&&await generate(e,t)}}async function createProject(e,t,a={}){if(_fsExtra.default.existsSync(t))throw new Error(`"${t}" exists! Please pick a new name.`);if(!(0,_sharedUtils.mkdirsSync)(t))throw new Error('failed to created folder "'+t+'"!.');const{dsl:i,deviceType:r,templateType:l,web:o,minaH5:n,minaTv:s}=a;let p="",u=!1;if(l&&!r)throw new Error("there is no deviceType specified");p=(0,_utils.hyphenedToCamelCase)(`${r}-${l}`),u="xappDemo"===p;let c=["phone"];if(s&&(c=["tv-quickapp"]),n&&(c=["tv-h5"]),r&&r.length>0){const e=r.split(",");let t=new Set,a=new Set;e.map((e=>{e=e.toLowerCase();allSupportedDeviceArray.includes(e)||a.add(e),t.add(e)})),c=Array.from(t),a.size>0&&(_sharedUtils.colorconsole.warn(`These device types have not been officially supported by Quickapp: "${Array.from(a).join(",")}"`),_sharedUtils.colorconsole.warn(`Now Quickapp officially supports device types: "${allSupportedDevicesString}"`))}let d=null,f=null;switch(i){case"vue":d=_template2.default.app.demo,f=_template2.default.app.deviceJsonTemplate;break;default:d=o?_template.default.app.webDemo:n?_template.default.app.minaH5Demo:s?_template.default.app.minaTvDemo:p&&_template.default.app[p]?_template.default.app[p]:c.includes("watch")?_template.default.app.velaDemo:_template.default.app.demo,f=_template.default.app.deviceJsonTemplate}const m=_path.default.resolve(__dirname,d);await copyFiles(t,m,{_gitignore:".gitignore"});const _={appName:e,toolkitVersion:require("../../package.json").version};(n?["package.json","manifest.json"]:u?["app/manifest.json","package.json"]:["src/manifest.json","package.json"]).map((e=>_path.default.join(t,e))).forEach((e=>{let t=_fsExtra.default.readFileSync(e,"utf-8");if(t=(0,_sharedUtils.renderString)(t,_),e.includes("manifest.json")&&!u){let e=JSON.parse(t.toString());e.deviceTypeList=c,t=JSON.stringify(e,null,2)}_fsExtra.default.writeFileSync(e,t)})),n||u||c.map((a=>{const i=`config-${a}.json`,r=_path.default.join(f,i);let l="{}";_fsExtra.default.existsSync(r)&&(l=_fsExtra.default.readFileSync(r,"utf-8")),console.log(`${e}/src/${i} created`),_fsExtra.default.writeFileSync(_path.default.join(t,`src/config-${a}.json`),l)}))}function copyFiles(e,t,a){const i=_path.default.join(t,"**/{*,.*}"),r=_glob.default.sync(i,{nodir:!0,dot:!0}).map((i=>new Promise((r=>{const l=_path.default.relative(t,i),o=_path.default.join(e,a[l]||l);_fsExtra.default.existsSync(o)?r(_chalk.default.yellow(`${(0,_sharedUtils.relateCwd)(o)} already existed.`)):(r(`${(0,_sharedUtils.relateCwd)(o)} created.`),_fsExtra.default.copySync(i,o))}))));return Promise.all(r).then((e=>{console.log(e.join("\n"))}))}module.exports=generate;
2
2
  //# sourceMappingURL=init.js.map
@@ -1,2 +1,2 @@
1
- "use strict";var _path=_interopRequireDefault(require("path")),_fsExtra=_interopRequireDefault(require("fs-extra")),_glob=_interopRequireDefault(require("glob")),_chalk=_interopRequireDefault(require("chalk")),_semver=_interopRequireDefault(require("semver")),_inquirer=_interopRequireDefault(require("inquirer")),_sharedUtils=require("@aiot-toolkit/shared-utils"),_utils=require("./utils");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const curDir=process.cwd(),packageInfo=require("../../package.json"),dslModuleXvmDir=_path.default.dirname(require.resolve("@aiot-toolkit/dsl-xvm/package.json")),dslModuleVueDir=_path.default.dirname(require.resolve("@aiot-toolkit/dsl-vue/package.json")),dslModuleHash={xvm:dslModuleXvmDir,vue:dslModuleVueDir};let dslName,dslModuleDir;function checkVersion(){const e={cur:"",toolkit:"",res:0};let t;const o=_path.default.join(curDir,"package.json");return _fsExtra.default.existsSync(o)&&(t=JSON.parse(_fsExtra.default.readFileSync(o).toString()),e.cur=t.subversion&&t.subversion.toolkit||""),""===e.cur&&(e.res=1),e.toolkit=packageInfo.version,""===e.toolkit?(console.log("### App Toolkit ### The current toolkit file is wrong and cannot be upgraded. Please re-install and then upgrade"),e.res=-1,e):(1!==e.res&&(e.res=_semver.default.gt(e.toolkit,e.cur)?1:0),e)}function mergeProps(e,t){if(e)for(const o in t)e[o]||/babel-|^webpack$|^koa/.test(o)||(e[o]=t[o])}const dependencies=["babel-cli","babel-core","babel-eslint","babel-loader","babel-plugin-syntax-jsx","cross-env","css-what","koa","koa-body","koa-router","koa-send","koa-static","socket.io","style-loader","webpack"];function cleanupDependencies(e,t){if(t.force)return e.devDependencies={},Promise.resolve(e);if(!e.devDependencies)return Promise.resolve(e);const o=dependencies.filter((t=>e.devDependencies[t]));if(!o.length)return Promise.resolve(e);let a=Promise.resolve(dependencies);return t.updateDeps||(a=new Promise((e=>{const t=[{type:"confirm",name:"toDelete",message:"The module dependency that has been included in the hap-toolkit is detected, now remove it",default:!0},{type:"checkbox",name:"selectedDeps",message:"The selected modules below will be removed",choices:o.map((e=>({checked:!0,name:e}))),pageSize:o.length,when:function(e){return e.toDelete}}];_inquirer.default.prompt(t).then((t=>{e(t.toDelete?t.selectedDeps:[])}))}))),a.then((t=>(t.forEach((t=>{e.devDependencies[t]=void 0})),e)))}function upgradePackage(e){console.log(_chalk.default.green("升级 package.json"));const t=_path.default.join(curDir,"package.json"),o=require(t),a=require(_path.default.resolve(dslModuleDir,"templates/app/demo/package.json"));return e.force&&(a.devDependencies={}),a.devDependencies["hap-toolkit"]=packageInfo.version,a.subversion&&(a.subversion.toolkit=packageInfo.version),cleanupDependencies(o,e).then((e=>{for(const t in a){const l=a[t];"string"==typeof l&&o[t]?a[t]=e[t]:mergeProps(l,e[t])}_fsExtra.default.writeFileSync(t,JSON.stringify(a,null,2))}))}function copyFiles(e,t){const o=_path.default.join(t,"**/{*,.*}");_glob.default.sync(o).forEach((o=>{const a=_path.default.relative(t,o),l=_path.default.join(e,a);console.log(_chalk.default.green(`file ${(0,_sharedUtils.relateCwd)(l)} copied.`)),_fsExtra.default.copySync(o,l)}))}function upgradeSign(){console.log(_chalk.default.green("Upgrade signature file"));const e=_path.default.join(curDir,"sign/debug");_fsExtra.default.removeSync(e),(0,_sharedUtils.mkdirsSync)(e),copyFiles(e,_path.default.join(dslModuleDir,"templates/app/demo/sign/debug"))}function upgradeEslint(){const e=".eslintrc.json",t=_path.default.join(dslModuleDir,"templates/app/demo",e),o=_path.default.join(curDir,e);_fsExtra.default.copySync(t,o)}function upgradeBabelConfig(){const e="babel.config.js",t=".babelrc",o=_path.default.join(dslModuleDir,"templates/app/demo",e),a=_path.default.join(curDir,t),l=_path.default.join(curDir,e),r=(0,_utils.formatDate)("yyyyMMdd_hhmmss",new Date);if(console.log(_chalk.default.green("The project is upgraded to babel7, and the default configuration uses babel.config.js")),_fsExtra.default.existsSync(a)){const e=_path.default.join(curDir,t+".old."+r);_fsExtra.default.copySync(a,e),_fsExtra.default.removeSync(a),console.log(_chalk.default.yellow(`### App Toolkit ### The backup file of ${t} is saved as: ${(0,_sharedUtils.relateCwd)(e)}`))}if(_fsExtra.default.existsSync(l)){const t=_path.default.join(curDir,_path.default.basename(e,".js")+".old."+r+".js");_fsExtra.default.copySync(l,t),console.log(_chalk.default.yellow(`### App Toolkit ### The backup file of the updated ${e} is saved as: ${(0,_sharedUtils.relateCwd)(t)}`))}_fsExtra.default.existsSync(o)&&(_fsExtra.default.copySync(o,l),console.log(_chalk.default.yellow(`### App Toolkit ### The updated ${e} succeeded!`)))}function savePackage(){const e="package.json",t=_path.default.join(curDir,e),o=(0,_utils.formatDate)("yyyyMMdd_hhmmss",new Date),a=_path.default.join(curDir,_path.default.basename(e,".json")+".old."+o+".json");_fsExtra.default.copySync(t,a),console.log(_chalk.default.yellow(`### App Toolkit ### The updated backup file of ${e} is saved as: ${(0,_sharedUtils.relateCwd)(a)}`))}function updateProject(e){const t=checkVersion();if(e.force)console.log(_chalk.default.yellow(`Force upgrade project( ${t.cur} ----\x3e ${t.toolkit} )(There may be compatibility issues)`)),savePackage();else{if(t.res<0||0===t.res)return void(0===t.res&&console.log("### App Toolkit ### The version is already the latest version"));console.log(_chalk.default.green(`Upgrade project( ${t.cur} ----\x3e ${t.toolkit} )`))}dslName=(0,_sharedUtils.getProjectDslName)(curDir),dslModuleDir=dslModuleHash[dslName],upgradePackage(e).then((()=>{upgradeSign(),upgradeEslint(),upgradeBabelConfig(),console.log(_chalk.default.green("Upgrade complete, Please run npm install to update the dependency package"))}))}module.exports=updateProject;
1
+ "use strict";var _path=_interopRequireDefault(require("path")),_fsExtra=_interopRequireDefault(require("fs-extra")),_glob=_interopRequireDefault(require("glob")),_chalk=_interopRequireDefault(require("chalk")),_semver=_interopRequireDefault(require("semver")),_inquirer=_interopRequireDefault(require("inquirer")),_sharedUtils=require("@aiot-toolkit/shared-utils"),_utils=require("./utils");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const curDir=process.cwd(),packageInfo=require("../../package.json"),dslModuleXvmDir=_path.default.dirname(require.resolve("@aiot-toolkit/dsl-xvm/package.json")),dslModuleVueDir=_path.default.dirname(require.resolve("@aiot-toolkit/dsl-vue/package.json")),dslModuleHash={xvm:dslModuleXvmDir,vue:dslModuleVueDir};let dslName,dslModuleDir;function checkVersion(){const e={cur:"",toolkit:"",res:0};let t;const a=_path.default.join(curDir,"package.json");return _fsExtra.default.existsSync(a)&&(t=JSON.parse(_fsExtra.default.readFileSync(a).toString()),e.cur=t.subversion&&t.subversion.toolkit||""),""===e.cur&&(e.res=1),e.toolkit=packageInfo.version,""===e.toolkit?(console.log("### App Toolkit ### The current toolkit file is wrong and cannot be upgraded. Please re-install and then upgrade"),e.res=-1,e):(1!==e.res&&(e.res=_semver.default.gt(e.toolkit,e.cur)?1:0),e)}function mergeProps(e,t){if(e)for(const a in t)e[a]||/babel-|^webpack$|^koa/.test(a)||(e[a]=t[a])}const dependencies=["babel-cli","babel-core","babel-eslint","babel-loader","babel-plugin-syntax-jsx","cross-env","css-what","koa","koa-body","koa-router","koa-send","koa-static","socket.io","style-loader","webpack"];function cleanupDependencies(e,t){if(t.force)return e.devDependencies={},Promise.resolve(e);if(!e.devDependencies)return Promise.resolve(e);const a=dependencies.filter((t=>e.devDependencies[t]));if(!a.length)return Promise.resolve(e);let o=Promise.resolve(dependencies);return t.updateDeps||(o=new Promise((e=>{const t=[{type:"confirm",name:"toDelete",message:"The module dependency that has been included in the hap-toolkit is detected, now remove it",default:!0},{type:"checkbox",name:"selectedDeps",message:"The selected modules below will be removed",choices:a.map((e=>({checked:!0,name:e}))),pageSize:a.length,when:function(e){return e.toDelete}}];_inquirer.default.prompt(t).then((t=>{e(t.toDelete?t.selectedDeps:[])}))}))),o.then((t=>(t.forEach((t=>{e.devDependencies[t]=void 0})),e)))}function upgradePackage(e){console.log(_chalk.default.green("升级 package.json"));const t=_path.default.join(curDir,"package.json"),a=require(t),o=require(_path.default.resolve(dslModuleDir,"templates/app/demo/package.json"));return e.force&&(o.devDependencies={}),o.devDependencies["hap-toolkit"]=packageInfo.version,o.subversion&&(o.subversion.toolkit=packageInfo.version),cleanupDependencies(a,e).then((e=>{for(const t in o){const l=o[t];"string"==typeof l&&a[t]?o[t]=e[t]:mergeProps(l,e[t])}_fsExtra.default.writeFileSync(t,JSON.stringify(o,null,2))}))}function copyFiles(e,t){const a=_path.default.join(t,"**/{*,.*}");_glob.default.sync(a).forEach((a=>{const o=_path.default.relative(t,a),l=_path.default.join(e,o);console.log(_chalk.default.green(`file ${(0,_sharedUtils.relateCwd)(l)} copied.`)),_fsExtra.default.copySync(a,l)}))}function upgradeSign(){console.log(_chalk.default.green("Upgrade signature file"));const e=_path.default.join(curDir,"sign/debug");_fsExtra.default.removeSync(e),(0,_sharedUtils.mkdirsSync)(e),copyFiles(e,_path.default.join(dslModuleDir,"templates/app/demo/sign/debug"))}function upgradeEslint(){const e=".eslintrc.json",t=_path.default.join(dslModuleDir,"templates/app/demo",e),a=_path.default.join(curDir,e);_fsExtra.default.copySync(t,a)}function upgradeBabelConfig(){const e="babel.config.js",t=".babelrc",a=_path.default.join(dslModuleDir,"templates/app/demo",e),o=_path.default.join(curDir,t),l=_path.default.join(curDir,e),r=(0,_utils.formatDate)("yyyyMMdd_hhmmss",new Date);if(console.log(_chalk.default.green("The project is upgraded to babel7, and the default configuration uses babel.config.js")),_fsExtra.default.existsSync(o)){const e=_path.default.join(curDir,".babelrc.old."+r);_fsExtra.default.copySync(o,e),_fsExtra.default.removeSync(o),console.log(_chalk.default.yellow(`### App Toolkit ### The backup file of .babelrc is saved as: ${(0,_sharedUtils.relateCwd)(e)}`))}if(_fsExtra.default.existsSync(l)){const t=_path.default.join(curDir,_path.default.basename(e,".js")+".old."+r+".js");_fsExtra.default.copySync(l,t),console.log(_chalk.default.yellow(`### App Toolkit ### The backup file of the updated ${e} is saved as: ${(0,_sharedUtils.relateCwd)(t)}`))}_fsExtra.default.existsSync(a)&&(_fsExtra.default.copySync(a,l),console.log(_chalk.default.yellow(`### App Toolkit ### The updated ${e} succeeded!`)))}function savePackage(){const e="package.json",t=_path.default.join(curDir,e),a=(0,_utils.formatDate)("yyyyMMdd_hhmmss",new Date),o=_path.default.join(curDir,_path.default.basename(e,".json")+".old."+a+".json");_fsExtra.default.copySync(t,o),console.log(_chalk.default.yellow(`### App Toolkit ### The updated backup file of ${e} is saved as: ${(0,_sharedUtils.relateCwd)(o)}`))}function updateProject(e){const t=checkVersion();if(e.force)console.log(_chalk.default.yellow(`Force upgrade project( ${t.cur} ----\x3e ${t.toolkit} )(There may be compatibility issues)`)),savePackage();else{if(t.res<0||0===t.res)return void(0===t.res&&console.log("### App Toolkit ### The version is already the latest version"));console.log(_chalk.default.green(`Upgrade project( ${t.cur} ----\x3e ${t.toolkit} )`))}dslName=(0,_sharedUtils.getProjectDslName)(curDir),dslModuleDir=dslModuleHash[dslName],upgradePackage(e).then((()=>{upgradeSign(),upgradeEslint(),upgradeBabelConfig(),console.log(_chalk.default.green("Upgrade complete, Please run npm install to update the dependency package"))}))}module.exports=updateProject;
2
2
  //# sourceMappingURL=update.js.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkQuickappDir=checkQuickappDir,exports.cleanOrCreateDir=cleanOrCreateDir,exports.downloadFile=downloadFile,exports.formatDate=formatDate,exports.getAspectEntries=getAspectEntries,exports.getCardContent=getCardContent,exports.getClients=getClients,exports.getQuickappDebuggerUrl=getQuickappDebuggerUrl,exports.getQuickappPreviewUrl=getQuickappPreviewUrl,exports.sendReq=sendReq,exports.summaryErrors=summaryErrors,exports.summaryWarnings=summaryWarnings;var _fsExtra=_interopRequireDefault(require("fs-extra")),_path=_interopRequireDefault(require("path")),_request=_interopRequireDefault(require("request")),_http=_interopRequireDefault(require("http")),_recordClient=require("@aiot-toolkit/shared-utils/lib/record-client"),_config=require("@aiot-toolkit/shared-utils/config"),_sharedUtils=require("@aiot-toolkit/shared-utils");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const fsExtra=require("fs-extra");function formatDate(e,t){let r,o,s,n,i,a,l=e;return(e.indexOf("yyyy")>=0||e.indexOf("YYYYY")>=0)&&(r=t.getFullYear(),l=l.replace(/[yY]{4}/g,r)),e.indexOf("MM")>=0&&(o=t.getMonth()+1,l=l.replace(/MM/g,String(o).length<2?"0"+o:o)),e.indexOf("dd")>=0&&(s=t.getDate(),l=l.replace(/dd/g,String(s).length<2?"0"+s:s)),(e.indexOf("hh")>=0||e.indexOf("HH")>=0)&&(n=t.getHours(),l=l.replace(/[hH]{2}/g,String(n).length<2?"0"+n:n)),e.indexOf("mm")>=0&&(i=t.getMinutes(),l=l.replace(/mm/g,String(i).length<2?"0"+i:i)),(e.indexOf("ss")>=0||e.indexOf("SS")>=0)&&(a=t.getSeconds(),l=l.replace(/[sS]{2}/g,String(a).length<2?"0"+a:a)),l}function summaryErrors(e){const t=[];return e.compilation.errors.forEach((e=>{const r=e.message,o=/Can't resolve '(sass-loader|less-loader|stylus-loader)'/.exec(r);if("ModuleNotFoundError"===e.name&&o){let t=o[1];"less-loader"===t?t=`less ${t}`:"sass-loader"===t?t=`node-sass ${t}`:"stylus-loader"===t&&(t=`stylus ${t}`),e.message=` Missing dependency: ${t}, Please execute npm install -D ${t} to install the corresponding dependencies `}const s=e.module?e.module.resource:"";t.push(`${s}\r\n${e.message}`)})),t.join("\n\n")}function summaryWarnings(e){return e.compilation.warnings.map((e=>e.message)).join("\n\n")}const quickapp_url="https://statres.quickapp.cn/quickapp/quickapptool/release/platform/";function getQuickappDebuggerUrl(e){let t=e||"v1080";return _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${t}`),`${quickapp_url}quickapp_debugger_${t}.apk`}function getQuickappPreviewUrl(e){let t=e||"v1080";return _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${t}`),`${quickapp_url}quickapp_platform_preview_release_${t}.apk`}function downloadFile(e,t){return _sharedUtils.colorconsole.log(`Start downloading file:${t}, address:${e}`),new Promise((function(r,o){(0,_request.default)(e,(function(s,n,i){if(s||200!==n.statusCode)o(s||new Error(`Download failed, status code:${n.statusCode}`));else{const s=_path.default.join(__dirname,"./apk");_fsExtra.default.ensureDirSync(s);let n=_fsExtra.default.createWriteStream(_path.default.join(s,t));(0,_request.default)(e).pipe(n).on("close",(e=>{e?o(e):r(`Download file ${t} successfully`)}))}}))}))}async function sendReq(e,t,r){return new Promise((o=>{const s=`http://${e.ip}:${e.port}${t}`;let n={host:e.ip,port:e.port,path:t,timeout:3e3};r&&(n=Object.assign({},n,{headers:r}));const i=_http.default.request(n,(e=>{e.on("data",(e=>{_sharedUtils.colorconsole.log(`### App Server ### Request ${s} succeeded`),o(e.toString())}))})).on("error",(e=>{_sharedUtils.colorconsole.error(`### App Server ### Request ${s} error message: ${e.message}`)})).on("timeout",(function(){_sharedUtils.colorconsole.log(`### App Server ### Request ${s} timed out, please try again`),i.abort()}));i.end()}))}async function getClients(){return new Promise((e=>{if(_fsExtra.default.existsSync(_config.clientRecordPath)){const t=(0,_recordClient.getRecords)(_config.clientRecordPath),r=(0,_recordClient.getProjectClients)(t);r.length>0&&e(r)}e(null)}))}function checkQuickappDir(e,t="src"){const r=_path.default.join(e,t,"manifest.json");_fsExtra.default.existsSync(r)||(_sharedUtils.colorconsole.error("Please execute this command under the Quickapp project"),process.exit())}function getCardContent(e){const t=_path.default.join(e,"src","manifest.json"),r=(0,_sharedUtils.readJson)(t).router.widgets||null;return r||_sharedUtils.colorconsole.error("No card configuration in manifest.json"),r}function cleanOrCreateDir(e){try{_fsExtra.default.accessSync(e,_fsExtra.default.constants.F_OK),fsExtra.emptyDirSync(e)}catch(t){_fsExtra.default.mkdirSync(e,{recursive:!0})}}function getAspectEntries(e,t){let r=["app"],o={},s={},n=_fsExtra.default.readdirSync(e,{encoding:"utf8"});const i=_path.default.join(e,"app","manifest.json"),a=t.router.aspects||null,l=Object.keys(a);return t.router||_sharedUtils.colorconsole.error(`Configuration file ${i} error: router is not exsist, please check`),a||_sharedUtils.colorconsole.error(`Configuration file ${i} error: router.aspect is not exist, please check`),l.forEach((e=>{const t=a[e];let l=[];t.forEach((t=>{n.includes(t.path)&&!r.includes(t.path)?r.push(t.path):_sharedUtils.colorconsole.throw(`Configuration file ${i} error: ${t.path} is not exist in root directory`);let a=t.devices?t.devices:["phone"];for(let r=0;r<a.length;r++){let n=[a[r],t.rule?t.rule:""].join(" ");l.includes(n)?_sharedUtils.colorconsole.throw(`Configuration file ${i} error, devices or devices rule: ${n} is repeat in router ${e}`):l.push(n),Object.keys(o).includes(n)?(o[n].push(t.path),s[n][e]=[t]):(o[n]=[t.path],s[n]={[e]:[t]})}}))})),{entries:r,deviceAspects:o,routerObj:s}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatDate=formatDate,exports.summaryErrors=summaryErrors,exports.summaryWarnings=summaryWarnings,exports.getQuickappDebuggerUrl=getQuickappDebuggerUrl,exports.getQuickappPreviewUrl=getQuickappPreviewUrl,exports.downloadFile=downloadFile,exports.sendReq=sendReq,exports.getClients=getClients,exports.checkQuickappDir=checkQuickappDir,exports.getCardContent=getCardContent,exports.cleanOrCreateDir=cleanOrCreateDir,exports.getAspectEntries=getAspectEntries;var _fsExtra=_interopRequireDefault(require("fs-extra")),_path=_interopRequireDefault(require("path")),_request=_interopRequireDefault(require("request")),_http=_interopRequireDefault(require("http")),_recordClient=require("@aiot-toolkit/shared-utils/lib/record-client"),_config=require("@aiot-toolkit/shared-utils/config"),_sharedUtils=require("@aiot-toolkit/shared-utils");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const fsExtra=require("fs-extra");function formatDate(e,t){let r,o,s,n,i,a,l=e;return(e.indexOf("yyyy")>=0||e.indexOf("YYYYY")>=0)&&(r=t.getFullYear(),l=l.replace(/[yY]{4}/g,r)),e.indexOf("MM")>=0&&(o=t.getMonth()+1,l=l.replace(/MM/g,String(o).length<2?"0"+o:o)),e.indexOf("dd")>=0&&(s=t.getDate(),l=l.replace(/dd/g,String(s).length<2?"0"+s:s)),(e.indexOf("hh")>=0||e.indexOf("HH")>=0)&&(n=t.getHours(),l=l.replace(/[hH]{2}/g,String(n).length<2?"0"+n:n)),e.indexOf("mm")>=0&&(i=t.getMinutes(),l=l.replace(/mm/g,String(i).length<2?"0"+i:i)),(e.indexOf("ss")>=0||e.indexOf("SS")>=0)&&(a=t.getSeconds(),l=l.replace(/[sS]{2}/g,String(a).length<2?"0"+a:a)),l}function summaryErrors(e){const t=[];return e.compilation.errors.forEach((e=>{const r=e.message,o=/Can't resolve '(sass-loader|less-loader|stylus-loader)'/.exec(r);if("ModuleNotFoundError"===e.name&&o){let t=o[1];"less-loader"===t?t=`less ${t}`:"sass-loader"===t?t=`node-sass ${t}`:"stylus-loader"===t&&(t=`stylus ${t}`),e.message=` Missing dependency: ${t}, Please execute npm install -D ${t} to install the corresponding dependencies `}const s=e.module?e.module.resource:"";t.push(`${s}\r\n${e.message}`)})),t.join("\n\n")}function summaryWarnings(e){return e.compilation.warnings.map((e=>e.message)).join("\n\n")}const quickapp_url="https://statres.quickapp.cn/quickapp/quickapptool/release/platform/";function getQuickappDebuggerUrl(e){let t=e||"v1080";return _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${t}`),`${quickapp_url}quickapp_debugger_${t}.apk`}function getQuickappPreviewUrl(e){let t=e||"v1080";return _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${t}`),`${quickapp_url}quickapp_platform_preview_release_${t}.apk`}function downloadFile(e,t){return _sharedUtils.colorconsole.log(`Start downloading file:${t}, address:${e}`),new Promise((function(r,o){(0,_request.default)(e,(function(s,n,i){if(s||200!==n.statusCode)o(s||new Error(`Download failed, status code:${n.statusCode}`));else{const s=_path.default.join(__dirname,"./apk");_fsExtra.default.ensureDirSync(s);let n=_fsExtra.default.createWriteStream(_path.default.join(s,t));(0,_request.default)(e).pipe(n).on("close",(e=>{e?o(e):r(`Download file ${t} successfully`)}))}}))}))}async function sendReq(e,t,r){return new Promise((o=>{const s=`http://${e.ip}:${e.port}${t}`;let n={host:e.ip,port:e.port,path:t,timeout:3e3};r&&(n=Object.assign({},n,{headers:r}));const i=_http.default.request(n,(e=>{e.on("data",(e=>{_sharedUtils.colorconsole.log(`### App Server ### Request ${s} succeeded`),o(e.toString())}))})).on("error",(e=>{_sharedUtils.colorconsole.error(`### App Server ### Request ${s} error message: ${e.message}`)})).on("timeout",(function(){_sharedUtils.colorconsole.log(`### App Server ### Request ${s} timed out, please try again`),i.abort()}));i.end()}))}async function getClients(){return new Promise((e=>{if(_fsExtra.default.existsSync(_config.clientRecordPath)){const t=(0,_recordClient.getRecords)(_config.clientRecordPath),r=(0,_recordClient.getProjectClients)(t);r.length>0&&e(r)}e(null)}))}function checkQuickappDir(e,t="src"){const r=_path.default.join(e,t,"manifest.json");_fsExtra.default.existsSync(r)||(_sharedUtils.colorconsole.error("Please execute this command under the Quickapp project"),process.exit())}function getCardContent(e){const t=_path.default.join(e,"src","manifest.json"),r=(0,_sharedUtils.readJson)(t).router.widgets||null;return r||_sharedUtils.colorconsole.error("No card configuration in manifest.json"),r}function cleanOrCreateDir(e){try{_fsExtra.default.accessSync(e,_fsExtra.default.constants.F_OK),fsExtra.emptyDirSync(e)}catch(t){_fsExtra.default.mkdirSync(e,{recursive:!0})}}function getAspectEntries(e,t){let r=["app"],o={},s={},n=_fsExtra.default.readdirSync(e,{encoding:"utf8"});const i=_path.default.join(e,"app","manifest.json"),a=t.router.aspects||null,l=Object.keys(a);return t.router||_sharedUtils.colorconsole.error(`Configuration file ${i} error: router is not exsist, please check`),a||_sharedUtils.colorconsole.error(`Configuration file ${i} error: router.aspect is not exist, please check`),l.forEach((e=>{const t=a[e];let l=[];t.forEach((t=>{n.includes(t.path)&&!r.includes(t.path)?r.push(t.path):_sharedUtils.colorconsole.throw(`Configuration file ${i} error: ${t.path} is not exist in root directory`);let a=t.devices?t.devices:["phone"];for(let r=0;r<a.length;r++){let n=[a[r],t.rule?t.rule:""].join(" ");l.includes(n)?_sharedUtils.colorconsole.throw(`Configuration file ${i} error, devices or devices rule: ${n} is repeat in router ${e}`):l.push(n),Object.keys(o).includes(n)?(o[n].push(t.path),s[n][e]=[t]):(o[n]=[t.path],s[n]={[e]:[t]})}}))})),{entries:r,deviceAspects:o,routerObj:s}}
2
2
  //# sourceMappingURL=utils.js.map
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "aiot-toolkit",
3
- "version": "1.0.18-aspect-beta.7",
3
+ "version": "1.0.18-aspect-beta.9",
4
4
  "description": "A command line toolkit for developing Aiot Quick Apps.",
5
5
  "engines": {
6
6
  "node": ">=8.0.0"
7
7
  },
8
8
  "dependencies": {
9
- "@aiot-toolkit/compiler": "1.0.18-aspect-beta.7",
10
- "@aiot-toolkit/debugger": "1.0.18-aspect-beta.7",
11
- "@aiot-toolkit/dsl-vue": "1.0.18-aspect-beta.7",
12
- "@aiot-toolkit/dsl-xvm": "1.0.18-aspect-beta.7",
13
- "@aiot-toolkit/packager": "1.0.18-aspect-beta.7",
14
- "@aiot-toolkit/server": "1.0.18-aspect-beta.7",
15
- "@aiot-toolkit/shared-utils": "1.0.18-aspect-beta.7",
9
+ "@aiot-toolkit/compiler": "1.0.18-aspect-beta.9",
10
+ "@aiot-toolkit/debugger": "1.0.18-aspect-beta.9",
11
+ "@aiot-toolkit/dsl-vue": "1.0.18-aspect-beta.9",
12
+ "@aiot-toolkit/dsl-xvm": "1.0.18-aspect-beta.9",
13
+ "@aiot-toolkit/packager": "1.0.18-aspect-beta.9",
14
+ "@aiot-toolkit/server": "1.0.18-aspect-beta.9",
15
+ "@aiot-toolkit/shared-utils": "1.0.18-aspect-beta.9",
16
16
  "@babel/core": "^7.9.6",
17
17
  "@babel/plugin-syntax-jsx": "^7.8.3",
18
18
  "@babel/preset-env": "^7.9.6",
@@ -51,5 +51,5 @@
51
51
  "supertest": "^3.3.0",
52
52
  "webpack-cli": "^4.3.0"
53
53
  },
54
- "gitHead": "d23d335a64624598f2b81e16ce5c947fefdc145d"
54
+ "gitHead": "4d8af6974f48ef33ebd9264caea288cd6aef42a2"
55
55
  }