@deveco-test/deveco-cli-common 1.3.11-Test.4 → 1.3.11-Test.6

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.
@@ -1,9 +1,46 @@
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 Tt="deveco-cli",J,$=class extends Error{constructor(t){super(t),this.name="CliDataDirError"}};function Et(){let n=process.env.DEVECO_CLI_DATA_DIR,e=(n===void 0||n===""?"":N(n))||Y.join(St(),".local","share",Tt);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=Et();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}},T=null;function Ot(n=!1){T&&T.dispose(),T=new j(n)}function F(){return T||Ot(!1),T}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 E=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.4",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
- `,"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 w=e.slice(i).join(`
1
+ import _r from"path";import*as R from"fs";import*as ve from"path";import{homedir as ct}from"os";import*as ge from"fs";import*as v from"path";function z(r){let e=v.resolve(r),t=[],n=e;for(;;)try{let i=ge.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 q(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=q(r);if(!e)throw new Error("Path must not be empty.");return z(e)}var ut="deveco-cli",ye,K=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function lt(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":q(r))||ve.join(ct(),".local","share",ut);try{return he(t)}catch(n){throw new K(n instanceof Error?n.message:String(n))}}function C(){if(ye!==void 0)return ye;let r=lt();try{if(R.existsSync(r))return R.realpathSync(r)}catch{}return r}import rt from"crypto";import m from"fs";import V from"os";import y from"path";import dt from"https";var Ee={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var N=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 l=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")})})});l.on("timeout",()=>{l.destroy(new Error("request timeout"))}),l.on("error",a),l.write(n),l.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()},W=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}},be=new W({namingStrategy:Se.snakeCase,fieldNames:{}});import P from"crypto";import I from"fs";import ft from"path";var k="aes-256-gcm",mt=12,gt="deveco-cli-trace-file",ht="trace-file-secret",Ce=32;function Te(r){try{let e=I.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Ce?e:null}catch{return null}}function Ae(r){let e=ft.join(r,ht),t=Te(e);if(t)return X(t);let n=P.randomBytes(Ce).toString("base64");try{I.mkdirSync(r,{recursive:!0});try{I.writeFileSync(e,n,{flag:"wx"})}catch{let i=Te(e);if(i)return X(i);I.writeFileSync(e,n)}}catch{}return X(n)}function X(r){return P.createHash("sha256").update(gt).update(r).digest()}function we(r,e){let t=P.randomBytes(mt),n=P.createCipheriv(k,e,t),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o={version:1,algorithm:k,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=P.createDecipheriv(k,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===k&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as d from"fs";import*as M from"path";import*as D from"os";import*as b from"path";import on from"json5";var un=64*1024;function Re(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??b.join(D.homedir(),"AppData","Local");return b.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?b.join(D.homedir(),"Library","Logs","devecocli-mcp-server"):b.join(D.homedir(),".local","share","devecocli-mcp-server","logs")}var Pe="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,Pe),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===Pe||/^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(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="object"?JSON.stringify(l,null,2):String(l)).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 l=Buffer.from(a);d.writeSync(this.fd,l),this.checkRotation(l.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}},L=null;function St(r=!1){L&&L.dispose(),L=new Y(r)}function O(){return L||St(!1),L}var f={debug:(r,...e)=>O().debug(r,...e),info:(r,...e)=>O().info(r,...e),warn:(r,...e)=>O().warn(r,...e),error:(r,...e)=>O().error(r,...e)};import Le from"fs";import bt from"path";var F=300*1e3,B=3600*1e3,_e=10080*60*1e3,A=8*1024*1024,Ne=3600*1e3,De=".pending",Tt=/\.reclaim-\d+-\d+$/;function $(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var Ct="upload-state.json";function Ie(r){return bt.join(r,Ct)}function At(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function J(r){try{let e=Le.readFileSync(Ie(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 At()}}function Z(r,e){try{Le.writeFileSync(Ie(r),JSON.stringify(e),"utf8")}catch{}}function ke(r){let e=J(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Z(r,e))}function Oe(r){let e=J(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,Z(r,e)}function Me(r){let e=J(r);e.lastRetryAt=Date.now(),Z(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 Q(r){if(!r.startsWith("telemetry-"))return null;let e=Tt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(De))return null;let n=t.slice(0,-De.length);return n.endsWith(".txt")?n:null}function Be(r){return Q(r)!==null}import wt from"crypto";import U from"fs";import xt from"path";var Rt="install-id";function Pt(r){return xt.join(r,Rt)}function $e(r){try{let e=U.readFileSync(r,"utf8").trim();return Dt(e)?e:null}catch{return null}}function Dt(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 Ue(r){let e=Pt(r),t=$e(e);if(t)return t;let n=wt.randomUUID();try{U.mkdirSync(r,{recursive:!0});try{U.writeFileSync(e,n,{flag:"wx"})}catch{let i=$e(e);if(i)return i;U.writeFileSync(e,n)}}catch{}return n}import Ut from"axios";var Ge={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ee={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 Lt={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function _t(r){try{return new URL(r)}catch{return null}}function G(r){var e=(typeof r=="string"?_t(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)||Lt[t]||0,!Nt(n,i)))return"";var o=te(t+"_proxy")||te("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Nt(r,e){var t=te("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 te(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}import{spawn as Ve}from"child_process";import*as T from"fs";import*as ze from"os";import*as H from"path";var qe=6e4;async function It(){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=Ve("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 Ot(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function je(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=T.readFileSync(e,"utf8"),h=T.readFileSync(t),S=je(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),l=je(s);return{statusCode:l.statusCode,statusText:l.statusText,body:a,headers:l.headers}}async function Ke(r){if(process.platform!=="win32")return null;let e=kt()??await It();if(!e)return null;let t;r.binary&&(t=T.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 $t(o,r.timeoutMs);return!s||s.code!==0?null:Bt(s.stdout,n,i)}catch{return null}finally{t&&T.rmSync(t,{recursive:!0,force:!0})}}function $t(r,e){let t=Ot();return new Promise(n=>{let i=Ve(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??qe);i.stdout.on("data",l=>{o+=l.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),i.on("close",l=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:l??-1,stdout:o})})})}function Gt(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 re=class{client;constructor(){let e={timeout:Ge.HTTP_TIMEOUT_MS,headers:{"User-Agent":ee.USER_AGENT,"accept-language":ee.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Ut.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=G(t.url??"");return t.proxy=n?Gt(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)||!jt(e))return null;let s,a=t;return n==="GET"?i?.params&&(a=Vt(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})}},ne=new re;function Ht(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function jt(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 Vt(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 Wt from"http";import Xt from"https";import Yt from"path";import We from"tls";import se 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 se.X509Certificate(Qt),Xe=[{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 se.X509Certificate(n)})}catch{}return e}var Ye=new Set,j;function rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(j&&j.envValue===r)return j.anchors;let e=r?nr(r):[],t=e.length?[...Xe,...e]:Xe;return j={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){Ye.has(r)||(Ye.add(r),console.warn(Zt(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Yt.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 se.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(!ur(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 ur(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),l=n.slice(0,-a.length);if(n.endsWith(a)&&l.length>0&&!l.includes("."))return!0}}return!1}var lr=8e3,ie=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)}}},oe=class extends Xt.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??lr}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=G(o),a=new ie(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=We.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),l=this.buildProxyHeaders(s,n,i);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let g=Wt.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:l});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=We.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)})}},ae=new oe({keepAlive:!0});var ce=[{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 ue(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 ne.post(t,{headers:{"User-Agent":dr},httpsAgent:ae,timeout:mr}),i=ne.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 ce.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 br(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 ue(this.countryCode);this.services=t,this.resolved=!0,await Tr(this.countryCode,t)}},E=new le;function tt(r){return yr.join(C(),`grs_${r}.json`)}async function br(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 Tr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await Qe.promises.writeFile(tt(r),JSON.stringify(t),"utf8")}catch{}}var _=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 N;storageDir="";failedDir="";installId="";get disabled(){return $()||!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.6",this.nodeVersion=process.version,this.installId=Ue(e).replace(/-/g,""),this.traceFileKey=Ae(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=be.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=V.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=V.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 V.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(V.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 Oe(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>_e){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<Ne)return;n=g.size}catch{return}let i=y.dirname(e),o=Q(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),l=A-await this.fileSize(a);if(n>l){try{await m.promises.unlink(s)}catch{}f.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${l})`);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>A){f.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${A}), 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 l=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(l,this.installId)}catch{}if(!g){f.warn("[telemetry] upload failed");let h=t.slice(i).join(`
5
42
  `)+`
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
- `).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(`
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=A-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&f.warn(`[telemetry] failed file capped at ${A} 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 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 E;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)}})();
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 x=new _;import{execFile as io,spawn as oo}from"child_process";import{existsSync as ao,readdirSync as co,readFileSync as uo}from"fs";import{spawn as Co}from"child_process";import{existsSync as wo}from"fs";import{dirname as Ro,join as Po}from"path";import{fileURLToPath as Lo}from"url";var Ar=new Set(["C","POSIX"]);function pe(){let r=wr();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=xr(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function wr(){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 xr(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 de={"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 fe(){let r=pe();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=de[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 Rr}from"os";var Pr="country.region.xml",Dr=".config",Lr="deveco-cli";function st(){let r=process.env.DEVECO_CLI_DATA_DIR?C():ot.join(Rr(),Dr,Lr);return ot.join(r,Pr)}function me(){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=me();if(at)E.setCountryCode(at);else{let r=fe();r&&E.setCountryCode(r.code)}if(!E.isCN())f.info("[telemetry] background upload skipped (non-CN region)");else{let r=_r.join(C(),"TraceLogData",E.countryCode);x.init(r),(async()=>{try{await x.flush(),await x.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.4",
3
+ "version": "1.3.11-Test.6",
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.4"
70
+ "@deveco-test/deveco-cli-knowledgebase": "1.3.11-Test.6"
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` |
@@ -38,6 +39,7 @@ Compile and package project/modules. (Defaults: `--product default`, `--build-mo
38
39
  - **Build efficiency**: if build/clean is slow, consult https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-build-optimize-practices for build optimization practices.
39
40
  - **Clean mode**: `devecocli build clean [--mode <mode>] [--modules <m1> <m2>]` runs in module mode by default and reads build options (analyze/parallel/incremental/daemon) from `hvigor-config.json5` `execution`, matching DevEco Studio.
40
41
  - **Build artifacts**: on success, prints absolute paths of all produced `.hap`/`.hsp`/`.har`/`.app` files for direct use.
42
+ - **debugLine**: disabled by default. Pass `--debug-line` to build to forward `-p debugLine=true` to hvigor.
41
43
  - **Signing config**: `--signing-config <name>` overrides the product's default signing config from `build-profile.json5`, enabling release builds with a release signing config.
42
44
 
43
45
  ### `devecocli check lint`
@@ -171,6 +173,7 @@ Build, install, and launch. After a successful ability launch (and after a succe
171
173
  - `--ability <ability>`: Default from `module.json5`.
172
174
  - `--uninstall`: Uninstall existing app first (Fixes signing key issues).
173
175
  - `--skip-build`: Deploy existing artifacts.
176
+ - `--debug-line`: Forward `-p debugLine=true` to hvigor for the full build, `--apply`, and hot-reload compiles (default: disabled).
174
177
  - `--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).
175
178
  - `<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.
176
179
  - **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.
@@ -247,6 +250,33 @@ Examples:
247
250
  - `devecocli verify --test-plan '1. 启动应用,预期:进入应用主界面' --no-fresh-start`
248
251
  - `devecocli verify --test-plan '1. 启动应用,预期:进入应用主界面' --device 127.0.0.1:5555`
249
252
 
253
+ ### `devecocli verify appanalyzer` `[Outside sandbox]`
254
+ 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.
255
+ - **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.
256
+
257
+ | Subcommand | Description |
258
+ |---|---|
259
+ | `init` | Initialize the tool environment (installs Python dependencies). |
260
+ | `autoAnalyze` | Automated page traversal + detection. |
261
+ | `uxAnalyze` | Manual single-page UX detection; put the device on the target page and keep the screen on first. |
262
+ | `powerAnalyze` | Manual power-consumption detection: records ~15s of the app standing by in the foreground, then reports. Real devices only. |
263
+
264
+ - **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).
265
+ - `autoAnalyze` also takes `-t/--duration <minutes>` (5–240, default `10`).
266
+ - Reports are written as both JSON and ZIP to the output path.
267
+
268
+ **Scenes** — `-s` takes a category (`Dxx`, runs every scene under it) or individual scenes (`Sxx`, comma-separated):
269
+
270
+ | Category | Meaning | Scenes |
271
+ |---|---|---|
272
+ | `D03` | UX — multi-device layout adaptation | `S14` truncation, `S15` large image/large font, `S16` white space, `S17` avoid-area occlusion, `S18` foundation |
273
+ | `D04` | Power consumption | `S11` foreground standby |
274
+
275
+ *Ex*: `devecocli verify appanalyzer init`
276
+ *Ex*: `devecocli verify appanalyzer autoAnalyze -b com.example.app -p ./MyApp -s D03 -t 5 -o ./output`
277
+ *Ex*: `devecocli verify appanalyzer uxAnalyze -b com.example.app -p ./MyApp -s S14,S15 -d 127.0.0.1:5555`
278
+ *Ex*: `devecocli verify appanalyzer powerAnalyze -b com.example.app -p ./MyApp`
279
+
250
280
  ### `devecocli verify log`
251
281
  Retrieve the execution log of a verification task by ID.
252
282
 
@@ -328,6 +358,8 @@ devecocli testing update --service MemLeakTest
328
358
  devecocli testing run MemLeakTest --package com.example.myapp --sn <serial> --duration 10 --yes
329
359
  ```
330
360
 
361
+ **Device**: `--sn` must be the device the user confirmed. With several devices connected (`devecocli device list`), ask which one to test and wait for the answer; never default to the first serial.
362
+
331
363
  **Progress**: run `testing run` with the globally installed CLI (`& "$env:APPDATA\npm\devecocli.cmd"` on Windows, `"$(npm prefix -g)/bin/devecocli"` elsewhere) so output streams.
332
364
 
333
365
  **Result**: the run ends with `[REPORT] 报告已生成: <dir>`; read `<dir>/export/2d_report_data.json` (`isTaskPass`, `expandData[].resultSummary`, `expandData[].resultDetails[].status`) or `<dir>/export/Task-*.html` — never print the JSON. Services that write no `2d_report_data.json` keep the verdict in `<dir>/report/<taskId>_report.json` (`taskResult.taskPass`). Exit code stays `0` even when the task fails; on failure read `[ERROR]` / `[SUGGEST]`.
@@ -458,3 +490,5 @@ Solution design supports UI pages only; repository analysis covers the target pa
458
490
  - **`当前 DevEco Testing 版本不支持 testing`**: The installed client is too old. Run `devecocli testing update`, then retry.
459
491
  - **`[ERROR] 前置确认未通过`**: `run` hit the confirmation prompt in a non-interactive shell. Add `--yes`.
460
492
  - **`run` killed mid-test**: The bash timeout was shorter than the test. Re-run with a longer timeout; a killed run produces no report.
493
+ - **"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.
494
+ - **"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
@@ -1,5 +1,5 @@
1
1
  {
2
- "generatedAt": "2026-11-04T07:16:31.607Z",
2
+ "generatedAt": "2026-11-06T09:26:43.746Z",
3
3
  "skills": [
4
4
  {
5
5
  "name": "deveco-cli",