@deveco-test/deveco-cli-common 1.3.10-Test.1 → 1.3.11-Test.3
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.
- package/README.md +741 -31
- package/THIRD-PARTY-LICENSES +46 -0
- package/dist/cli.js +165 -154
- package/dist/internal/plugin-hook-runner.js +1 -0
- package/dist/internal/telemetry-upload-background.js +5 -5
- package/package.json +12 -6
- package/skills/deveco-cli/SKILL.md +102 -18
- package/src/resources/arkts-check.cjs +33 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import g from"path";import{pathToFileURL as l}from"url";function t(n){return new Promise(o=>{let e=process.send;if(!e){o();return}try{e.call(process,n,()=>o())}catch{o()}})}function d(n){let o=n;return{message:n instanceof Error?n.message:String(n),name:o?.name,code:o?.code}}async function f(){let n=process.argv[2];if(!n)throw new Error("missing hook payload");let o=JSON.parse(n),e=g.join(o.pluginDir,"index.js"),a=await import(l(e).href),i=a.plugin??a.default?.plugin;if(!i||typeof i!="object")throw new Error("plugin export not found");let s=i[o.hookName];if(typeof s!="function")throw new Error(`plugin hook ${o.hookName} is not a function`);let u={...o.ctx,log:p=>{t({type:"log",message:String(p)})}};await s(u)}var c=!1;async function r(n){c||(c=!0,await t({type:"error",...d(n)})),process.exit(1)}process.on("uncaughtException",n=>{r(n)});process.on("unhandledRejection",n=>{r(n)});try{await f(),await t({type:"done"}),process.exit(0)}catch(n){await r(n)}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import Vt from"path";import*as
|
|
2
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},E=null;function Ot(n=!1){E&&E.dispose(),E=new j(n)}function F(){return E||Ot(!1),E}var c={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import at from"fs";import Pt from"path";var k=300*1e3,O=3600*1e3,lt=10080*60*1e3,v=8*1024*1024,ct=3600*1e3,st=".pending",Rt=/\.reclaim-\d+-\d+$/;function P(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var It="upload-state.json";function ut(n){return Pt.join(n,It)}function Nt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function U(n){try{let t=at.readFileSync(ut(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return Nt()}}function V(n,t){try{at.writeFileSync(ut(n),JSON.stringify(t),"utf8")}catch{}}function pt(n){let t=U(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),V(n,t))}function ft(n){let t=U(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,V(n,t)}function dt(n){let t=U(n);t.lastRetryAt=Date.now(),V(n,t)}function mt(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function z(n){if(!n.startsWith("telemetry-"))return null;let t=Rt.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(st))return null;let r=e.slice(0,-st.length);return r.endsWith(".txt")?r:null}function gt(n){return z(n)!==null}import $t from"crypto";import R from"fs";import Mt from"path";var Bt="install-id";function jt(n){return Mt.join(n,Bt)}function ht(n){try{let t=R.readFileSync(n,"utf8").trim();return Ut(t)?t:null}catch{return null}}function Ut(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function yt(n){let t=jt(n),e=ht(t);if(e)return e;let r=$t.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=ht(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var
|
|
1
|
+
import Vt from"path";import*as b from"fs";import*as Y from"path";import{homedir as St}from"os";import*as H from"fs";import*as g from"path";function W(n){let t=g.resolve(n),e=[],r=t;for(;;)try{let i=H.realpathSync(r);return e.length===0?i:g.join(i,...e.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=g.dirname(r);if(o===r)return t;e.push(g.basename(r)),r=o}}function N(n){let t=n.trim();return(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1).trim()),t}function K(n){let t=N(n);if(!t)throw new Error("Path must not be empty.");return W(t)}var Et="deveco-cli",J,$=class extends Error{constructor(t){super(t),this.name="CliDataDirError"}};function Tt(){let n=process.env.DEVECO_CLI_DATA_DIR,e=(n===void 0||n===""?"":N(n))||Y.join(St(),".local","share",Et);try{return K(e)}catch(r){throw new $(r instanceof Error?r.message:String(r))}}function X(){if(J!==void 0)return J;let n=Tt();try{if(b.existsSync(n))return b.realpathSync(n)}catch{}return n}import vt from"crypto";import u from"fs";import I from"os";import m from"path";import wt from"https";var G={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var D=class n{static ENDPOINT=G.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(t,e){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:e.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(t,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(t,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(t){try{let e=JSON.parse(t),r=e?.code??e?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(t,e,r,i){let o=new URL(t);return new Promise((s,l)=>{let p=wt.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:e,timeout:i},h=>{let w=[];h.on("data",bt=>w.push(bt)),h.on("end",()=>{s({code:h.statusCode??0,body:Buffer.concat(w).toString("utf8")})})});p.on("timeout",()=>{p.destroy(new Error("request timeout"))}),p.on("error",l),p.write(r),p.end()})}};var q={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},M=class{constructor(t={}){this.config=t}serialize(t){let e=this.transform(t);return this.config.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}toObject(t){return this.transform(t)}transform(t){if(t==null)return t;if(Array.isArray(t))return t.map(o=>this.transform(o));if(typeof t!="object")return t;let e=this.config.namingStrategy??q.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(t)){let l=r[o]??e(o);i[l]=this.transform(s)}return i}},Z=new M({namingStrategy:q.snakeCase,fieldNames:{}});import S from"crypto";import C from"fs";import Dt from"path";var _="aes-256-gcm",Ct=12,_t="deveco-cli-trace-file",Lt="trace-file-secret",tt=32;function Q(n){try{let t=C.readFileSync(n,"utf8").trim();return t&&Buffer.from(t,"base64").length===tt?t:null}catch{return null}}function et(n){let t=Dt.join(n,Lt),e=Q(t);if(e)return B(e);let r=S.randomBytes(tt).toString("base64");try{C.mkdirSync(n,{recursive:!0});try{C.writeFileSync(t,r,{flag:"wx"})}catch{let i=Q(t);if(i)return B(i);C.writeFileSync(t,r)}}catch{}return B(r)}function B(n){return S.createHash("sha256").update(_t).update(n).digest()}function rt(n,t){let e=S.randomBytes(Ct),r=S.createCipheriv(_,t,e),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:_,ciphertext:i.toString("base64"),iv:e.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function nt(n,t){let e;try{e=JSON.parse(n)}catch{return null}if(!Ft(e))return n;try{let r=S.createDecipheriv(_,t,Buffer.from(e.iv,"base64"));return r.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([r.update(Buffer.from(e.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function Ft(n){if(!n||typeof n!="object")return!1;let t=n;return t.version===1&&t.algorithm===_&&typeof t.ciphertext=="string"&&typeof t.iv=="string"&&typeof t.authTag=="string"}import*as a from"fs";import*as A from"path";import*as L from"os";import*as y from"path";import ge from"json5";var ve=64*1024;function it(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??y.join(L.homedir(),"AppData","Local");return y.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?y.join(L.homedir(),"Library","Logs","devecocli-mcp-server"):y.join(L.homedir(),".local","share","devecocli-mcp-server","logs")}var ot="mcp-server.log",At="mcp-server",kt={maxSize:10*1024*1024,maxFiles:4},j=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(t,e){this.rotationOptions={...kt,...e},this.minLevel=t?"debug":"info",t?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=it(),this.currentLogFile=A.join(this.logDir,ot),a.existsSync(this.logDir)||a.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${i}`}getRotatedFileName(t,e){return A.join(this.logDir,`${At}-${t}.log.${e}`)}fileExists(t){try{return a.accessSync(t,a.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let t=a.readdirSync(this.logDir),e=[];for(let i of t)if(i===ot||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=A.join(this.logDir,i),s=a.statSync(o);e.push({name:i,mtime:s.mtime,path:o})}e.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<e.length;i++)try{a.unlinkSync(e[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let t=this.getCurrentDateString(),e=this.getRotatedFileName(t,this.rotationOptions.maxFiles);this.fileExists(e)&&a.unlinkSync(e);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(t,i),s=this.getRotatedFileName(t,i+1);this.fileExists(o)&&a.renameSync(o,s)}let r=this.getRotatedFileName(t,1);a.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let t=a.statSync(this.currentLogFile);this.currentFileSize=t.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=a.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{a.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(t){let e=this.getCurrentDateString();this.currentDate&&this.currentDate!==e&&(this.rotateLog(),this.currentDate=e),this.currentFileSize+=t,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(t,e,...r){if(this.mode==="silent"||n.LEVEL_ORDER[t]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(p=>p instanceof Error?`${p.name}: ${p.message}`:typeof p=="object"?JSON.stringify(p,null,2):String(p)).join(" "),o=i?`${e} ${i}`:e,l=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${t.toUpperCase()}] [pid=${process.pid}] ${o}
|
|
2
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},E=null;function Ot(n=!1){E&&E.dispose(),E=new j(n)}function F(){return E||Ot(!1),E}var c={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import at from"fs";import Pt from"path";var k=300*1e3,O=3600*1e3,lt=10080*60*1e3,v=8*1024*1024,ct=3600*1e3,st=".pending",Rt=/\.reclaim-\d+-\d+$/;function P(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var It="upload-state.json";function ut(n){return Pt.join(n,It)}function Nt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function U(n){try{let t=at.readFileSync(ut(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return Nt()}}function V(n,t){try{at.writeFileSync(ut(n),JSON.stringify(t),"utf8")}catch{}}function pt(n){let t=U(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),V(n,t))}function ft(n){let t=U(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,V(n,t)}function dt(n){let t=U(n);t.lastRetryAt=Date.now(),V(n,t)}function mt(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function z(n){if(!n.startsWith("telemetry-"))return null;let t=Rt.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(st))return null;let r=e.slice(0,-st.length);return r.endsWith(".txt")?r:null}function gt(n){return z(n)!==null}import $t from"crypto";import R from"fs";import Mt from"path";var Bt="install-id";function jt(n){return Mt.join(n,Bt)}function ht(n){try{let t=R.readFileSync(n,"utf8").trim();return Ut(t)?t:null}catch{return null}}function Ut(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function yt(n){let t=jt(n),e=ht(t);if(e)return e;let r=$t.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=ht(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var T=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new D;storageDir="";failedDir="";installId="";disabled=P();traceFileKey=Buffer.alloc(0);sessionId=vt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){c.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=m.join(t,"failed"),this.cliVersion="1.3.11-Test.3",this.nodeVersion=process.version,this.installId=yt(t).replace(/-/g,""),this.traceFileKey=et(t),u.mkdirSync(t,{recursive:!0}),u.mkdirSync(this.failedDir,{recursive:!0}),c.debug(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,c.debug(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,c.debug(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,c.debug(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!e){await this.record(t,0,!0,null);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code);return}let r=e,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(t,s,!0,null),o}catch(o){let s=Date.now()-i,l=this.toErrorCode(o);throw await this.record(t,s,!1,l),o}}async record(t,e,r,i){let o=this.buildTraceEvent(t,e,r,i);try{let s=rt(JSON.stringify(o),this.traceFileKey);await u.promises.appendFile(this.currentFile(),s+`
|
|
3
3
|
`,"utf8"),pt(this.storageDir)}catch{}}buildTraceEvent(t,e,r,i){let o=`${n.EVENT_PREFIX}${t.event}`,s=Z.toObject(t);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:vt.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:e,success:r,error_code:i,event_detail:s}}}toErrorCode(t){return t instanceof Error?t.code??t.name:"UnknownError"}resolveOsArch(){let t=I.arch();return t==="x64"?"amd64":t}resolveOsName(){switch(process.platform){case"win32":{let t=I.release().split(".");return(parseInt(t[t.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return I.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(I.totalmem()/1024)}KB`}formatVersion(t){return t?`${t}_${this.resolveOsSuffix()}`:""}dateString(){let t=new Date,e=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${e}-${r}`}currentFile(){return m.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){c.debug("[telemetry] scheduler not started (telemetry disabled)");return}c.debug(`[telemetry] scheduler started (flush every ${k/1e3}s, retry failed every ${O/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},k)},k),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},O)},O)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),c.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let t=await this.listPendingFiles(),e=!0;for(let r of t)await this.flushFile(r)||(e=!1);return ft(this.storageDir),e}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let t=Date.now(),e;try{e=await u.promises.readdir(this.failedDir)}catch{return!0}let r=e.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>m.join(this.failedDir,o)),i=!0;for(let o of r){let s=m.basename(o),l=mt(s);if(l!==null){if(t-l>lt){try{await u.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||c.warn("[telemetry] retry failed"),dt(this.storageDir),i}async reclaimStalePending(){let t=Date.now();for(let e of[this.storageDir,this.failedDir]){let r;try{r=await u.promises.readdir(e)}catch{continue}for(let i of r)gt(i)&&await this.reclaimOrphan(m.join(e,i),t)}}async reclaimOrphan(t,e){let r;try{let h=await u.promises.stat(t);if(e-h.mtimeMs<ct)return;r=h.size}catch{return}let i=m.dirname(t),o=z(m.basename(t));if(o===null)return;let s=await this.claimOrphan(t,i,o);if(s===null)return;let l=m.join(i,o),p=v-await this.fileSize(l);if(r>p){try{await u.promises.unlink(s)}catch{}c.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${p})`);return}if(await this.mergeOrphanInto(s,l)){c.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}c.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(t,e,r){let i=m.join(e,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await u.promises.rename(t,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(t,e){try{await u.promises.appendFile(e,await u.promises.readFile(t))}catch(r){return c.warn(`[telemetry] merge orphan pending failed: ${t} -> ${e}: ${r instanceof Error?r.message:String(r)}`),!1}try{await u.promises.unlink(t)}catch(r){c.warn(`[telemetry] merged but failed to remove orphan pending: ${t}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(t){try{return(await u.promises.stat(t)).size}catch{return 0}}async touch(t){let e=new Date;try{await u.promises.utimes(t,e,e)}catch{}}runExclusive(t){let e=()=>t(),r=this.flushChain.then(e,e);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let t;try{t=await u.promises.readdir(this.storageDir)}catch{return[]}return t.filter(e=>e.startsWith("telemetry-")&&e.endsWith(".txt")).map(e=>m.join(this.storageDir,e)).sort()}async flushFile(t){let e=await this.fileSize(t);if(e>v){c.warn(`[telemetry] ${m.basename(t)} is ${e} bytes (> ${v}), dropped without uploading`);try{await u.promises.unlink(t)}catch{}return!0}let r=t+".pending";try{await u.promises.rename(t,r)}catch{return!1}await this.touch(r);let i;try{i=await u.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
|
|
4
|
-
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await u.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(t,e){let r=[],i=16,o=e;for(;o<t.length&&r.length<n.MAX_BATCH;){let s=nt(t[o],this.traceFileKey);if(s===null){o++;continue}let l=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+l>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=l,o++}return{batch:r,next:o}}async uploadInBatches(t,e){let r=0;for(;r<e.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(e,r);r=s;let l=this.buildPayloadItems(o);if(l.length===0)continue;let p=JSON.stringify(l),h=!1;try{h=await this.uploader.upload(p,this.installId)}catch{}if(!h){c.warn("[telemetry] upload failed");let
|
|
4
|
+
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await u.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(t,e){let r=[],i=16,o=e;for(;o<t.length&&r.length<n.MAX_BATCH;){let s=nt(t[o],this.traceFileKey);if(s===null){o++;continue}let l=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+l>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=l,o++}return{batch:r,next:o}}async uploadInBatches(t,e){let r=0;for(;r<e.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(e,r);r=s;let l=this.buildPayloadItems(o);if(l.length===0)continue;let p=JSON.stringify(l),h=!1;try{h=await this.uploader.upload(p,this.installId)}catch{}if(!h){c.warn("[telemetry] upload failed");let w=e.slice(i).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;return await this.moveToFailed(t,
|
|
6
|
+
`;return await this.moveToFailed(t,w),!1}}try{await u.promises.unlink(t)}catch{}return!0}buildPayloadItems(t){let e=[];for(let r of t)try{let i=JSON.parse(r);e.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return e}async moveToFailed(t,e){let r=m.basename(t,".pending"),i=m.join(this.failedDir,r),o=e.split(`
|
|
7
7
|
`).filter(Boolean),s=v-await this.fileSize(i),l=this.takeNewestWithinBudget(o,s);l.length<o.length&&c.warn(`[telemetry] failed file capped at ${v} bytes, dropped ${o.length-l.length} older events`);try{l.length>0&&await u.promises.appendFile(i,l.join(`
|
|
8
8
|
`)+`
|
|
9
|
-
`,"utf8")}catch{return}try{await u.promises.unlink(t)}catch{}}takeNewestWithinBudget(t,e){if(e<=0)return[];let r=[],i=0;for(let o=t.length-1;o>=0;o--){let s=Buffer.byteLength(t[o],"utf8")+1;if(i+s>e)break;i+=s,r.push(t[o])}return r.reverse(),r}};var x=new
|
|
9
|
+
`,"utf8")}catch{return}try{await u.promises.unlink(t)}catch{}}takeNewestWithinBudget(t,e){if(e<=0)return[];let r=[],i=0;for(let o=t.length-1;o>=0;o--){let s=Buffer.byteLength(t[o],"utf8")+1;if(i+s>e)break;i+=s,r.push(t[o])}return r.reverse(),r}};var x=new T;import{spawn as Ge}from"child_process";import{existsSync as Ze}from"fs";import{dirname as tr,join as er}from"path";import{fileURLToPath as nr}from"url";var zt=Vt.join(X(),"TraceLogData");x.init(zt);(async()=>{try{await x.flush(),await x.retryFailed()}catch(n){c.warn("[telemetry] background upload error:",n),process.exit(1)}})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deveco-test/deveco-cli-common",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.11-Test.3",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"supportedDocsApi": 1,
|
|
6
6
|
"license": "MIT",
|
|
@@ -24,7 +24,9 @@
|
|
|
24
24
|
"prepack": "node ../../scripts/sync-cli-docs.mjs",
|
|
25
25
|
"prepublishOnly": "npm run lint && npm run build"
|
|
26
26
|
},
|
|
27
|
-
"engines": {
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22"
|
|
29
|
+
},
|
|
28
30
|
"os": [
|
|
29
31
|
"darwin",
|
|
30
32
|
"linux",
|
|
@@ -34,9 +36,12 @@
|
|
|
34
36
|
"x64",
|
|
35
37
|
"arm64"
|
|
36
38
|
],
|
|
37
|
-
"keywords": [
|
|
39
|
+
"keywords": [
|
|
40
|
+
"harmonyos",
|
|
41
|
+
"deveco",
|
|
42
|
+
"cli"
|
|
43
|
+
],
|
|
38
44
|
"dependencies": {
|
|
39
|
-
"@deveco-test/deveco-cli-knowledgebase": "1.3.10-Test.1",
|
|
40
45
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
41
46
|
"@xmldom/xmldom": "^0.8.15",
|
|
42
47
|
"adm-zip": "0.6.1",
|
|
@@ -56,9 +61,10 @@
|
|
|
56
61
|
"semver": "^7.8.5",
|
|
57
62
|
"smol-toml": "^1.6.1",
|
|
58
63
|
"socket.io-client": "^4.7.5",
|
|
59
|
-
"ui-verification-mcp": "0.0.
|
|
64
|
+
"ui-verification-mcp": "0.0.20",
|
|
60
65
|
"xpath": "^0.0.35",
|
|
61
|
-
"zod": "^4.4.3"
|
|
66
|
+
"zod": "^4.4.3",
|
|
67
|
+
"@deveco-test/deveco-cli-knowledgebase": "1.3.11-Test.3"
|
|
62
68
|
},
|
|
63
69
|
"devDependencies": {
|
|
64
70
|
"@types/adm-zip": "^0.5.8",
|
|
@@ -91,17 +91,78 @@ Inspect UI on a connected physical device or running emulator.
|
|
|
91
91
|
### `devecocli docs`
|
|
92
92
|
Search HarmonyOS developer documentation in the local HarmonyOS Knowledge Base — returns articles with examples and guidance on HarmonyOS APIs, ArkTS, and libraries. Typical use cases: finding API migration guides, examples for HarmonyOS APIs/ArkTS, up-to-date API references, and best practices for HarmonyOS development.
|
|
93
93
|
- `search <keywords...>`: Match any keyword. Opts: `--catalog <name>`, `--format <default|json>`, `--limit <n>`.
|
|
94
|
-
- `read <documentId>`: Read full content by ID (e.g. `devecocli docs read
|
|
94
|
+
- `read <documentId>`: Read full content by ID (e.g. `devecocli docs read guides/harmonyos-guides/指南/系统/网络/网络`).
|
|
95
95
|
- `catalog`: List available catalogs.
|
|
96
96
|
- `update`: Update docs to the latest compatible version — downloads, sha512-verifies, and installs the docs-data package with atomic version switching; falls back to the bundled baseline if missing/corrupted. Opts: `--force`, `--check`.
|
|
97
97
|
|
|
98
98
|
Always use this tool to get the most up-to-date information about HarmonyOS concepts.
|
|
99
99
|
|
|
100
100
|
### `devecocli device`
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
101
|
+
Manage connected devices — device info, app management, system control, screen, files, clipboard, fonts, view mode, location mock, network simulation, and media playback. All subcommands accept `--device <name|serial>` (Req on multi-device hosts).
|
|
102
|
+
|
|
103
|
+
| Subcommand | Description | Key Options |
|
|
104
|
+
|---|---|---|
|
|
105
|
+
| `list` | Show active real devices and running emulators | `--format table\|json` (default: `table`) |
|
|
106
|
+
| `view` | Detailed device info | `-t <name\|serial>` (Req on multi-device), `--format table\|json` (default: `table`) |
|
|
107
|
+
| `sqlite3 <db-path>` | Run `sqlite3` on a device; all args after `db-path` forwarded as-is | Maps to `hdc -t <serial> shell sqlite3 <db-path> [args...]` |
|
|
108
|
+
| `app install [files...]` | Install hap/hsp packages | `--replace` (overwrite), `--shared <path>` (HSP libs, repeatable), `--wait <seconds>` (180–600), `--user <userId>` |
|
|
109
|
+
| `app uninstall` | Uninstall app by bundle name | `--bundle <name>` |
|
|
110
|
+
| `app list` | List installed apps | `--format default\|json` |
|
|
111
|
+
| `app info <bundleName>` | Show app details | `--format default\|json` |
|
|
112
|
+
| `app foreground` | Show current foreground app | `--format default\|json` |
|
|
113
|
+
| `app start` | Launch app ability | `--bundle <name>`, `--ability <name>`, `--action <action>`, `--uri <uri>` |
|
|
114
|
+
| `app stop` | Force-stop app | `--bundle <name>` |
|
|
115
|
+
| `app cleardata` | Clear app data | `--bundle <name>` |
|
|
116
|
+
| `app clearcache` | Clear app cache | `--bundle <name>` |
|
|
117
|
+
| `wake` | Wake screen | — |
|
|
118
|
+
| `sleep` | Suspend screen | — |
|
|
119
|
+
| `status` | Show screen state (AWAKE/SLEEP) | — |
|
|
120
|
+
| `unlock` | Wake + swipe-up to unlock (phone/tablet only, not 2in1) | — |
|
|
121
|
+
| `open-control-center` | Swipe to open control center (phone/tablet only) | — |
|
|
122
|
+
| `open-notification-center` | Swipe to open notification center (phone/tablet only) | — |
|
|
123
|
+
| `time [datetime]` | Get (no arg) or set system time | `[datetime]` positional arg |
|
|
124
|
+
| `timezone [timezone]` | Get (no arg) or set system timezone | `[timezone]` positional arg |
|
|
125
|
+
| `screen size` | Get screen resolution | `--format default\|json` (json: `{width, height}`) |
|
|
126
|
+
| `screen rotation` | Get current screen rotation | — |
|
|
127
|
+
| `screen rotate <angle>` | Set screen rotation angle | `<angle>`: `0\|90\|180\|270` |
|
|
128
|
+
| `screen rotation-lock <state>` | Lock/unlock auto-rotate | `<state>`: `on\|off` |
|
|
129
|
+
| `screen sleeptime <ms>` | Set screen-off timeout | `<ms>`: timeout in ms; `-1` = never sleep |
|
|
130
|
+
| `file send <local> <remote>` | Push file to device | `<local>` source path, `<remote>` dest path |
|
|
131
|
+
| `file recv <remote> <local>` | Pull file from device | `<remote>` source path, `<local>` dest path |
|
|
132
|
+
| `file exist <path>` | Check if file exists on device | `<path>` on-device file path |
|
|
133
|
+
| `file delete <path>` | Delete file on device | `<path>` on-device file path |
|
|
134
|
+
| `clipboard read` | Read clipboard text | — |
|
|
135
|
+
| `clipboard write <text>` | Write text to clipboard | `<text>` positional arg |
|
|
136
|
+
| `clipboard clear` | Clear clipboard | — |
|
|
137
|
+
| `font info <fontpath>` | Query font info | `<fontpath>` font file path |
|
|
138
|
+
| `font install <fontpath>` | Install font file | `<fontpath>` font file path |
|
|
139
|
+
| `font uninstall <name>` | Uninstall font by name | `<name>` font name |
|
|
140
|
+
| `viewmode` | Get current dark/light mode | — |
|
|
141
|
+
| `viewmode dark` | Set dark mode | — |
|
|
142
|
+
| `viewmode light` | Set light mode | — |
|
|
143
|
+
| `location set` | Mock location from coordinates | `--latitude <degrees>`, `--longitude <degrees>`, `--altitude <m>`, `--speed <m/s>`, `--direction <degrees>` (0–360), `--interval <seconds>` (1–3600, default 1) |
|
|
144
|
+
| `location set` (gpx) | Mock location from GPX file | `--gpx-file <path>`, `--interval <seconds>` (mutually exclusive with lat/lon mode) |
|
|
145
|
+
| `location enable` | Turn on location mock (also done automatically by `set`) | — |
|
|
146
|
+
| `location disable` | Turn off and restore real location | — |
|
|
147
|
+
| `network-sim start` (preset) | Start preset scenario (1–8) | `--id <n>` |
|
|
148
|
+
| `network-sim start` (custom) | Start custom network scenario | `--name <n>`, `--up-bandwidth <bps>`, `--down-bandwidth <bps>`, `--up-latency <ms>`, `--down-latency <ms>`, `--up-drop <0-1>`, `--down-drop <0-1>` (`--id` and custom options mutually exclusive) |
|
|
149
|
+
| `network-sim stop` | Clear simulation, delete custom scenario, disable netcopilot (idempotent) | — |
|
|
150
|
+
| `network-sim list` | Show preset scenarios | — |
|
|
151
|
+
| `network-sim status` | Report enabled/disabled | — |
|
|
152
|
+
| `playback list` | Show active media sessions (bundle name + session ID) | — |
|
|
153
|
+
| `playback play` | Play media | `--id <sessionID>` or `--bundle <bundleName>` |
|
|
154
|
+
| `playback pause` | Pause media | `--id <sessionID>` or `--bundle <bundleName>` |
|
|
155
|
+
| `playback next` | Next track | `--id <sessionID>` or `--bundle <bundleName>` |
|
|
156
|
+
| `playback previous` | Previous track | `--id <sessionID>` or `--bundle <bundleName>` |
|
|
157
|
+
| `playback forward` | Fast forward (step size app-defined) | `--id <sessionID>` or `--bundle <bundleName>` |
|
|
158
|
+
| `playback rewind` | Rewind (step size app-defined) | `--id <sessionID>` or `--bundle <bundleName>` |
|
|
159
|
+
| `playback seek` | Jump to position | `--position <seconds>`, `--id <sessionID>` or `--bundle <bundleName>` |
|
|
160
|
+
|
|
161
|
+
- `location`: requires system version 7.0+ (testhelper).
|
|
162
|
+
- `network-sim`: requires API 20+ (netcopilot).
|
|
163
|
+
- `playback`: requires system version 6.1+ (ohos-avsession-manager).
|
|
164
|
+
|
|
165
|
+
|
|
105
166
|
|
|
106
167
|
### `devecocli run` `[Outside sandbox]`
|
|
107
168
|
Build, install, and launch. After a successful ability launch (and after a successful `--apply`), runs a **default smoke check**. Success prints `Smoke: PASS`; failures print `Smoke: FAIL_CRASH` or `Smoke: FAIL_BLANK` (crash log path via `crash_log:`, blank screenshot via `screenshot:`) and exit non-zero. Smoke is skipped when there is no ability to launch, and for `--hotreload` / `--hotreload-apply`.
|
|
@@ -113,9 +174,9 @@ Build, install, and launch. After a successful ability launch (and after a succe
|
|
|
113
174
|
- `--skip-build`: Deploy existing artifacts.
|
|
114
175
|
- `--apply <fileName>`: **Fast incremental deploy** — rebuilds only changed files into a signed hqf, installs via `bm quickfix -a -f -o`, then restarts the app. Much faster than a full `devecocli run` for iterating on code changes. Modules are auto-detected from the file paths in `<fileName>` (no `--module` needed).
|
|
115
176
|
- `<fileName>`: a plain file name (no path separators) under the project's `.hvigor/` directory; the caller writes the changed-file list there. File name is sanitized to prevent path traversal. Content: list of **source file paths changed this round** (one per line, relative to project root or absolute; `#` comments and blank lines ignored; typically `.ets`/`.ts`/`.cpp`/resource files). The changeFileList is **incrementally merged** — only list files changed since the last apply; previously listed files are retained automatically.
|
|
116
|
-
- **Prereq**: DevEco Studio ≥6.1.1 (hvigor `assembleDevHqf` support; below is rejected with an upgrade hint); run `devecocli run` once first (full build + deploy — `--apply` reuses its build intermediates and generates its own short-lived `buildConfig.json` per apply).
|
|
177
|
+
- **Prereq**: DevEco Studio ≥6.1.1 (hvigor `assembleDevHqf` support; below is rejected with an upgrade hint); run `devecocli run` once first (full build + deploy — `--apply` reuses its build intermediates and generates its own short-lived `buildConfig.json` per apply). Normal `run`/`build` clears the symbol table required by cold-reload ArkTS patches; the first `--apply` with ArkTS changes after a normal build automatically runs a full `assembleHap`/`assembleHsp` bootstrap (by module type) to regenerate it (may take tens of seconds on a cold cache; resource-only applies skip this). Consecutive applies without an intervening normal build reuse the symbol table and are fast.
|
|
117
178
|
- **Do not mix with an active `--hotreload` watch session**: both drive patch builds over the same per-module `buildConfig.json`; stop the session (`--hotreload stop`) first.
|
|
118
|
-
- **If changes don't take effect**: on any apply failure, fall back to a full `devecocli run`.
|
|
179
|
+
- **If changes don't take effect**: on any apply failure, fall back to a full `devecocli run`. Note: the bootstrap rebuild produces a hap containing `ets/symbolMap.map` (hot-reload compilation side effect); this is harmless for `--apply` (only the hqf is installed, not the hap) and the next normal `run`/`build` cleans it — a later `run --skip-build` would deploy that regenerated hap as-is.
|
|
119
180
|
*Ex*: `devecocli run` → edit code → write `.hvigor/changes.txt` → `devecocli run --apply changes.txt`
|
|
120
181
|
- `--hotreload [action]`: **Hot-reload watch session** — must be started as a **background process** (the process holds a persistent socket to the hvigor daemon). It builds the hap in hot-reload mode (`hotReload=true debuggable=true`), deploys+launches the app, then the process itself connects a socket to the daemon and sends `CommonBuild assembleHap --hot-reload-build --watch`, **staying connected** so the daemon's watch worker (rollup watch) stays alive for `--hotreload-apply` to reuse. The process stays alive (onBuildOutput streams to its stdout). **Must be stopped (kill the background process) when the hot-reload debug session ends** — otherwise the watch worker/daemon leaks. `--hotreload stop` additionally stops the hvigor daemon.
|
|
121
182
|
- **Usage**: start `devecocli run --module <m> --hotreload` as a background process; wait for the `.hotreload-mode` marker (or "watch session active" on its stdout) = ready; then run `devecocli run --module <m> --hotreload-apply <file>` (foreground). When done: kill the background process + `devecocli run --hotreload stop`.
|
|
@@ -171,7 +232,7 @@ Supported operations include tap, double-tap, swipe, long press, key input, mous
|
|
|
171
232
|
- `--no-fresh-start` — Skip relaunching the app before verification; omit to relaunch by default.
|
|
172
233
|
- `--device <name|serial>` — device name (substring) or serial; auto-selected on single-device hosts, **required on multi-device hosts**. Quote names with spaces (e.g. `--device "Mate 70 Pro"`).
|
|
173
234
|
|
|
174
|
-
Output JSON contains `success`, `reason` (failure cause), `successPart`, `failPart`, and `id` (unique task ID for log and screenshot retrieval).
|
|
235
|
+
Output JSON contains `success`, `reason` (failure cause), `successPart`, `failPart`, `failType`, and `id` (unique task ID for log and screenshot retrieval). `failType` is `''` when verification passed. Otherwise it is `verification_failed` (a step did not meet its expectation), `unsupported` (a required action is outside the tool, including sound, haptics, and acting on a moving target), `invalid_plan` (the plan is not a valid test, or this device cannot run it), `execution_error` (the run stopped before a conclusion), or `inconclusive` (the evidence cannot separate an app failure from a tool limit, including the round limit).
|
|
175
236
|
|
|
176
237
|
Each UI verification run is limited to 10 minutes.
|
|
177
238
|
|
|
@@ -216,18 +277,31 @@ Inspect UI on a connected device. All subcommands accept `--device <name|serial>
|
|
|
216
277
|
| `window list` | List active windows | `--format default\|json`, `--all` (include system windows) |
|
|
217
278
|
| `screenshot` | Capture a screenshot of the device screen | `--display <displayId>`, required `--path <path>` (existing directory or PNG file path; relative paths supported; writable destination; no overwrite) |
|
|
218
279
|
| `screenrecord` | Record the screen to an MP4 file (physical devices only; emulators are rejected) | interactive by default, or `start` / `stop` / `status`; required `--path <dir|file.mp4>` for interactive and `start`; `stop --force` stops a recording not started by this CLI; `status --format table\|json` |
|
|
219
|
-
| `click [x] [y]` | Tap at the specified coordinates or node | `--id <id>` (auto-resolves to center), `--window <windowId>` (used with `--id`) |
|
|
220
|
-
| `doubleclick [x] [y]` | Double-tap at the specified coordinates or node | `--id <id>`, `--window <windowId>` |
|
|
221
|
-
| `longclick [x] [y]` | Long-press at the specified coordinates or node | `--id <id>`, `--window <windowId>` |
|
|
222
|
-
| `swipe <x1> <y1> <x2> <y2>` | Swipe from one point to another (
|
|
280
|
+
| `click [x] [y]` | Tap at the specified coordinates or node | `--id <id>` (auto-resolves to center), `--selector <expr>`, `--window <windowId>` (used with `--id` or `--selector`) |
|
|
281
|
+
| `doubleclick [x] [y]` | Double-tap at the specified coordinates or node | `--id <id>`, `--selector <expr>`, `--window <windowId>` |
|
|
282
|
+
| `longclick [x] [y]` | Long-press at the specified coordinates or node | `--id <id>`, `--selector <expr>`, `--duration <ms>` (500–60000, default 1000), `--window <windowId>` |
|
|
283
|
+
| `swipe <x1> <y1> <x2> <y2>` | Swipe from one point to another (coordinates or element mode) | `--start <expr> --end <expr>` (element mode; both required together), `--speed <n>` (200–40000, px/s) |
|
|
223
284
|
| `fling <x1> <y1> <x2> <y2>` | Fling from one point to another | `--speed <n>` (200–40000, px/s) |
|
|
224
|
-
| `drag <x1> <y1> <x2> <y2>` | Drag from one point to another | `--speed <n>` (200–40000, px/s) |
|
|
285
|
+
| `drag <x1> <y1> <x2> <y2>` | Drag from one point to another (coordinates or element mode) | `--start <expr> --end <expr>` (element mode; both required together), `--speed <n>` (200–40000, px/s) |
|
|
225
286
|
| `dircfling <direction>` | Quick directional fling (system default speed, ideal for scrolling) | `direction`: `up`, `down`, `left`, `right` |
|
|
226
|
-
| `text <text> [x] [y]` | Input text at a target location or the currently focused field | `--id <id>` (auto-resolves to center), `--window <windowId>` (used with `--id`) |
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
287
|
+
| `text <text> [x] [y]` | Input text at a target location or the currently focused field | `--id <id>` (auto-resolves to center), `--selector <expr>`, `--window <windowId>` (used with `--id` or `--selector`) |
|
|
288
|
+
| `cleartext` | Clear text via Ctrl+A + Del (optionally click target element first) | `--selector <expr>` (click before clearing; default: focused field), `--window <windowId>` |
|
|
289
|
+
| `scrolltostart` | Scroll a scrollable container to the start (top) | `--selector <expr>` (default: first scrollable element), `--speed <n>` (200–40000, default 1500), `--timeout <ms>` (1–3600000, default 60000) |
|
|
290
|
+
| `scrolltoend` | Scroll a scrollable container to the end (bottom) | `--selector <expr>` (default: first scrollable element), `--speed <n>` (200–40000, default 1500), `--timeout <ms>` (1–3600000, default 60000) |
|
|
291
|
+
| `scrollsearch <selector>` | Scroll within a container and search for a target element | `--scroll-selector <expr>` (default: first scrollable element), `--vertical <true\|false>` (default true), `--offset <n>` (≥0, default 80), `--timeout <ms>` (1–3600000, default 60000) |
|
|
292
|
+
| `pinch <scale> [x] [y]` | Pinch (zoom) at an element or coordinates | `--selector <expr>`, `--area-radius <n>` (integer ≥50; default: 300 for coords, 90% of area for element/screen), `--speed <n>` (600–3000, default 600), `--window <windowId>` |
|
|
293
|
+
| `rotate <angle> [x] [y]` | Two-finger rotation at an element or coordinates | `--direction <cw\|ccw>` (default cw), `--selector <expr>`, `--radius <n>` (50–500, default 300), `--speed <n>` (200–40000, default 1500), `--window <windowId>` (used with `--selector`) |
|
|
294
|
+
| `press_key <key1> [key2] [key3]` | Press hardware/system key(s), up to 3 for combos | keys: string name (`back`/`enter`/`ctrl_left`) or numeric keycode |
|
|
295
|
+
| `find [selector]` | Find UI element(s) by selector DSL, XPath, or base64 — polls until match or timeout | `--device`, `--window <windowId>`, `--all` (return all matches), `--timeout <ms>` (default 3000, max 360000), `--format default\|json` |
|
|
296
|
+
| `wait [timeoutMs]` | Wait for element to appear/disappear, or pure sleep if no selector | `--device`, `--window <windowId>`, `--disappear` (wait for element to disappear; requires selector); `<selector>` as positional arg triggers element wait mode |
|
|
297
|
+
|
|
298
|
+
- **Coordinates vs `--id`/`--selector`**: Mutually exclusive. Provide either `x y`, `--id <id>`, or `--selector <expr>`. For `text`, if none is given, text goes to the currently focused field. For `swipe`/`drag`, use either coordinates or `--start <expr> --end <expr>` (both required together).
|
|
299
|
+
- **`--window`**: Default is focused window. May be used with `--id`, `--selector`, or coordinate mode.
|
|
300
|
+
- **Selector DSL**: `key op value` clauses, `,`-separated for AND, `[n]` for index. Operators: `=` (exact), `*=` (contains), `^=` (prefix), `$=` (suffix), `/=` (regex). Also supports `xpath=` prefix for XPath 1.0 expressions and `base64=` prefix to escape shell/DSL special characters. Duplicate property keys (including `desc`/`description` aliases) are rejected.
|
|
301
|
+
- **`swipe`/`drag` element mode**: `--start <expr> --end <expr>` resolves each selector to bounds center, then performs the swipe/drag. Both must be provided together.
|
|
302
|
+
- **`find`/`wait`**: `find` polls the UI tree every 300ms until a match is found or `--timeout` expires. `wait` without a selector is a pure sleep; with a selector, polls for appearance (default) or disappearance (`--disappear`).
|
|
303
|
+
- **`swipe` vs `dircfling`**: `swipe` requires exact start/end coordinates (or `--start`/`--end`) and supports `--speed`; `dircfling` only needs a direction (`up/down/left/right`) and uses system default speed (ideal for page/list scrolling).
|
|
304
|
+
- **`scrollsearch`**: The target `<selector>` does not support an index (`[n]`); passing one triggers an error.
|
|
231
305
|
- **Text encoding**: Special characters in `text` are Base64-encoded internally to safely pass through device shell.
|
|
232
306
|
- `--format json` pairs well with `jq`.
|
|
233
307
|
- `--mode full`: full layout tree, no filtering.
|
|
@@ -281,6 +355,16 @@ Extracted skills are stored in <CLI data directory>/skills/store/<name> globally
|
|
|
281
355
|
|
|
282
356
|
*Ex*: `devecocli skills add --skill <name> --agent opencode --project ./MyApp`
|
|
283
357
|
|
|
358
|
+
### `devecocli plugin`
|
|
359
|
+
Manage whitelisted npm-packaged AI agent plugins (official registry only; the whitelist `npmPackage` coordinate may carry a `@tag` suffix to select a dist-tag, e.g. `@scope/pkg@cli` — defaults to `latest`).
|
|
360
|
+
- `list [-l|--long]`: List whitelisted plugins and locally downloaded versions in a `Name / Version / Status` table (one row per cached version, ascending; `not installed` when none); `--long` appends `NpmPackage` and `Desc` columns.
|
|
361
|
+
- `install <name> [--agent <a,b…>] [--project <path>] [-f]`: Download the package into the CLI data directory, then run the plugin's `install` hook per target agent (detected agents ∩ plugin `supportedAgents`; a plugin omitting `supportedAgents` defaults to all known agents, while an explicitly empty/unknown list fails contract validation). `--force` runs the previous version's `uninstall` hook first. With an explicit `--agent` plus `--project`, missing target skills dirs (including the `.<agent>` root) are created before hooks run, matching `init --project --agent`.
|
|
362
|
+
- `update <name> [--agent <a,b…>] [--project <path>]`: Fetch the latest version and run the `update` hook (`from`/`to` provided; `from` is the highest pre-download store version — `from === to` means no local version or latest already cached, treat as repair/first install). With an explicit `--agent` plus `--project`, missing target skills dirs (including the `.<agent>` root) are created before hooks run, same as `install`.
|
|
363
|
+
- `uninstall <name> [--agent <a,b…>] [--project <path>]`: Run the `uninstall` hook of the highest loadable local version. Never deletes cached packages (`<dataDir>/plugins/store/<name>/`) or plugin data (`<dataDir>/plugins/data/<name>/`); remove those manually if needed.
|
|
364
|
+
- Hook execution is capped at 120s (override with `DEVECO_CLI_PLUGIN_HOOK_TIMEOUT_MS`).
|
|
365
|
+
|
|
366
|
+
*Ex*: `devecocli plugin install example-plugin --agent opencode --project ./MyApp`
|
|
367
|
+
|
|
284
368
|
### `devecocli check compat` `[Outside sandbox]`
|
|
285
369
|
Scan source code for breaking API changes between two SDK versions. Built on top of DevEco Studio's `arkanalyzer-apiscan` plugin.
|
|
286
370
|
- `versions`: List available target SDK versions. Opts: `--format <default|json>` (default: `default`).
|
|
@@ -2818,6 +2818,21 @@ function diagKey(d) {
|
|
|
2818
2818
|
return `${d.file}|${d.line}|${d.column}|${d.message}`;
|
|
2819
2819
|
}
|
|
2820
2820
|
|
|
2821
|
+
// Order by file, then position, then rule/message. Plain code-unit comparison
|
|
2822
|
+
// rather than localeCompare so the result does not depend on the host locale.
|
|
2823
|
+
function compareStr(a, b) {
|
|
2824
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
function sortDiagnostics(diags) {
|
|
2828
|
+
return diags.slice().sort((a, b) =>
|
|
2829
|
+
compareStr(String(a.file || ''), String(b.file || '')) ||
|
|
2830
|
+
(a.line || 0) - (b.line || 0) ||
|
|
2831
|
+
(a.column || 0) - (b.column || 0) ||
|
|
2832
|
+
compareStr(String(a.rule || ''), String(b.rule || '')) ||
|
|
2833
|
+
compareStr(String(a.message || ''), String(b.message || '')));
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2821
2836
|
// --- Checker run (reusable so we can re-check after applying fixes) ---
|
|
2822
2837
|
|
|
2823
2838
|
// Project-level diagnostics read only immutable config/SDK files (module.json5,
|
|
@@ -3127,8 +3142,10 @@ function mergeIncrementalDiagnostics(firstPass, recheckResult, recheckSet, proje
|
|
|
3127
3142
|
// diagnostics, kept files keep their `after` diagnostics, and project diagnostics
|
|
3128
3143
|
// appear exactly once. Only valid when no reverted file is a cross-file
|
|
3129
3144
|
// propagation source (an export-fix decl file) — the caller checks that first.
|
|
3130
|
-
|
|
3131
|
-
|
|
3145
|
+
// `staleProjectDiags` are first-pass project diagnostic objects superseded by a
|
|
3146
|
+
// recompute; they are filtered out like `projectDiags` but not re-emitted.
|
|
3147
|
+
function spliceRevertedDiagnostics(firstPass, after, reverted, projectDiags, absOf, staleProjectDiags = []) {
|
|
3148
|
+
const projectSet = new Set([...projectDiags, ...staleProjectDiags]);
|
|
3132
3149
|
const kept = after.filter((d) => !projectSet.has(d) && !reverted.has(absOf(d.file)));
|
|
3133
3150
|
const restored = firstPass.filter((d) => !projectSet.has(d) && reverted.has(absOf(d.file)));
|
|
3134
3151
|
return [...kept, ...restored, ...projectDiags];
|
|
@@ -3283,6 +3300,12 @@ function applyAutoFixes(diagnostics, env) {
|
|
|
3283
3300
|
// cached diagnostics CAN go stale after an edit: recompute them before the
|
|
3284
3301
|
// re-check, or a successful flip still reports its original mismatch and the
|
|
3285
3302
|
// fix is never credited.
|
|
3303
|
+
// `diagnostics` still holds the first-pass project diagnostic objects. The merge
|
|
3304
|
+
// and splice below drop project entries by identity, so they need both the old
|
|
3305
|
+
// and the recomputed objects; with only the new ones, every first-pass project
|
|
3306
|
+
// diagnostic on a non-.ets file (module.json5, route_map.json, resource dirs)
|
|
3307
|
+
// survives as "carried over" and is reported twice.
|
|
3308
|
+
const firstPassProjectDiags = env.projectDiagnostics || [];
|
|
3286
3309
|
if (touched && touched.length > 0) {
|
|
3287
3310
|
env.projectDiagnostics = computeProjectDiagnostics(env.files || [], env, env.hasExplicitFiles);
|
|
3288
3311
|
}
|
|
@@ -3320,6 +3343,7 @@ function applyAutoFixes(diagnostics, env) {
|
|
|
3320
3343
|
}
|
|
3321
3344
|
|
|
3322
3345
|
const projectDiags = env.projectDiagnostics || [];
|
|
3346
|
+
const allProjectDiags = [...firstPassProjectDiags, ...projectDiags];
|
|
3323
3347
|
// Per-file error counts before/after to detect regressions.
|
|
3324
3348
|
const errCount = (list, abs) => list.filter(d => d.severity === 'error' && absOf(d.file) === abs).length;
|
|
3325
3349
|
|
|
@@ -3357,7 +3381,7 @@ function applyAutoFixes(diagnostics, env) {
|
|
|
3357
3381
|
}
|
|
3358
3382
|
} else {
|
|
3359
3383
|
// No cross-file propagation among reverted files: splice instead of re-running.
|
|
3360
|
-
recheckResult = spliceRevertedDiagnostics(diagnostics, after, reverted, projectDiags, absOf);
|
|
3384
|
+
recheckResult = spliceRevertedDiagnostics(diagnostics, after, reverted, projectDiags, absOf, firstPassProjectDiags);
|
|
3361
3385
|
}
|
|
3362
3386
|
|
|
3363
3387
|
// Only files still holding a fixer edit may lose diagnostics; a reverted file
|
|
@@ -3369,7 +3393,7 @@ function applyAutoFixes(diagnostics, env) {
|
|
|
3369
3393
|
...(touched || []).filter((t) => !reverted.has(t.abs)).map((t) => t.abs),
|
|
3370
3394
|
...exportImporters,
|
|
3371
3395
|
]);
|
|
3372
|
-
const merged = mergeIncrementalDiagnostics(diagnostics, recheckResult, recheckSet,
|
|
3396
|
+
const merged = mergeIncrementalDiagnostics(diagnostics, recheckResult, recheckSet, allProjectDiags, absOf);
|
|
3373
3397
|
const finalDiagnostics = restoreDroppedDiagnostics(diagnostics, merged, writtenFiles, absOf);
|
|
3374
3398
|
|
|
3375
3399
|
// Built from the guarded view: a restored diagnostic must not read as fixed.
|
|
@@ -3503,6 +3527,11 @@ function runCheck(args) {
|
|
|
3503
3527
|
checkerDiagCount = Math.max(checkerDiagCount, filtered.filter((d) => !afterProjectSet.has(d)).length);
|
|
3504
3528
|
}
|
|
3505
3529
|
|
|
3530
|
+
// The checker, the project rules and the post-fix merge each emit in their own
|
|
3531
|
+
// order (file walk order is filesystem-dependent), so sort once here to make
|
|
3532
|
+
// the output stable across platforms and runs.
|
|
3533
|
+
filtered = sortDiagnostics(filtered);
|
|
3534
|
+
|
|
3506
3535
|
const errorCount = filtered.filter(d => d.severity === 'error').length;
|
|
3507
3536
|
const warnCount = filtered.filter(d => d.severity === 'warning').length;
|
|
3508
3537
|
|