@deveco-test/deveco-cli-common 1.3.11-Test.4 → 1.3.11-Test.5
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 +64 -0
- package/THIRD-PARTY-LICENSES +3 -3
- package/dist/cli.js +240 -199
- package/dist/internal/telemetry-upload-background.js +44 -7
- package/package.json +2 -3
- package/skills/deveco-cli/SKILL.md +30 -0
- package/skills/index.json +1 -1
|
@@ -1,9 +1,46 @@
|
|
|
1
|
-
import
|
|
2
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let
|
|
3
|
-
|
|
4
|
-
`)
|
|
1
|
+
import _r from"path";import*as x from"fs";import*as ve from"path";import{homedir as ct}from"os";import*as me from"fs";import*as v from"path";function ge(r){let e=v.resolve(r),t=[],n=e;for(;;)try{let i=me.realpathSync(n);return t.length===0?i:v.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=v.dirname(n);if(o===n)return e;t.push(v.basename(n)),n=o}}function z(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function he(r){let e=z(r);if(!e)throw new Error("Path must not be empty.");return ge(e)}var lt="deveco-cli",ye,q=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function ut(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":z(r))||ve.join(ct(),".local","share",lt);try{return he(t)}catch(n){throw new q(n instanceof Error?n.message:String(n))}}function A(){if(ye!==void 0)return ye;let r=ut();try{if(x.existsSync(r))return x.realpathSync(r)}catch{}return r}import rt from"crypto";import m from"fs";import j from"os";import y from"path";import dt from"https";var Ee={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var P=class r{static ENDPOINT=Ee.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),n=t?.code??t?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(e,t,n,i){let o=new URL(e);return new Promise((s,a)=>{let c=dt.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},g=>{let h=[];g.on("data",S=>h.push(S)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(h).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(n),c.end()})}};var Se={identity:r=>r,camelCase:r=>r,snakeCase:r=>r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},K=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??Se.identity,n=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=n[o]??t(o);i[a]=this.transform(s)}return i}},Te=new K({namingStrategy:Se.snakeCase,fieldNames:{}});import R from"crypto";import O from"fs";import ft from"path";var N="aes-256-gcm",mt=12,gt="deveco-cli-trace-file",ht="trace-file-secret",Ae=32;function Ce(r){try{let e=O.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Ae?e:null}catch{return null}}function be(r){let e=ft.join(r,ht),t=Ce(e);if(t)return X(t);let n=R.randomBytes(Ae).toString("base64");try{O.mkdirSync(r,{recursive:!0});try{O.writeFileSync(e,n,{flag:"wx"})}catch{let i=Ce(e);if(i)return X(i);O.writeFileSync(e,n)}}catch{}return X(n)}function X(r){return R.createHash("sha256").update(gt).update(r).digest()}function we(r,e){let t=R.randomBytes(mt),n=R.createCipheriv(N,e,t),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o={version:1,algorithm:N,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(o)}function xe(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!yt(t))return r;try{let n=R.createDecipheriv(N,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function yt(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===N&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as d from"fs";import*as M from"path";import*as k from"os";import*as T from"path";import rn from"json5";var sn=64*1024;function Re(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??T.join(k.homedir(),"AppData","Local");return T.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?T.join(k.homedir(),"Library","Logs","devecocli-mcp-server"):T.join(k.homedir(),".local","share","devecocli-mcp-server","logs")}var De="mcp-server.log",vt="mcp-server",Et={maxSize:10*1024*1024,maxFiles:4},Y=class r{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(e,t){this.rotationOptions={...Et,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Re(),this.currentLogFile=M.join(this.logDir,De),d.existsSync(this.logDir)||d.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}getRotatedFileName(e,t){return M.join(this.logDir,`${vt}-${e}.log.${t}`)}fileExists(e){try{return d.accessSync(e,d.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=d.readdirSync(this.logDir),t=[];for(let i of e)if(i===De||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=M.join(this.logDir,i),s=d.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<t.length;i++)try{d.unlinkSync(t[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 e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&d.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&d.renameSync(o,s)}let n=this.getRotatedFileName(e,1);d.renameSync(this.currentLogFile,n),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 e=d.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=d.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{d.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${o}
|
|
2
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);d.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{d.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},D=null;function St(r=!1){D&&D.dispose(),D=new Y(r)}function I(){return D||St(!1),D}var f={debug:(r,...e)=>I().debug(r,...e),info:(r,...e)=>I().info(r,...e),warn:(r,...e)=>I().warn(r,...e),error:(r,...e)=>I().error(r,...e)};import _e from"fs";import Tt from"path";var F=300*1e3,B=3600*1e3,Pe=10080*60*1e3,b=8*1024*1024,Oe=3600*1e3,Le=".pending",Ct=/\.reclaim-\d+-\d+$/;function U(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var At="upload-state.json";function Ne(r){return Tt.join(r,At)}function bt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function W(r){try{let e=_e.readFileSync(Ne(r),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return bt()}}function J(r,e){try{_e.writeFileSync(Ne(r),JSON.stringify(e),"utf8")}catch{}}function ke(r){let e=W(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),J(r,e))}function Ie(r){let e=W(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,J(r,e)}function Me(r){let e=W(r);e.lastRetryAt=Date.now(),J(r,e)}function Fe(r){let e=r.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function Z(r){if(!r.startsWith("telemetry-"))return null;let e=Ct.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(Le))return null;let n=t.slice(0,-Le.length);return n.endsWith(".txt")?n:null}function Be(r){return Z(r)!==null}import wt from"crypto";import G from"fs";import xt from"path";var Rt="install-id";function Dt(r){return xt.join(r,Rt)}function Ue(r){try{let e=G.readFileSync(r,"utf8").trim();return Lt(e)?e:null}catch{return null}}function Lt(r){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(r)}function Ge(r){let e=Dt(r),t=Ue(e);if(t)return t;let n=wt.randomUUID();try{G.mkdirSync(r,{recursive:!0});try{G.writeFileSync(e,n,{flag:"wx"})}catch{let i=Ue(e);if(i)return i;G.writeFileSync(e,n)}}catch{}return n}import Gt from"axios";var $e={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Q={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var _t={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Pt(r){try{return new URL(r)}catch{return null}}function $(r){var e=(typeof r=="string"?Pt(r):r)||{},t=e.protocol,n=e.host,i=e.port;if(typeof n!="string"||!n||typeof t!="string"||(t=t.split(":",1)[0],n=n.replace(/:\d*$/,""),i=parseInt(i)||_t[t]||0,!Ot(n,i)))return"";var o=ee(t+"_proxy")||ee("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Ot(r,e){var t=ee("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(n){if(!n)return!0;var i=n.match(/^(.+):(\d+)$/),o=i?i[1]:n,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!r.endsWith(o)):r!==o}):!0}function ee(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}import{spawn as je}from"child_process";import*as C from"fs";import*as ze from"os";import*as H from"path";var qe=6e4;async function Nt(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await He(r,"ProxyServer");if(!e)return null;let t=await He(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function He(r,e){return new Promise(t=>{let n=je("reg.exe",["query",r,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";n.stdout.on("data",o=>{i+=o.toString()}),n.on("error",()=>t(null)),n.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function kt(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function It(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ve(r){let e={},t=0,n="";for(let i of r.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),n=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:n,headers:e}}function Mt(r,e,t,n){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((r.timeoutMs??qe)/1e3)))];return r.method&&r.method!=="GET"&&i.push("-X",r.method),r.data!==void 0&&i.push("--data-binary",r.data),i.push(...Ft(r.headers,r.data!==void 0)),n?(i.push("--dump-header",t),i.push("--output",n)):i.push("--include"),i.push(r.url),i}function Ft(r,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),n=[],i=!1;for(let[o,s]of Object.entries(r??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||n.push("-H",`${o}: ${s}`)}return e&&!i&&n.push("-H","Content-Type: application/json"),n}function Bt(r,e,t){if(t){let g=C.readFileSync(e,"utf8"),h=C.readFileSync(t),S=Ve(g);return{statusCode:S.statusCode,statusText:S.statusText,body:h.toString("base64"),headers:S.headers,bodyBuffer:h}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let i=r.slice(n),o=i.indexOf(`\r
|
|
3
|
+
\r
|
|
4
|
+
`);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=Ve(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function Ke(r){if(process.platform!=="win32")return null;let e=kt()??await Nt();if(!e)return null;let t;r.binary&&(t=C.mkdtempSync(H.join(ze.tmpdir(),"curl-")));let n=t?H.join(t,"header.tmp"):void 0,i=t?H.join(t,"body.tmp"):void 0;try{let o=Mt(r,e,n,i),s=await Ut(o,r.timeoutMs);return!s||s.code!==0?null:Bt(s.stdout,n,i)}catch{return null}finally{t&&C.rmSync(t,{recursive:!0,force:!0})}}function Ut(r,e){let t=It();return new Promise(n=>{let i=je(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??qe);i.stdout.on("data",c=>{o+=c.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),i.on("close",c=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:c??-1,stdout:o})})})}function $t(r){let e=new URL(r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var te=class{client;constructor(){let e={timeout:$e.HTTP_TIMEOUT_MS,headers:{"User-Agent":Q.USER_AGENT,"accept-language":Q.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Gt.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=$(t.url??"");return t.proxy=n?$t(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`,i=new Error(`${t.message}
|
|
5
|
+
${n}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"GET",t)}}async post(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,signal:t?.signal,maxContentLength:t?.maxContentLength,maxBodyLength:t?.maxBodyLength,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw n}}async postAllowFailure(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}async deleteAllowFailure(e,t){try{let n=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{return await this.requestBinary(e,t)}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw n}}async requestBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(n.data);return{statusCode:n.status,statusText:n.statusText??"",buffer:i,body:i.toString("utf8")}}async withCurlFallback(e,t,n,i){let o=await this.tryCurlFallback(e,t,n,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,n,i,o=!1){if(Ht(i)||process.platform!=="win32"||!(e instanceof Error)||!Vt(e))return null;let s,a=t;return n==="GET"?i?.params&&(a=jt(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Ke({url:a,method:n,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},re=new te;function Ht(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function Vt(r){if(r.response?.status===407)return!0;let e=r.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:r.code==="SELF_SIGNED_CERT_IN_CHAIN"||r.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||r.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||r.code==="CERT_HAS_EXPIRED"||r.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function jt(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let n=t.toString();if(!n)return r;let i=r.includes("?")?"&":"?";return`${r}${i}${n}`}import{AsyncLocalStorage as zt}from"async_hooks";var qt=new zt;function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;qt.getStore()?console.error(`[DEBUG] ${e}`):console.log(`[DEBUG] ${e}`)}}import Kt from"fs";import Xt from"http";import Yt from"https";import Wt from"path";import Xe from"tls";import oe from"crypto";import{URL as Jt}from"url";import{yellow as Zt}from"colorette";var Qt=`-----BEGIN CERTIFICATE-----
|
|
6
|
+
MIIF/TCCA+WgAwIBAgIIIQV1CU5bvEMwDQYJKoZIhvcNAQELBQAwUDELMAkGA1UE
|
|
7
|
+
BhMCQ04xDzANBgNVBAoMBkh1YXdlaTETMBEGA1UECwwKSHVhd2VpIENCRzEbMBkG
|
|
8
|
+
A1UEAwwSSHVhd2VpIENCRyBSb290IENBMB4XDTE4MDEzMDA3NDI1OVoXDTM4MDEy
|
|
9
|
+
NTA3NDI1OVowYzELMAkGA1UEBhMCQ04xDzANBgNVBAoMBkh1YXdlaTETMBEGA1UE
|
|
10
|
+
CwwKSHVhd2VpIENCRzEuMCwGA1UEAwwlSHVhd2VpIENCRyBBcHBsaWNhdGlvbiBJ
|
|
11
|
+
bnRlZ3JhdGlvbiBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMCC
|
|
12
|
+
UUvjL5oXThUxFklLXbLNkfHtjs8rlOT3hRE3VmicI7LFJXGMCByB7ORucGDStwIM
|
|
13
|
+
H1ac1pnBsV2dabuQj0WiXbYtRD44IxCN879RJBFry9AV7PypYrxucFqgeqt19PpS
|
|
14
|
+
pSMa4ROBxAyVRq9F6m6HWlBTtlLXvH9yAbPOp+rvaEd5LD7MNsVFOXeMVBoRuhox
|
|
15
|
+
ohrAIB3pzwAjX8fWSoe8Vrz6F3LAIVHE1CzEn0sFUtKIuWVm1l1cGNlsMeUwSMwj
|
|
16
|
+
8PBtTNb9IQaNTsA2qguQgkdPaDda0ENg/FIZ2zHzV9l4k7SrpFvqSde0sEDR9mSf
|
|
17
|
+
IeJ3x5pATJp25X5K1+ZoFZRa7sQHMWA6HOYwfqBXxQmK0pETzjB5zVfXQLnDP0Tq
|
|
18
|
+
K1xcS8X6jJuvkm5F691nu7ypfmZx0RNPTnFZiNOz+Qdzklm1BJHlmNIVbFke6qHU
|
|
19
|
+
HOBX57EAsu2HumkWWyqQ0MaXcpuuLMdU3OZ6vtoSsYevNhN4Ypm2v0Zr3FCSjgnW
|
|
20
|
+
AwU02MNROMCBCRazt4txJ1tEYnmu0Bd5qLJXFWc1zweP52XS6BqeFRYb50M5O/AQ
|
|
21
|
+
I5sXsO10fWN05jezS7jDzqjar7PYNGHuuY6cO5QVo8/t9t/sZ8vHN++Et2BzMKm5
|
|
22
|
+
n11YM6tPJZKKpL0F+ZBa3qgEMFoNxwckvnmT79D5AgMBAAGjgccwgcQwHwYDVR0j
|
|
23
|
+
BBgwFoAUqsTTeUfobiNr7/CpbCJzPXoZaaEwHQYDVR0OBBYEFOHI/wFzBqHgXhMO
|
|
24
|
+
Wqee63/XnhuIMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMGEGA1Ud
|
|
25
|
+
HwRaMFgwVqBUoFKGUGh0dHA6Ly9jcGtpLWNhd2ViLmh1YXdlaS5jb20vY3BraS9z
|
|
26
|
+
ZXJ2bGV0L2NybEZpbGVEb3duLmNybD9jZXJ0eXBlPTEmL3Jvb3RjcmwuY3JsMA0G
|
|
27
|
+
CSqGSIb3DQEBCwUAA4ICAQDPxMXcr1lLbdPHfoncb/QzQpRCQx/EYd7c/7VUKaTX
|
|
28
|
+
V8k4JQ2Z0hHNPPHyjU8MkPg764d+UCcOMkI+PB+zXYKeumQsWks2YRHQQa93bLAO
|
|
29
|
+
NPo0Z8b/r9fjrklCExJT3kA2qThRA4BEfl4WydFS4J2kpdTFxtSbMI77DEllyF8L
|
|
30
|
+
1Nn5mqKCXgZGA3g6vgkxBM/gLaApV9/Mg2QEhTV9WA78+fCbgGVLCYELrvuc+MKl
|
|
31
|
+
jbBnOIoj49tz8VUbjoFJD6AcCBe00qbecDjvx31ERskziWMs+PZ4oNp2zMdsa3Br
|
|
32
|
+
E/vANlEbtTigmTHMora36tEL1JX1cKu+So7I6fykmsPZA3keDHp8treLb4KcbDpL
|
|
33
|
+
cqAu4V8vMqJ8tFU6ilh65HOATWz+g/jEpMPZuiN+qjSYnDFxzts9mWERsSG003S6
|
|
34
|
+
yg9ZnehcA3iRVNPZZ8hSZZH0YKNqxpda/TR6P5qXiHRA6A+MdoBOE4HmuUy3QFV7
|
|
35
|
+
zYl5snR6SmrDfVmtsyz8aMqifx4gsVV2M5/owv8H3bUdOd5RbkKhzOS2Pmep0bbw
|
|
36
|
+
WRFUrWuQ+5ci2LLkZyIt9ffNR8W9gbmZOZZTrwSFRIT1Q433NOzCQNDjKwnekGAx
|
|
37
|
+
8o746tqqZxGCXgy2MaIIqvajhNw9Dr3NBQ8ziWyqaQBk2RrCWh6Q++Sd0b5L3RwH
|
|
38
|
+
rQ==
|
|
39
|
+
-----END CERTIFICATE-----`,er=new oe.X509Certificate(Qt),Ye=[{cert:er}];function tr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new oe.X509Certificate(n)})}catch{}return e}var We=new Set,V;function rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(V&&V.envValue===r)return V.anchors;let e=r?nr(r):[],t=e.length?[...Ye,...e]:Ye;return V={envValue:r,anchors:t},t}function nr(r){try{let e=tr(Kt.readFileSync(r,"utf8"));return e.length===0&&Je(r,"no parseable certificate found"),e}catch(e){return Je(r,e instanceof Error?e.message:String(e)),[]}}function Je(r,e){We.has(r)||(We.add(r),console.warn(Zt(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Wt.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function ir(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let i=n.fingerprint256||n.fingerprint||"";if(!i||t.has(i))break;t.add(i);try{e.push(new oe.X509Certificate(n.raw))}catch{break}let o=n.issuerCertificate??null;if(o===r)break;n=o}return e}function or(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!sr(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=ar(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function sr(r,e){for(let n of e){let i=r.findIndex(o=>o.fingerprint256===n.cert.fingerprint256);if(i>=0&&Ze(r,i))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&Ze(r,r.length-1))return!0}catch{}return!1}function Ze(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function ar(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!lr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function cr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=ir(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):or(n,e,rr())}function lr(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let i of t.split(",")){let o=i.trim();if(!o.startsWith("DNS:"))continue;let s=o.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var ur=8e3,ne=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let n of this.destroyers)try{n()}catch{}this.callback(e,t)}}},ie=class extends Yt.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??ur}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=$(o),a=new ne(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,i,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let i=Xe.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,n),i}createConnectionViaProxy(e,t,n,i,o){let s;try{s=new Jt(t)}catch{o.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),c=this.buildProxyHeaders(s,n,i);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let g=Xt.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:c});o.onDestroy(()=>g.destroy()),g.on("connect",(h,S)=>{if(h.statusCode!==200){S.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}o.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,o,n)}),g.on("error",h=>{o.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,i){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=Xe.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,n,i)}buildProxyHeaders(e,t,n){let i={Host:`${t}:${n}`};if(e.username||e.password){let o=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(o).toString("base64")}`}return i}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let i=cr(e,n);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},se=new ie({keepAlive:!0});var ae=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],w=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var pr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],dr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",fr="devecostudio",mr=8e3;async function ce(r){let e=[],t="";for(let o of pr){let s=await gr(o,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new w("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new w("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function gr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${fr}`;p(()=>`[GRS] POST ${t}`);try{let n=await re.post(t,{headers:{"User-Agent":dr},httpsAgent:se,timeout:mr}),i=re.parseJson(n);return i.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):hr(i.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let i=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${i}`),{outcome:"network",detail:i}}}function hr(r){return ae.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import Qe from"fs";import yr from"path";var vr="com.huawei.devecostudio.region",Er={[vr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},Sr=1440*60*1e3,et=new Set(["CN","HK","MO"]),le=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return et.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=Er,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Tr(this.countryCode);if(e){this.services=e.services,this.resolved=!0,p(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}p(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await ce(this.countryCode);this.services=t,this.resolved=!0,await Cr(this.countryCode,t)}},E=new le;function tt(r){return yr.join(A(),`grs_${r}.json`)}async function Tr(r){try{let e=await Qe.promises.readFile(tt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Sr?null:t}catch{return null}}async function Cr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await Qe.promises.writeFile(tt(r),JSON.stringify(t),"utf8")}catch{}}var L=class r{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 P;storageDir="";failedDir="";installId="";get disabled(){return U()||!E.isCN()}traceFileKey=Buffer.alloc(0);sessionId=rt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.11-Test.5",this.nodeVersion=process.version,this.installId=Ge(e).replace(/-/g,""),this.traceFileKey=be(e),m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0}),f.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return f.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=we(JSON.stringify(o),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
|
|
40
|
+
`,"utf8"),ke(this.storageDir)}catch{}}buildTraceEvent(e,t,n,i){let o=`${r.EVENT_PREFIX}${e.event}`,s=Te.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:rt.randomUUID(),trace_os_version:r.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:t,success:n,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=j.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=j.release().split(".");return(parseInt(e[e.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 j.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(j.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}currentFile(){return y.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.debug("[telemetry] scheduler not started (telemetry disabled)");return}f.debug(`[telemetry] scheduler started (flush every ${F/1e3}s, retry failed every ${B/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},F)},F),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},B)},B)}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),f.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return f.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return Ie(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return f.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await m.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>y.join(this.failedDir,o)),i=!0;for(let o of n){let s=y.basename(o),a=Fe(s);if(a!==null){if(e-a>Pe){try{await m.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||f.warn("[telemetry] retry failed"),Me(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await m.promises.readdir(t)}catch{continue}for(let i of n)Be(i)&&await this.reclaimOrphan(y.join(t,i),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<Oe)return;n=g.size}catch{return}let i=y.dirname(e),o=Z(y.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=y.join(i,o),c=b-await this.fileSize(a);if(n>c){try{await m.promises.unlink(s)}catch{}f.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){f.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}f.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let i=y.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await m.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await m.promises.appendFile(t,await m.promises.readFile(e))}catch(n){return f.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){f.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await m.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await m.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await m.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>y.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>b){f.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${b}), dropped without uploading`);try{await m.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await m.promises.rename(e,n)}catch{return!1}await this.touch(n);let i;try{i=await m.promises.readFile(n,"utf8")}catch{return!1}let o=i.split(`
|
|
41
|
+
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await m.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,o)}collectDecryptBatch(e,t){let n=[],i=16,o=t;for(;o<e.length&&n.length<r.MAX_BATCH;){let s=xe(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&i+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),i+=a,o++}return{batch:n,next:o}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let i=n,{batch:o,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let c=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(c,this.installId)}catch{}if(!g){f.warn("[telemetry] upload failed");let h=t.slice(i).join(`
|
|
5
42
|
`)+`
|
|
6
|
-
`;return await this.moveToFailed(
|
|
7
|
-
`).filter(Boolean),s=
|
|
43
|
+
`;return await this.moveToFailed(e,h),!1}}try{await m.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let i=JSON.parse(n);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=y.basename(e,".pending"),i=y.join(this.failedDir,n),o=t.split(`
|
|
44
|
+
`).filter(Boolean),s=b-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&f.warn(`[telemetry] failed file capped at ${b} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await m.promises.appendFile(i,a.join(`
|
|
8
45
|
`)+`
|
|
9
|
-
`,"utf8")}catch{return}try{await
|
|
46
|
+
`,"utf8")}catch{return}try{await m.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let n=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,n.push(e[o])}return n.reverse(),n}};var _=new L;import{spawn as eo}from"child_process";import{existsSync as ro}from"fs";import{dirname as io,join as oo}from"path";import{fileURLToPath as ao}from"url";var Ar=new Set(["C","POSIX"]);function ue(){let r=br();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),Ar.has(r))return p("[region] locale=C/POSIX\uFF0C\u89C6\u4E3A\u65E0\u4FE1\u53F7\uFF0C\u4EA4\u7531\u65F6\u533A\u515C\u5E95"),null;let e=r.split(".")[0],t=wr(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function br(){let r=process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG;if(r)return r.trim();try{return Intl.DateTimeFormat().resolvedOptions().locale||null}catch{return null}}function wr(r){let e=r.split(/[-_]/);if(e.length<2)return null;for(let t=e.length-1;t>=0;t--){let n=e[t];if(/^[A-Za-z]{2}$/.test(n))return n.toUpperCase()}return null}var pe={"Asia/Shanghai":"CN","Asia/Urumqi":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Pyongyang":"KP","Asia/Ulaanbaatar":"MN","Asia/Singapore":"SG","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Manila":"PH","Asia/Kuala_Lumpur":"MY","Asia/Kuching":"MY","Asia/Ho_Chi_Minh":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Yangon":"MM","Asia/Brunei":"BN","Asia/Dili":"TL","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Mumbai":"IN","Asia/Delhi":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Colombo":"LK","Asia/Kathmandu":"NP","Asia/Thimphu":"BT","Asia/Male":"MV","Asia/Almaty":"KZ","Asia/Aqtobe":"KZ","Asia/Qyzylorda":"KZ","Asia/Tashkent":"UZ","Asia/Dushanbe":"TJ","Asia/Bishkek":"KG","Asia/Ashgabat":"TM","Asia/Dubai":"AE","Asia/Riyadh":"SA","Asia/Qatar":"QA","Asia/Bahrain":"BH","Asia/Kuwait":"KW","Asia/Muscat":"OM","Asia/Aden":"YE","Asia/Baghdad":"IQ","Asia/Tehran":"IR","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Beirut":"LB","Asia/Damascus":"SY","Asia/Amman":"JO","Asia/Kabul":"AF","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Tbilisi":"GE","Asia/Nicosia":"CY","Europe/London":"GB","Europe/Dublin":"IE","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Europe/Amsterdam":"NL","Europe/Brussels":"BE","Europe/Vienna":"AT","Europe/Zurich":"CH","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Helsinki":"FI","Europe/Warsaw":"PL","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Moscow":"RU","Europe/Kaliningrad":"RU","Europe/Lisbon":"PT","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Kyiv":"UA","Europe/Kiev":"UA","Europe/Minsk":"BY","Europe/Bucharest":"RO","Europe/Sofia":"BG","Europe/Belgrade":"RS","Europe/Zagreb":"HR","Europe/Ljubljana":"SI","Europe/Sarajevo":"BA","Europe/Skopje":"MK","Europe/Tirane":"AL","Europe/Riga":"LV","Europe/Tallinn":"EE","Europe/Vilnius":"LT","Europe/Chisinau":"MD","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","America/Juneau":"US","America/Honolulu":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Halifax":"CA","America/Edmonton":"CA","America/Winnipeg":"CA","America/Mexico_City":"MX","America/Sao_Paulo":"BR","America/Argentina/Buenos_Aires":"AR","America/Buenos_Aires":"AR","America/Santiago":"CL","America/Lima":"PE","America/Bogota":"CO","America/Caracas":"VE","America/Guayaquil":"EC","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Havana":"CU","America/Santo_Domingo":"DO","America/Jamaica":"JM","America/Port-au-Prince":"HT","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Hobart":"AU","Pacific/Auckland":"NZ","Pacific/Fiji":"FJ","Pacific/Guam":"GU","Africa/Cairo":"EG","Africa/Lagos":"NG","Africa/Johannesburg":"ZA","Africa/Nairobi":"KE","Africa/Casablanca":"MA","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Accra":"GH","Africa/Addis_Ababa":"ET","Africa/Dar_es_Salaam":"TZ","Africa/Khartoum":"SD","Africa/Tripoli":"LY"};function de(){let r=ue();if(r)return{code:r,source:"locale"};let e=nt();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function nt(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=pe[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import it from"fs";import ot from"path";import{homedir as xr}from"os";var Rr="country.region.xml",Dr=".config",Lr="deveco-cli";function st(){let r=process.env.DEVECO_CLI_DATA_DIR?A():ot.join(xr(),Dr,Lr);return ot.join(r,Rr)}function fe(){let r=st();try{if(!it.existsSync(r))return null;let t=it.readFileSync(r,"utf8").match(/<countryregion\s+name="([A-Za-z]{2})"/);return t?t[1].toUpperCase():(p(()=>`[region] country.region.xml malformed: ${r}`),null)}catch(e){return p(()=>`[region] failed to read country.region.xml: ${e.message}`),null}}var at=fe();if(at)E.setCountryCode(at);else{let r=de();r&&E.setCountryCode(r.code)}if(!E.isCN())f.info("[telemetry] background upload skipped (non-CN region)");else{let r=_r.join(A(),"TraceLogData",E.countryCode);_.init(r),(async()=>{try{await _.flush(),await _.retryFailed()}catch(e){f.warn("[telemetry] background upload error:",e),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.11-Test.
|
|
3
|
+
"version": "1.3.11-Test.5",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"supportedDocsApi": 1,
|
|
6
6
|
"license": "MIT",
|
|
@@ -61,14 +61,13 @@
|
|
|
61
61
|
"ora": "^9.4.0",
|
|
62
62
|
"p-limit": "^5.0.0",
|
|
63
63
|
"proper-lockfile": "^4.1.2",
|
|
64
|
-
"regedit": "^5.1.4",
|
|
65
64
|
"semver": "^7.8.5",
|
|
66
65
|
"smol-toml": "^1.6.1",
|
|
67
66
|
"socket.io-client": "^4.7.5",
|
|
68
67
|
"ui-verification-mcp": "0.0.20",
|
|
69
68
|
"xpath": "^0.0.35",
|
|
70
69
|
"zod": "^4.4.3",
|
|
71
|
-
"@deveco-test/deveco-cli-knowledgebase": "1.3.11-Test.
|
|
70
|
+
"@deveco-test/deveco-cli-knowledgebase": "1.3.11-Test.5"
|
|
72
71
|
},
|
|
73
72
|
"devDependencies": {
|
|
74
73
|
"@types/adm-zip": "^0.5.8",
|
|
@@ -27,6 +27,7 @@ Scaffold a new HarmonyOS project.
|
|
|
27
27
|
|
|
28
28
|
### `devecocli build` `[Outside sandbox]`
|
|
29
29
|
Compile and package project/modules. (Defaults: `--product default`, `--build-mode debug`)
|
|
30
|
+
- **AI agent invocation (Windows only)**: `devecocli build` must be launched inside a Start-Process wrapper; running it directly in the agent shell lets the `hvigor` daemon hold the console output pipe, so the agent cannot detect command completion and the window waits forever.
|
|
30
31
|
| Goal | Command |
|
|
31
32
|
|---|---|
|
|
32
33
|
| Single-module / single-`entry` | `devecocli build` |
|
|
@@ -247,6 +248,33 @@ Examples:
|
|
|
247
248
|
- `devecocli verify --test-plan '1. 启动应用,预期:进入应用主界面' --no-fresh-start`
|
|
248
249
|
- `devecocli verify --test-plan '1. 启动应用,预期:进入应用主界面' --device 127.0.0.1:5555`
|
|
249
250
|
|
|
251
|
+
### `devecocli verify appanalyzer` `[Outside sandbox]`
|
|
252
|
+
Run local health checks for apps and atomic services through the bundled AppAnalyzer CLI: it inspects the running app, then reports analysis guidance and fix suggestions.
|
|
253
|
+
- **Prereq**: Command Line Tools install source (not available in DevEco Studio) with the AppAnalyzer component. Run `devecocli verify appanalyzer init` before any check to initialize the environment.
|
|
254
|
+
|
|
255
|
+
| Subcommand | Description |
|
|
256
|
+
|---|---|
|
|
257
|
+
| `init` | Initialize the tool environment (installs Python dependencies). |
|
|
258
|
+
| `autoAnalyze` | Automated page traversal + detection. |
|
|
259
|
+
| `uxAnalyze` | Manual single-page UX detection; put the device on the target page and keep the screen on first. |
|
|
260
|
+
| `powerAnalyze` | Manual power-consumption detection: records ~15s of the app standing by in the foreground, then reports. Real devices only. |
|
|
261
|
+
|
|
262
|
+
- **Common options**: `-b/--bundleName` (Req), `-p/--projectPath` (Req), `-s/--scenes` (default: recommended scenes), `-d/--device <serial|IP:port>` (default: first available real device, else first emulator), `-o/--output <reportPath>` (default: cwd), `-m/--hapPaths` (only with the basic scene, for icon checks).
|
|
263
|
+
- `autoAnalyze` also takes `-t/--duration <minutes>` (5–240, default `10`).
|
|
264
|
+
- Reports are written as both JSON and ZIP to the output path.
|
|
265
|
+
|
|
266
|
+
**Scenes** — `-s` takes a category (`Dxx`, runs every scene under it) or individual scenes (`Sxx`, comma-separated):
|
|
267
|
+
|
|
268
|
+
| Category | Meaning | Scenes |
|
|
269
|
+
|---|---|---|
|
|
270
|
+
| `D03` | UX — multi-device layout adaptation | `S14` truncation, `S15` large image/large font, `S16` white space, `S17` avoid-area occlusion, `S18` foundation |
|
|
271
|
+
| `D04` | Power consumption | `S11` foreground standby |
|
|
272
|
+
|
|
273
|
+
*Ex*: `devecocli verify appanalyzer init`
|
|
274
|
+
*Ex*: `devecocli verify appanalyzer autoAnalyze -b com.example.app -p ./MyApp -s D03 -t 5 -o ./output`
|
|
275
|
+
*Ex*: `devecocli verify appanalyzer uxAnalyze -b com.example.app -p ./MyApp -s S14,S15 -d 127.0.0.1:5555`
|
|
276
|
+
*Ex*: `devecocli verify appanalyzer powerAnalyze -b com.example.app -p ./MyApp`
|
|
277
|
+
|
|
250
278
|
### `devecocli verify log`
|
|
251
279
|
Retrieve the execution log of a verification task by ID.
|
|
252
280
|
|
|
@@ -458,3 +486,5 @@ Solution design supports UI pages only; repository analysis covers the target pa
|
|
|
458
486
|
- **`当前 DevEco Testing 版本不支持 testing`**: The installed client is too old. Run `devecocli testing update`, then retry.
|
|
459
487
|
- **`[ERROR] 前置确认未通过`**: `run` hit the confirmation prompt in a non-interactive shell. Add `--yes`.
|
|
460
488
|
- **`run` killed mid-test**: The bash timeout was shorter than the test. Re-run with a longer timeout; a killed run produces no report.
|
|
489
|
+
- **"Skills marketplace is not available in your region"**: Expected when running `skills list/find/add` outside Chinese mainland (incl. HK/MO). Installed skills still work; `skills remove` and `init` don't touch the network.
|
|
490
|
+
- **"CLI online services are not available in your region"**: Commands needing cloud services (login/signature/agreement) abort when GRS is unreachable or the region has no config; local-only commands (`create`/`build`/`device`) are unaffected. Suggest checking `HTTP_PROXY`/`HTTPS_PROXY`. GRS verifies server certificates on every connection, proxied or not — a proxy that re-signs TLS (corporate inspection) fails closed unless its CA is listed in a `NODE_EXTRA_CA_CERTS` PEM file. Use `DEVECO_CLI_DEBUG=1` to inspect country-code detection and GRS resolution. Telemetry is CN-only (silently disabled elsewhere).
|
package/skills/index.json
CHANGED