@deveco-test/deveco-cli-common 1.3.13-23.2 → 1.3.13-23.4

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.
Files changed (50) hide show
  1. package/README.md +7 -81
  2. package/THIRD-PARTY-LICENSES +76 -0
  3. package/dist/cli.js +245 -287
  4. package/dist/design2arkts-engine/resources/skill/SKILL.md +82 -9
  5. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkui-scoring-workflow/INSTRUCTIONS.md +25 -0
  6. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/INSTRUCTIONS.md +2 -0
  7. package/dist/design2arkts-engine/resources/skill/references/cli-integration.md +26 -1
  8. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/01-acquire-figma-react-source.md +1 -1
  9. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/02-convert-react-to-arkui.md +3 -1
  10. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/03-complete-interaction-logic.md +1 -1
  11. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/04-quality-and-build.md +3 -1
  12. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/05-summary.md +9 -1
  13. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/01-acquire-figma-react-source.md +1 -1
  14. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/02-convert-react-to-arkui.md +3 -1
  15. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/03-complete-interaction-logic.md +1 -1
  16. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/04-quality-and-build.md +3 -1
  17. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/05-visual-calibration.md +5 -2
  18. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/06-summary.md +14 -2
  19. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/01-acquire-pixso-dsl.md +2 -2
  20. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/02-generate-skeleton-and-assets.md +4 -2
  21. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/03-understand-repository.md +2 -2
  22. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/05-design-component-tree.md +2 -2
  23. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/06-implement-static-layout.md +2 -2
  24. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/07-complete-interaction-logic.md +2 -2
  25. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/08-quality-build-and-audits.md +4 -2
  26. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/09-summary.md +13 -3
  27. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/01-acquire-pixso-dsl.md +2 -2
  28. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/02-generate-skeleton-and-assets.md +4 -2
  29. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/03-understand-repository.md +2 -2
  30. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/05-design-and-confirm-component-tree.md +5 -5
  31. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/06-implement-static-layout.md +2 -2
  32. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/07-complete-interaction-logic.md +2 -2
  33. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/08-quality-build-and-audits.md +4 -2
  34. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/09-visual-calibration.md +5 -2
  35. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/10-summary.md +23 -3
  36. package/dist/design2arkts-engine/resources/skill/references/runtime-contract.md +24 -15
  37. package/dist/design2arkts-engine/resources/skill/scripts/workflow.mjs +464 -7
  38. package/dist/internal/telemetry-upload-background.js +9 -9
  39. package/package.json +3 -5
  40. package/skills/deveco-cli/SKILL.md +13 -51
  41. package/skills/hmos-dfx-analyzer/SKILL.md +42 -8
  42. package/skills/hmos-dfx-analyzer/references/report-encoding-pitfalls.md +41 -0
  43. package/skills/hmos-dfx-analyzer/scripts/export_report.py +10 -4
  44. package/skills/hmos-dfx-analyzer/test-cases/functional.md +54 -6
  45. package/skills/hmos-dfx-analyzer/test-cases/smoke.md +40 -3
  46. package/skills/hmos-dfx-analyzer/test-cases/trigger.md +21 -2
  47. package/skills/index.json +2 -2
  48. package/NOTICE +0 -5022
  49. package/skills/deveco-cli/docs/arkts-rules.md +0 -33
  50. package/skills/deveco-cli/docs/design2arkts.md +0 -276
@@ -1,8 +1,8 @@
1
- import on from"path";import*as _ from"fs";import*as _e from"path";import{homedir as Dt}from"os";var w=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function ee(r){if(r instanceof w)return r.traceMessage;if(r instanceof Error){let e=r.code;return typeof e=="string"&&e!==""?e:r.name}return"UnknownError"}function te(r,e){return`${r}:${e}`}var h=class extends w{category;constructor(e,t,n,o){super(t,n,o),this.name="CategorizedTraceError",this.category=e}};function A(...r){return e=>r.includes(e.name)}function F(r,...e){return t=>{let n=t.code;return t.name===r&&typeof n=="string"&&e.includes(n)}}function wt(r){let e=r.code;return e==="ETIMEDOUT"||e==="RPC_TIMEOUT"||/timeout/i.test(r.name)}function Rt(r){let e=r.code;return r.name==="ScreenRecordError"&&typeof e=="string"&&e.endsWith("_TIMEOUT")}var Pt=[{category:"Timeout",match:wt},{category:"Internal",match:A("ExecaError")},{category:"RuntimeCondition",match:A("CacheDirError","DocPathSafetyError")},{category:"InvalidArgument",match:A("SelectorParseError")},{category:"InvalidArgument",match:A("InvalidApiLevelError")},{category:"InvalidArgument",match:A("TemplateNotFoundError")},{category:"InvalidArgument",match:A("InvalidArgumentError")},{category:"InvalidArgument",match:F("ScreenRecordError","INVALID_ARGUMENT","INVALID_RECORDING_PATH")},{category:"Timeout",match:Rt},{category:"InvalidArgument",match:F("FaultLogError","INVALID_ARGUMENTS","INVALID_INPUT","INPUT_OVERSIZED")},{category:"RuntimeCondition",match:F("FaultLogError","FILE_NOT_FOUND","UNRECOGNIZED_LOG")},{category:"Internal",match:F("FaultLogError","INTERNAL_ERROR")},{category:"RuntimeCondition",match:A("GrsError")}];function Lt(r){return Pt.find(t=>t.match(r))?.category??"Other"}function re(r){if(r instanceof h)return te(r.category,r.traceMessage);let e=r instanceof Error?Lt(r):"Other";return te(e,ee(r))}import*as Le from"fs";import*as S from"path";function ne(r){let e=S.resolve(r),t=[],n=e;for(;;)try{let o=Le.realpathSync(n);return t.length===0?o:S.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=S.dirname(n);if(i===n)return e;t.push(S.basename(n)),n=i}}function oe(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function De(r){let e=oe(r);if(!e)throw new h("InvalidArgument","Path must not be empty.","Path must not be empty.");return ne(e)}var It="deveco-cli",Ie,ie=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function _t(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":oe(r))||_e.join(Dt(),".local","share",It);try{return De(t)}catch(n){throw new ie(n instanceof Error?n.message:String(n))}}function R(){if(Ie!==void 0)return Ie;let r=_t();try{if(_.existsSync(r))return _.realpathSync(r)}catch{}return r}import St from"crypto";import m from"fs";import Q from"os";import E from"path";import Ot from"https";var Ne={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var $=class r{static ENDPOINT=Ne.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:o}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(o)}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,o){let i=new URL(e);return new Promise((s,a)=>{let c=Ot.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},g=>{let v=[];g.on("data",I=>v.push(I)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(v).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(n),c.end()})}};var Oe={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()},se=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(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??Oe.identity,n=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=n[i]??t(i);o[a]=this.transform(s)}return o}},ke=new se({namingStrategy:Oe.snakeCase,fieldNames:{}});import N from"crypto";import U from"fs";import kt from"path";var G="aes-256-gcm",Mt=12,Ft="deveco-cli-trace-file",Bt="trace-file-secret",Fe=32;function Me(r){try{let e=U.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Fe?e:null}catch{return null}}function Be(r){let e=kt.join(r,Bt),t=Me(e);if(t)return ae(t);let n=N.randomBytes(Fe).toString("base64");try{U.mkdirSync(r,{recursive:!0});try{U.writeFileSync(e,n,{flag:"wx"})}catch{let o=Me(e);if(o)return ae(o);U.writeFileSync(e,n)}}catch{}return ae(n)}function ae(r){return N.createHash("sha256").update(Ft).update(r).digest()}function $e(r,e){let t=N.randomBytes(Mt),n=N.createCipheriv(G,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i={version:1,algorithm:G,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(i)}function Ue(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!$t(t))return r;try{let n=N.createDecipheriv(G,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 $t(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===G&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as f from"fs";import*as j from"path";import*as O from"os";import*as b from"path";import Bn from"json5";var Hn=64*1024;function Ge(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??b.join(O.homedir(),"AppData","Local");return b.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?b.join(O.homedir(),"Library","Logs","devecocli-mcp-server"):b.join(O.homedir(),".local","share","devecocli-mcp-server","logs")}var He="mcp-server.log",Ut="mcp-server",Gt={maxSize:10*1024*1024,maxFiles:4},ce=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={...Gt,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Ge(),this.currentLogFile=j.join(this.logDir,He),f.existsSync(this.logDir)||f.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"),o=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${o}`}getRotatedFileName(e,t){return j.join(this.logDir,`${Ut}-${e}.log.${t}`)}fileExists(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=f.readdirSync(this.logDir),t=[];for(let o of e)if(o===He||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=j.join(this.logDir,o),s=f.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let o=n;o<t.length;o++)try{f.unlinkSync(t[o].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)&&f.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&f.renameSync(i,s)}let n=this.getRotatedFileName(e,1);f.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=f.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=f.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{f.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 o=n.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`: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}] ${i}
2
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);f.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{f.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},k=null;function Ht(r=!1){k&&k.dispose(),k=new ce(r)}function H(){return k||Ht(!1),k}var d={debug:(r,...e)=>H().debug(r,...e),info:(r,...e)=>H().info(r,...e),warn:(r,...e)=>H().warn(r,...e),error:(r,...e)=>H().error(r,...e)};import Ve from"fs";import jt from"path";var V=300*1e3,z=3600*1e3,ze=10080*60*1e3,P=8*1024*1024,qe=3600*1e3,je=".pending",Vt=/\.reclaim-\d+-\d+$/;function q(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var zt="upload-state.json";function Ke(r){return jt.join(r,zt)}function qt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ue(r){try{let e=Ve.readFileSync(Ke(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 qt()}}function le(r,e){try{Ve.writeFileSync(Ke(r),JSON.stringify(e),"utf8")}catch{}}function We(r){let e=ue(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),le(r,e))}function Xe(r){let e=ue(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,le(r,e)}function Ye(r){let e=ue(r);e.lastRetryAt=Date.now(),le(r,e)}function Je(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 pe(r){if(!r.startsWith("telemetry-"))return null;let e=Vt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(je))return null;let n=t.slice(0,-je.length);return n.endsWith(".txt")?n:null}function K(r){return pe(r)!==null}import Kt from"crypto";import W from"fs";import Wt from"path";var Xt="install-id";function Yt(r){return Wt.join(r,Xt)}function Ze(r){try{let e=W.readFileSync(r,"utf8").trim();return Jt(e)?e:null}catch{return null}}function Jt(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 Qe(r){let e=Yt(r),t=Ze(e);if(t)return t;let n=Kt.randomUUID();try{W.mkdirSync(r,{recursive:!0});try{W.writeFileSync(e,n,{flag:"wx"})}catch{let o=Ze(e);if(o)return o;W.writeFileSync(e,n)}}catch{}return n}import y from"fs";import C from"path";var Zt="install-id",Qt="trace-file-secret",de="upload-state.json",et="failed";function rt(r){return r.startsWith("telemetry-")&&r.endsWith(".txt")||K(r)}function er(r){try{return y.readdirSync(r).filter(rt)}catch{return[]}}function tr(r,e,t){try{return y.existsSync(e)?t?(y.appendFileSync(e,y.readFileSync(r)),y.rmSync(r),!0):!1:(y.renameSync(r,e),!0)}catch{return!1}}function tt(r,e,t){let n=0;for(let o of r)tr(C.join(e,o),C.join(t,o),!0)&&n++;return n}function nt(r){let e=C.dirname(r);e!==r&&(rr(e,r),nr(e,r))}function rr(r,e){for(let t of[Zt,Qt]){let n=C.join(e,t),o=C.join(r,t);if(y.existsSync(n)&&y.existsSync(o))try{y.rmSync(n)}catch{}}}function nr(r,e){let t;try{t=y.readdirSync(r)}catch{return}let n=t.filter(rt),o=C.join(r,et),i=er(o),s=t.includes(de);if(n.length===0&&i.length===0&&!s)return;let a=C.join(e,et);try{y.mkdirSync(e,{recursive:!0}),y.mkdirSync(a,{recursive:!0})}catch{return}let c=tt(n,r,e)+tt(i,o,a);or(r,e,s);try{y.rmdirSync(o)}catch{}c>0&&d.debug(`[telemetry] migrated ${c} legacy trace files into region dir`)}function or(r,e,t){if(!t)return;let n=C.join(r,de),o=C.join(e,de);try{y.existsSync(o)?y.rmSync(n):y.renameSync(n,o)}catch{}}import gr from"axios";var ot={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},fe={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 ir={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function sr(r){try{return new URL(r)}catch{return null}}function X(r){var e=(typeof r=="string"?sr(r):r)||{},t=e.protocol,n=e.host,o=e.port;if(typeof n!="string"||!n||typeof t!="string"||(t=t.split(":",1)[0],n=n.replace(/:\d*$/,""),o=parseInt(o)||ir[t]||0,!ar(n,o)))return"";var i=me(t+"_proxy")||me("all_proxy");return i&&i.indexOf("://")===-1&&(i=t+"://"+i),i}function ar(r,e){var t=me("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(n){if(!n)return!0;var o=n.match(/^(.+):(\d+)$/),i=o?o[1]:n,s=o?parseInt(o[2]):0;return s&&s!==e?!0:/^[.*]/.test(i)?(i.charAt(0)==="*"&&(i=i.slice(1)),!r.endsWith(i)):r!==i}):!0}function me(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}function Y(r){try{let e=new URL(r);return`${e.protocol}//${e.host}`}catch{return"<redacted>"}}import{spawn as at}from"child_process";import*as x from"fs";import*as ct from"os";import*as J from"path";var ut=6e4;async function cr(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await it(r,"ProxyServer");if(!e)return null;let t=await it(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function it(r,e){return new Promise(t=>{let n=at("reg.exe",["query",r,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="";n.stdout.on("data",i=>{o+=i.toString()}),n.on("error",()=>t(null)),n.on("close",i=>{if(i!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(o);t(s?s[1]:null)})})}function ur(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function lr(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function st(r){let e={},t=0,n="";for(let o of r.split(/\r?\n/)){let i=o.trim();if(!i)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(i);if(s){t=parseInt(s[1],10),n=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(i);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:n,headers:e}}function pr(r,e,t,n){let o=["--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??ut)/1e3)))];return r.method&&r.method!=="GET"&&o.push("-X",r.method),r.data!==void 0&&o.push("--data-binary",r.data),o.push(...dr(r.headers,r.data!==void 0)),n?(o.push("--dump-header",t),o.push("--output",n)):o.push("--include"),o.push(r.url),o}function dr(r,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),n=[],o=!1;for(let[i,s]of Object.entries(r??{})){let a=i.toLowerCase();a==="content-type"&&(o=!0),t.has(a)||n.push("-H",`${i}: ${s}`)}return e&&!o&&n.push("-H","Content-Type: application/json"),n}function fr(r,e,t){if(t){let g=x.readFileSync(e,"utf8"),v=x.readFileSync(t),I=st(g);return{statusCode:I.statusCode,statusText:I.statusText,body:v.toString("base64"),headers:I.headers,bodyBuffer:v}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let o=r.slice(n),i=o.indexOf(`\r
1
+ import cn from"path";import*as I from"fs";import*as _e from"path";import{homedir as wt}from"os";import*as Pe from"fs";import*as S from"path";function Q(r){let e=S.resolve(r),t=[],n=e;for(;;)try{let o=Pe.realpathSync(n);return t.length===0?o:S.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=S.dirname(n);if(i===n)return e;t.push(S.basename(n)),n=i}}function ee(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function De(r){let e=ee(r);if(!e)throw new Error("Path must not be empty.");return Q(e)}var Rt="deveco-cli",Le,te=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Pt(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":ee(r))||_e.join(wt(),".local","share",Rt);try{return De(t)}catch(n){throw new te(n instanceof Error?n.message:String(n))}}function x(){if(Le!==void 0)return Le;let r=Pt();try{if(I.existsSync(r))return I.realpathSync(r)}catch{}return r}import St from"crypto";import m from"fs";import Z from"os";import y from"path";import Lt from"https";var Ie={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var F=class r{static ENDPOINT=Ie.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:o}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(o)}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,o){let i=new URL(e);return new Promise((s,a)=>{let c=Lt.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},g=>{let E=[];g.on("data",_=>E.push(_)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(E).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(n),c.end()})}};var w=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function re(r){if(r instanceof w)return r.traceMessage;if(r instanceof Error){let e=r.code;return typeof e=="string"&&e!==""?e:r.name}return"UnknownError"}function ne(r,e){return`${r}:${e}`}var R=class extends w{category;constructor(e,t,n,o){super(t,n,o),this.name="CategorizedTraceError",this.category=e}};function b(...r){return e=>r.includes(e.name)}function B(r,...e){return t=>{let n=t.code;return t.name===r&&typeof n=="string"&&e.includes(n)}}function _t(r){return r.code==="ETIMEDOUT"||/timeout/i.test(r.name)}function It(r){let e=r.code;return r.name==="ScreenRecordError"&&typeof e=="string"&&e.endsWith("_TIMEOUT")}var Nt=[{category:"Timeout",match:_t},{category:"Internal",match:b("ExecaError")},{category:"RuntimeCondition",match:b("CacheDirError","DocPathSafetyError")},{category:"InvalidArgument",match:b("SelectorParseError")},{category:"InvalidArgument",match:b("InvalidApiLevelError")},{category:"InvalidArgument",match:b("TemplateNotFoundError")},{category:"InvalidArgument",match:b("InvalidArgumentError")},{category:"InvalidArgument",match:B("ScreenRecordError","INVALID_ARGUMENT","INVALID_RECORDING_PATH")},{category:"Timeout",match:It},{category:"InvalidArgument",match:B("FaultLogError","INVALID_ARGUMENTS","INVALID_INPUT","INPUT_OVERSIZED")},{category:"RuntimeCondition",match:B("FaultLogError","FILE_NOT_FOUND","UNRECOGNIZED_LOG")},{category:"Internal",match:B("FaultLogError","INTERNAL_ERROR")},{category:"RuntimeCondition",match:b("GrsError")}];function Ot(r){return Nt.find(t=>t.match(r))?.category??"Other"}function oe(r){if(r instanceof R)return ne(r.category,r.traceMessage);let e=r instanceof Error?Ot(r):"Other";return ne(e,re(r))}var Ne={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()},ie=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(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??Ne.identity,n=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=n[i]??t(i);o[a]=this.transform(s)}return o}},Oe=new ie({namingStrategy:Ne.snakeCase,fieldNames:{}});import N from"crypto";import $ from"fs";import kt from"path";var U="aes-256-gcm",Mt=12,Ft="deveco-cli-trace-file",Bt="trace-file-secret",Me=32;function ke(r){try{let e=$.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Me?e:null}catch{return null}}function Fe(r){let e=kt.join(r,Bt),t=ke(e);if(t)return se(t);let n=N.randomBytes(Me).toString("base64");try{$.mkdirSync(r,{recursive:!0});try{$.writeFileSync(e,n,{flag:"wx"})}catch{let o=ke(e);if(o)return se(o);$.writeFileSync(e,n)}}catch{}return se(n)}function se(r){return N.createHash("sha256").update(Ft).update(r).digest()}function Be(r,e){let t=N.randomBytes(Mt),n=N.createCipheriv(U,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i={version:1,algorithm:U,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(i)}function $e(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!$t(t))return r;try{let n=N.createDecipheriv(U,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 $t(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===U&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as f from"fs";import*as H from"path";import*as O from"os";import*as C from"path";import Un from"json5";var Vn=64*1024;function Ue(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??C.join(O.homedir(),"AppData","Local");return C.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?C.join(O.homedir(),"Library","Logs","devecocli-mcp-server"):C.join(O.homedir(),".local","share","devecocli-mcp-server","logs")}var Ge="mcp-server.log",Ut="mcp-server",Gt={maxSize:10*1024*1024,maxFiles:4},ae=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={...Gt,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Ue(),this.currentLogFile=H.join(this.logDir,Ge),f.existsSync(this.logDir)||f.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"),o=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${o}`}getRotatedFileName(e,t){return H.join(this.logDir,`${Ut}-${e}.log.${t}`)}fileExists(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=f.readdirSync(this.logDir),t=[];for(let o of e)if(o===Ge||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=H.join(this.logDir,o),s=f.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let o=n;o<t.length;o++)try{f.unlinkSync(t[o].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)&&f.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&f.renameSync(i,s)}let n=this.getRotatedFileName(e,1);f.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=f.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=f.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{f.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 o=n.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`: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}] ${i}
2
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);f.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{f.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},k=null;function Ht(r=!1){k&&k.dispose(),k=new ae(r)}function G(){return k||Ht(!1),k}var d={debug:(r,...e)=>G().debug(r,...e),info:(r,...e)=>G().info(r,...e),warn:(r,...e)=>G().warn(r,...e),error:(r,...e)=>G().error(r,...e)};import je from"fs";import jt from"path";var j=300*1e3,V=3600*1e3,Ve=10080*60*1e3,P=8*1024*1024,ze=3600*1e3,He=".pending",Vt=/\.reclaim-\d+-\d+$/;function z(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var zt="upload-state.json";function qe(r){return jt.join(r,zt)}function qt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ce(r){try{let e=je.readFileSync(qe(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 qt()}}function ue(r,e){try{je.writeFileSync(qe(r),JSON.stringify(e),"utf8")}catch{}}function We(r){let e=ce(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),ue(r,e))}function Ke(r){let e=ce(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,ue(r,e)}function Xe(r){let e=ce(r);e.lastRetryAt=Date.now(),ue(r,e)}function Ye(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 le(r){if(!r.startsWith("telemetry-"))return null;let e=Vt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(He))return null;let n=t.slice(0,-He.length);return n.endsWith(".txt")?n:null}function q(r){return le(r)!==null}import Wt from"crypto";import W from"fs";import Kt from"path";var Xt="install-id";function Yt(r){return Kt.join(r,Xt)}function Je(r){try{let e=W.readFileSync(r,"utf8").trim();return Jt(e)?e:null}catch{return null}}function Jt(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 Ze(r){let e=Yt(r),t=Je(e);if(t)return t;let n=Wt.randomUUID();try{W.mkdirSync(r,{recursive:!0});try{W.writeFileSync(e,n,{flag:"wx"})}catch{let o=Je(e);if(o)return o;W.writeFileSync(e,n)}}catch{}return n}import h from"fs";import T from"path";var Zt="install-id",Qt="trace-file-secret",pe="upload-state.json",Qe="failed";function tt(r){return r.startsWith("telemetry-")&&r.endsWith(".txt")||q(r)}function er(r){try{return h.readdirSync(r).filter(tt)}catch{return[]}}function tr(r,e,t){try{return h.existsSync(e)?t?(h.appendFileSync(e,h.readFileSync(r)),h.rmSync(r),!0):!1:(h.renameSync(r,e),!0)}catch{return!1}}function et(r,e,t){let n=0;for(let o of r)tr(T.join(e,o),T.join(t,o),!0)&&n++;return n}function rt(r){let e=T.dirname(r);e!==r&&(rr(e,r),nr(e,r))}function rr(r,e){for(let t of[Zt,Qt]){let n=T.join(e,t),o=T.join(r,t);if(h.existsSync(n)&&h.existsSync(o))try{h.rmSync(n)}catch{}}}function nr(r,e){let t;try{t=h.readdirSync(r)}catch{return}let n=t.filter(tt),o=T.join(r,Qe),i=er(o),s=t.includes(pe);if(n.length===0&&i.length===0&&!s)return;let a=T.join(e,Qe);try{h.mkdirSync(e,{recursive:!0}),h.mkdirSync(a,{recursive:!0})}catch{return}let c=et(n,r,e)+et(i,o,a);or(r,e,s);try{h.rmdirSync(o)}catch{}c>0&&d.debug(`[telemetry] migrated ${c} legacy trace files into region dir`)}function or(r,e,t){if(!t)return;let n=T.join(r,pe),o=T.join(e,pe);try{h.existsSync(o)?h.rmSync(n):h.renameSync(n,o)}catch{}}import hr from"axios";var nt={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},de={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 ir={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function sr(r){try{return new URL(r)}catch{return null}}function K(r){var e=(typeof r=="string"?sr(r):r)||{},t=e.protocol,n=e.host,o=e.port;if(typeof n!="string"||!n||typeof t!="string"||(t=t.split(":",1)[0],n=n.replace(/:\d*$/,""),o=parseInt(o)||ir[t]||0,!ar(n,o)))return"";var i=fe(t+"_proxy")||fe("all_proxy");return i&&i.indexOf("://")===-1&&(i=t+"://"+i),i}function ar(r,e){var t=fe("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(n){if(!n)return!0;var o=n.match(/^(.+):(\d+)$/),i=o?o[1]:n,s=o?parseInt(o[2]):0;return s&&s!==e?!0:/^[.*]/.test(i)?(i.charAt(0)==="*"&&(i=i.slice(1)),!r.endsWith(i)):r!==i}):!0}function fe(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}function X(r){try{let e=new URL(r);return`${e.protocol}//${e.host}`}catch{return"<redacted>"}}import{spawn as st}from"child_process";import*as A from"fs";import*as at from"os";import*as Y from"path";var ct=6e4;async function cr(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await ot(r,"ProxyServer");if(!e)return null;let t=await ot(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function ot(r,e){return new Promise(t=>{let n=st("reg.exe",["query",r,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="";n.stdout.on("data",i=>{o+=i.toString()}),n.on("error",()=>t(null)),n.on("close",i=>{if(i!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(o);t(s?s[1]:null)})})}function ur(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function lr(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function it(r){let e={},t=0,n="";for(let o of r.split(/\r?\n/)){let i=o.trim();if(!i)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(i);if(s){t=parseInt(s[1],10),n=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(i);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:n,headers:e}}function pr(r,e,t,n){let o=["--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??ct)/1e3)))];return r.method&&r.method!=="GET"&&o.push("-X",r.method),r.data!==void 0&&o.push("--data-binary",r.data),o.push(...dr(r.headers,r.data!==void 0)),n?(o.push("--dump-header",t),o.push("--output",n)):o.push("--include"),o.push(r.url),o}function dr(r,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),n=[],o=!1;for(let[i,s]of Object.entries(r??{})){let a=i.toLowerCase();a==="content-type"&&(o=!0),t.has(a)||n.push("-H",`${i}: ${s}`)}return e&&!o&&n.push("-H","Content-Type: application/json"),n}function fr(r,e,t){if(t){let g=A.readFileSync(e,"utf8"),E=A.readFileSync(t),_=it(g);return{statusCode:_.statusCode,statusText:_.statusText,body:E.toString("base64"),headers:_.headers,bodyBuffer:E}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let o=r.slice(n),i=o.indexOf(`\r
3
3
  \r
4
- `);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),c=st(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function lt(r){if(process.platform!=="win32")return null;let e=ur()??await cr();if(!e)return null;let t;r.binary&&(t=x.mkdtempSync(J.join(ct.tmpdir(),"curl-")));let n=t?J.join(t,"header.tmp"):void 0,o=t?J.join(t,"body.tmp"):void 0;try{let i=pr(r,e,n,o),s=await mr(i,r.timeoutMs);return!s||s.code!==0?null:fr(s.stdout,n,o)}catch{return null}finally{t&&x.rmSync(t,{recursive:!0,force:!0})}}function mr(r,e){let t=lr();return new Promise(n=>{let o=at(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="",s=!1,a=setTimeout(()=>{s||(s=!0,o.kill())},e??ut);o.stdout.on("data",c=>{i+=c.toString()}),o.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),o.on("close",c=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:c??-1,stdout:i})})})}function he(r){let e=new URL(r),t=pt(e.username,r),n=pt(e.password,r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,...t||n?{auth:{username:t,password:n}}:{}}}function pt(r,e){try{return decodeURIComponent(r)}catch{throw new h("InvalidArgument",`Invalid proxy URL ${JSON.stringify(Y(e))}: malformed percent-encoding in credentials. Percent-encode special characters (e.g. '@' as '%40') in the proxy URL.`,"Invalid proxy URL.")}}function hr(r,e){return r==="ETIMEDOUT"||r==="ECONNABORTED"&&/timeout/i.test(e)}function yr(r){let e=`Network connection failed (${r.code}). Please check your proxy configuration or network settings`,t=new h(hr(r.code,r.message)?"Timeout":"RuntimeCondition",`${r.message}
5
- ${e}`,r.code??"Unknown",{cause:r});return t.code=r.code,t.response=r.response,t}var ge=class{client;constructor(){let e={timeout:ot.HTTP_TIMEOUT_MS,headers:{"User-Agent":fe.USER_AGENT,"accept-language":fe.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=gr.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=X(t.url??"");return t.proxy=n?he(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{throw yr(t)})}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 h("Internal",`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,"Failed to parse JSON response.",{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 h("Internal",`HTTP ${n.status}`,"HTTP request failed.");return Buffer.from(n.data)}catch(n){let o=await this.tryCurlFallback(n,e,"GET",t,!0);if(o?.bodyBuffer){if(o.statusCode!==200)throw new h("Internal",`HTTP ${o.statusCode}`,"HTTP request failed.");return o.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 o=await this.tryCurlFallback(n,e,"GET",t,!0);if(o?.bodyBuffer)return{statusCode:o.statusCode,statusText:o.statusText,buffer:o.bodyBuffer,body:o.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 o=Buffer.from(n.data);return{statusCode:n.status,statusText:n.statusText??"",buffer:o,body:o.toString("utf8")}}async withCurlFallback(e,t,n,o){let i=await this.tryCurlFallback(e,t,n,o,!1);if(i)return{data:i.body,statusCode:i.statusCode,statusText:i.statusText,headers:i.headers};throw e}async tryCurlFallback(e,t,n,o,i=!1){if(Er(o)||process.platform!=="win32"||!(e instanceof Error)||!vr(e))return null;let s,a=t;return n==="GET"?o?.params&&(a=Sr(t,o.params)):o?.params!==void 0&&o.params!==null&&(s=typeof o.params=="string"?o.params:JSON.stringify(o.params)),lt({url:a,method:n,data:s,headers:o?.headers,timeoutMs:o?.timeout,binary:i})}},ye=new ge;function Er(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function vr(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 Sr(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[i,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${i}[]`,String(a));else t.append(i,String(s));let n=t.toString();if(!n)return r;let o=r.includes("?")?"&":"?";return`${r}${o}${n}`}function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;console.error(`[DEBUG] ${e}`)}}import Tr from"fs";import Cr from"http";import br from"https";import Ar from"path";import dt from"tls";import Se from"crypto";import{yellow as xr}from"colorette";var wr=`-----BEGIN CERTIFICATE-----
4
+ `);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),c=it(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function ut(r){if(process.platform!=="win32")return null;let e=ur()??await cr();if(!e)return null;let t;r.binary&&(t=A.mkdtempSync(Y.join(at.tmpdir(),"curl-")));let n=t?Y.join(t,"header.tmp"):void 0,o=t?Y.join(t,"body.tmp"):void 0;try{let i=pr(r,e,n,o),s=await mr(i,r.timeoutMs);return!s||s.code!==0?null:fr(s.stdout,n,o)}catch{return null}finally{t&&A.rmSync(t,{recursive:!0,force:!0})}}function mr(r,e){let t=lr();return new Promise(n=>{let o=st(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="",s=!1,a=setTimeout(()=>{s||(s=!0,o.kill())},e??ct);o.stdout.on("data",c=>{i+=c.toString()}),o.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),o.on("close",c=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:c??-1,stdout:i})})})}function ge(r){let e=new URL(r),t=lt(e.username,r),n=lt(e.password,r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,...t||n?{auth:{username:t,password:n}}:{}}}function lt(r,e){try{return decodeURIComponent(r)}catch{throw new Error(`Invalid proxy URL ${JSON.stringify(X(e))}: malformed percent-encoding in credentials. Percent-encode special characters (e.g. '@' as '%40') in the proxy URL.`)}}function yr(r,e){return r==="ETIMEDOUT"||r==="ECONNABORTED"&&/timeout/i.test(e)}function Er(r){let e=`Network connection failed (${r.code}). Please check your proxy configuration or network settings`,t=new R(yr(r.code,r.message)?"Timeout":"RuntimeCondition",`${r.message}
5
+ ${e}`,r.code??"Unknown",{cause:r});return t.code=r.code,t.response=r.response,t}var me=class{client;constructor(){let e={timeout:nt.HTTP_TIMEOUT_MS,headers:{"User-Agent":de.USER_AGENT,"accept-language":de.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=hr.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=K(t.url??"");return t.proxy=n?ge(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{throw Er(t)})}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 o=await this.tryCurlFallback(n,e,"GET",t,!0);if(o?.bodyBuffer){if(o.statusCode!==200)throw new Error(`HTTP ${o.statusCode}`);return o.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 o=await this.tryCurlFallback(n,e,"GET",t,!0);if(o?.bodyBuffer)return{statusCode:o.statusCode,statusText:o.statusText,buffer:o.bodyBuffer,body:o.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 o=Buffer.from(n.data);return{statusCode:n.status,statusText:n.statusText??"",buffer:o,body:o.toString("utf8")}}async withCurlFallback(e,t,n,o){let i=await this.tryCurlFallback(e,t,n,o,!1);if(i)return{data:i.body,statusCode:i.statusCode,statusText:i.statusText,headers:i.headers};throw e}async tryCurlFallback(e,t,n,o,i=!1){if(Sr(o)||process.platform!=="win32"||!(e instanceof Error)||!vr(e))return null;let s,a=t;return n==="GET"?o?.params&&(a=Tr(t,o.params)):o?.params!==void 0&&o.params!==null&&(s=typeof o.params=="string"?o.params:JSON.stringify(o.params)),ut({url:a,method:n,data:s,headers:o?.headers,timeoutMs:o?.timeout,binary:i})}},he=new me;function Sr(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function vr(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 Tr(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[i,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${i}[]`,String(a));else t.append(i,String(s));let n=t.toString();if(!n)return r;let o=r.includes("?")?"&":"?";return`${r}${o}${n}`}import{AsyncLocalStorage as Cr}from"async_hooks";var br=new Cr;function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;br.getStore()?console.error(`[DEBUG] ${e}`):console.log(`[DEBUG] ${e}`)}}import Ar from"fs";import xr from"http";import wr from"https";import Rr from"path";import pt from"tls";import Se from"crypto";import{yellow as Pr}from"colorette";var Dr=`-----BEGIN CERTIFICATE-----
6
6
  MIIF/TCCA+WgAwIBAgIIIQV1CU5bvEMwDQYJKoZIhvcNAQELBQAwUDELMAkGA1UE
7
7
  BhMCQ04xDzANBgNVBAoMBkh1YXdlaTETMBEGA1UECwwKSHVhd2VpIENCRzEbMBkG
8
8
  A1UEAwwSSHVhd2VpIENCRyBSb290IENBMB4XDTE4MDEzMDA3NDI1OVoXDTM4MDEy
@@ -36,11 +36,11 @@ zYl5snR6SmrDfVmtsyz8aMqifx4gsVV2M5/owv8H3bUdOd5RbkKhzOS2Pmep0bbw
36
36
  WRFUrWuQ+5ci2LLkZyIt9ffNR8W9gbmZOZZTrwSFRIT1Q433NOzCQNDjKwnekGAx
37
37
  8o746tqqZxGCXgy2MaIIqvajhNw9Dr3NBQ8ziWyqaQBk2RrCWh6Q++Sd0b5L3RwH
38
38
  rQ==
39
- -----END CERTIFICATE-----`,Rr=new Se.X509Certificate(wr),ft=[{cert:Rr}];function Pr(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 mt=new Set,Z;function Lr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(Z&&Z.envValue===r)return Z.anchors;let e=r?Dr(r):[],t=e.length?[...ft,...e]:ft;return Z={envValue:r,anchors:t},t}function Dr(r){try{let e=Pr(Tr.readFileSync(r,"utf8"));return e.length===0&&gt(r,"no parseable certificate found"),e}catch(e){return gt(r,e instanceof Error?e.message:String(e)),[]}}function gt(r,e){mt.has(r)||(mt.add(r),console.warn(xr(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Ar.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 o=n.fingerprint256||n.fingerprint||"";if(!o||t.has(o))break;t.add(o);try{e.push(new Se.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function _r(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!Nr(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=Or(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function Nr(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&ht(r,o))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)&&ht(r,r.length-1))return!0}catch{}return!1}function ht(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 Or(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(!Mr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function kr(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"):_r(n,e,Lr())}function Mr(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let o of t.split(",")){let i=o.trim();if(!i.startsWith("DNS:"))continue;let s=i.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 Fr=8e3,Ee=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)}}},ve=class extends br.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Fr}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=X(i),a=new Ee(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,o,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let o=dt.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}parseProxyOrSettle(e,t){try{return he(e)}catch(n){return t.settle(new Error(`[GRS] ${n.message}`)),null}}createConnectionViaProxy(e,t,n,o,i){let s=this.parseProxyOrSettle(t,i);if(!s)return;let a=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${n}:${o}`);let c=Cr.request({host:s.host,port:s.port,method:"CONNECT",path:`${n}:${o}`,headers:a});i.onDestroy(()=>c.destroy()),c.on("connect",(g,v)=>{if(g.statusCode!==200){v.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${g.statusCode} ${g.statusMessage||""}`));return}i.onDestroy(()=>v.destroy()),this.startTlsOverTunnel(e,v,i,n)}),c.on("error",g=>{i.settle(new Error(`[GRS] Proxy connection failed: ${g.message}`))}),c.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=dt.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`},i=e.auth;if(i&&(i.username||i.password)){let s=`${i.username}:${i.password}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=kr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},Te=new ve({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"}],L=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var Br=["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"],$r="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",Ur="devecostudio",Gr=8e3;async function be(r){let e=[],t="";for(let i of Br){let s=await Hr(i,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(i=>i==="incomplete"))throw new L("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,o=n?`Current proxy: ${Y(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 L("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function Hr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Ur}`;p(()=>`[GRS] POST ${t}`);try{let n=await ye.post(t,{headers:{"User-Agent":$r},httpsAgent:Te,timeout:Gr}),o=ye.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):jr(o.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(o.services).length} service groups`),{outcome:"ok",services:o.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let o=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${o}`),{outcome:"network",detail:o}}}function jr(r){return Ce.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import yt from"fs";import Vr from"path";var zr="com.huawei.devecostudio.region",qr={[zr]:{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"}},Kr=1440*60*1e3,Et=new Set(["CN","HK","MO"]),Ae=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 h("RuntimeCondition",`GRS service ${e}.${t} not available`,"GRS service not available.");return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new h("RuntimeCondition","Country code not set, cannot resolve GRS","Country code not set.");if(this.countryCode==="CN"){this.services=qr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Wr(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 be(this.countryCode);this.services=t,this.resolved=!0,await Xr(this.countryCode,t)}},T=new Ae;function vt(r){return Vr.join(R(),`grs_${r}.json`)}async function Wr(r){try{let e=await yt.promises.readFile(vt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Kr?null:t}catch{return null}}async function Xr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await yt.promises.writeFile(vt(r),JSON.stringify(t),"utf8")}catch{}}var M=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 $;storageDir="";failedDir="";installId="";get disabled(){return q()||!T.isCN()}traceFileKey=Buffer.alloc(0);sessionId=St.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){d.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=E.join(e,"failed"),this.cliVersion="1.3.13-23.2",this.nodeVersion=process.version,m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0});let t=E.dirname(e);this.installId=Qe(t).replace(/-/g,""),this.traceFileKey=Be(t),nt(e),d.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,d.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,d.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,d.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return d.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 i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let n=t,o=Date.now();try{let i=await n(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=re(i);throw await this.record(e,s,!1,a),i}}async record(e,t,n,o){let i=this.buildTraceEvent(e,t,n,o);try{let s=$e(JSON.stringify(i),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
40
- `,"utf8"),We(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=ke.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:St.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,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:o,event_detail:s}}}resolveOsArch(){let e=Q.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Q.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 Q.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Q.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 E.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){d.debug("[telemetry] scheduler not started (telemetry disabled)");return}d.debug(`[telemetry] scheduler started (flush every ${V/1e3}s, retry failed every ${z/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},V)},V),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},z)},z)}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),d.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return d.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 Xe(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return d.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(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>E.join(this.failedDir,i)),o=!0;for(let i of n){let s=E.basename(i),a=Je(s);if(a!==null){if(e-a>ze){try{await m.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||d.warn("[telemetry] retry failed"),Ye(this.storageDir),o}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 o of n)K(o)&&await this.reclaimOrphan(E.join(t,o),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<qe)return;n=g.size}catch{return}let o=E.dirname(e),i=pe(E.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=E.join(o,i),c=P-await this.fileSize(a);if(n>c){try{await m.promises.unlink(s)}catch{}d.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){d.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}d.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let o=E.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await m.promises.rename(e,o)}catch{return null}return await this.touch(o),o}async mergeOrphanInto(e,t){try{await m.promises.appendFile(t,await m.promises.readFile(e))}catch(n){return d.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){d.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=>E.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>P){d.warn(`[telemetry] ${E.basename(e)} is ${t} bytes (> ${P}), 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 o;try{o=await m.promises.readFile(n,"utf8")}catch{return!1}let i=o.split(`
41
- `).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await m.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,i)}collectDecryptBatch(e,t){let n=[],o=16,i=t;for(;i<e.length&&n.length<r.MAX_BATCH;){let s=Ue(e[i],this.traceFileKey);if(s===null){i++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&o+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),o+=a,i++}return{batch:n,next:i}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let o=n,{batch:i,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(i);if(a.length===0)continue;let c=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(c,this.installId)}catch{}if(!g){d.warn("[telemetry] upload failed");let v=t.slice(o).join(`
39
+ -----END CERTIFICATE-----`,Lr=new Se.X509Certificate(Dr),dt=[{cert:Lr}];function _r(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 ft=new Set,J;function Ir(){let r=process.env.NODE_EXTRA_CA_CERTS;if(J&&J.envValue===r)return J.anchors;let e=r?Nr(r):[],t=e.length?[...dt,...e]:dt;return J={envValue:r,anchors:t},t}function Nr(r){try{let e=_r(Ar.readFileSync(r,"utf8"));return e.length===0&&mt(r,"no parseable certificate found"),e}catch(e){return mt(r,e instanceof Error?e.message:String(e)),[]}}function mt(r,e){ft.has(r)||(ft.add(r),console.warn(Pr(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Rr.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function Or(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let o=n.fingerprint256||n.fingerprint||"";if(!o||t.has(o))break;t.add(o);try{e.push(new Se.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function kr(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!Mr(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=Fr(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function Mr(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&gt(r,o))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)&&gt(r,r.length-1))return!0}catch{}return!1}function gt(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 Fr(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(!$r(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function Br(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=Or(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):kr(n,e,Ir())}function $r(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let o of t.split(",")){let i=o.trim();if(!i.startsWith("DNS:"))continue;let s=i.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,ye=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)}}},Ee=class extends wr.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Ur}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=K(i),a=new ye(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,o,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let o=pt.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}parseProxyOrSettle(e,t){try{return ge(e)}catch(n){return t.settle(new Error(`[GRS] ${n.message}`)),null}}createConnectionViaProxy(e,t,n,o,i){let s=this.parseProxyOrSettle(t,i);if(!s)return;let a=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${n}:${o}`);let c=xr.request({host:s.host,port:s.port,method:"CONNECT",path:`${n}:${o}`,headers:a});i.onDestroy(()=>c.destroy()),c.on("connect",(g,E)=>{if(g.statusCode!==200){E.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${g.statusCode} ${g.statusMessage||""}`));return}i.onDestroy(()=>E.destroy()),this.startTlsOverTunnel(e,E,i,n)}),c.on("error",g=>{i.settle(new Error(`[GRS] Proxy connection failed: ${g.message}`))}),c.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=pt.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`},i=e.auth;if(i&&(i.username||i.password)){let s=`${i.username}:${i.password}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=Br(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},ve=new Ee({keepAlive:!0});var Te=[{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"}],D=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var Gr=["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"],Hr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",jr="devecostudio",Vr=8e3;async function Ce(r){let e=[],t="";for(let i of Gr){let s=await zr(i,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(i=>i==="incomplete"))throw new D("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,o=n?`Current proxy: ${X(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 D("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function zr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${jr}`;p(()=>`[GRS] POST ${t}`);try{let n=await he.post(t,{headers:{"User-Agent":Hr},httpsAgent:ve,timeout:Vr}),o=he.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):qr(o.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(o.services).length} service groups`),{outcome:"ok",services:o.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let o=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${o}`),{outcome:"network",detail:o}}}function qr(r){return Te.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import ht from"fs";import Wr from"path";var Kr="com.huawei.devecostudio.region",Xr={[Kr]:{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"}},Yr=1440*60*1e3,yt=new Set(["CN","HK","MO"]),be=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return yt.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=Xr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Jr(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 Zr(this.countryCode,t)}},v=new be;function Et(r){return Wr.join(x(),`grs_${r}.json`)}async function Jr(r){try{let e=await ht.promises.readFile(Et(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Yr?null:t}catch{return null}}async function Zr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await ht.promises.writeFile(Et(r),JSON.stringify(t),"utf8")}catch{}}function vt(){return!z()&&v.isCN()}var M=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 F;storageDir="";failedDir="";installId="";get disabled(){return!vt()}traceFileKey=Buffer.alloc(0);sessionId=St.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){d.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.13-23.4",this.nodeVersion=process.version,m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0});let t=y.dirname(e);this.installId=Ze(t).replace(/-/g,""),this.traceFileKey=Fe(t),rt(e),d.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,d.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,d.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,d.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return d.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 i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let n=t,o=Date.now();try{let i=await n(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=this.resolveErrorCode(i);throw await this.record(e,s,!1,a),i}}resolveErrorCode(e){try{return oe(e)}catch{return null}}async record(e,t,n,o){try{let i=this.buildTraceEvent(e,t,n,o),s=Be(JSON.stringify(i),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
40
+ `,"utf8"),We(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=Oe.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:St.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,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:o,event_detail:s}}}resolveOsArch(){let e=Z.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Z.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 Z.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Z.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){d.debug("[telemetry] scheduler not started (telemetry disabled)");return}d.debug(`[telemetry] scheduler started (flush every ${j/1e3}s, retry failed every ${V/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},j)},j),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},V)},V)}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),d.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return d.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 Ke(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return d.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(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>y.join(this.failedDir,i)),o=!0;for(let i of n){let s=y.basename(i),a=Ye(s);if(a!==null){if(e-a>Ve){try{await m.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||d.warn("[telemetry] retry failed"),Xe(this.storageDir),o}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 o of n)q(o)&&await this.reclaimOrphan(y.join(t,o),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<ze)return;n=g.size}catch{return}let o=y.dirname(e),i=le(y.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=y.join(o,i),c=P-await this.fileSize(a);if(n>c){try{await m.promises.unlink(s)}catch{}d.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){d.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}d.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let o=y.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await m.promises.rename(e,o)}catch{return null}return await this.touch(o),o}async mergeOrphanInto(e,t){try{await m.promises.appendFile(t,await m.promises.readFile(e))}catch(n){return d.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){d.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>P){d.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${P}), 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 o;try{o=await m.promises.readFile(n,"utf8")}catch{return!1}let i=o.split(`
41
+ `).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await m.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,i)}collectDecryptBatch(e,t){let n=[],o=16,i=t;for(;i<e.length&&n.length<r.MAX_BATCH;){let s=$e(e[i],this.traceFileKey);if(s===null){i++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&o+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),o+=a,i++}return{batch:n,next:i}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let o=n,{batch:i,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(i);if(a.length===0)continue;let c=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(c,this.installId)}catch{}if(!g){d.warn("[telemetry] upload failed");let E=t.slice(o).join(`
42
42
  `)+`
43
- `;return await this.moveToFailed(e,v),!1}}try{await m.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let o=JSON.parse(n);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=E.basename(e,".pending"),o=E.join(this.failedDir,n),i=t.split(`
43
+ `;return await this.moveToFailed(e,E),!1}}try{await m.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let o=JSON.parse(n);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=y.basename(e,".pending"),o=y.join(this.failedDir,n),i=t.split(`
44
44
  `).filter(Boolean),s=P-await this.fileSize(o),a=this.takeNewestWithinBudget(i,s);a.length<i.length&&d.warn(`[telemetry] failed file capped at ${P} bytes, dropped ${i.length-a.length} older events`);try{a.length>0&&await m.promises.appendFile(o,a.join(`
45
45
  `)+`
46
- `,"utf8")}catch{return}try{await m.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let n=[],o=0;for(let i=e.length-1;i>=0;i--){let s=Buffer.byteLength(e[i],"utf8")+1;if(o+s>t)break;o+=s,n.push(e[i])}return n.reverse(),n}};var D=new M;import{execFile as Zi,spawn as Qi}from"child_process";import{existsSync as ts,readdirSync as rs,readFileSync as ns}from"fs";import{spawn as hs}from"child_process";import{existsSync as Es}from"fs";import{dirname as Ss,join as Ts}from"path";import{fileURLToPath as bs}from"url";var Jr=new Set(["C","POSIX"]);function xe(){let r=Zr();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),Jr.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=Qr(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function Zr(){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 Qr(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 we={"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 Re(){let r=xe();if(r)return{code:r,source:"locale"};let e=Tt();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function Tt(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=we[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import Ct from"fs";import bt from"path";import{homedir as en}from"os";var tn="country.region.xml",rn=".config",nn="deveco-cli";function At(){let r=process.env.DEVECO_CLI_DATA_DIR?R():bt.join(en(),rn,nn);return bt.join(r,tn)}function Pe(){let r=At();try{if(!Ct.existsSync(r))return null;let t=Ct.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 xt=Pe();if(xt)T.setCountryCode(xt);else{let r=Re();r&&T.setCountryCode(r.code)}if(!T.isCN())d.info("[telemetry] background upload skipped (non-CN region)");else{let r=on.join(R(),"TraceLogData",T.countryCode);D.init(r),(async()=>{try{await D.flush(),await D.retryFailed()}catch(e){d.warn("[telemetry] background upload error:",e),process.exit(1)}})()}
46
+ `,"utf8")}catch{return}try{await m.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let n=[],o=0;for(let i=e.length-1;i>=0;i--){let s=Buffer.byteLength(e[i],"utf8")+1;if(o+s>t)break;o+=s,n.push(e[i])}return n.reverse(),n}};var L=new M;import{execFile as Qi,spawn as es}from"child_process";import{existsSync as rs,readdirSync as ns,readFileSync as os}from"fs";import{spawn as ys}from"child_process";import{existsSync as Ss}from"fs";import{dirname as Ts,join as Cs}from"path";import{fileURLToPath as As}from"url";var en=new Set(["C","POSIX"]);function Ae(){let r=tn();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),en.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=rn(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function tn(){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 rn(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 xe={"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 we(){let r=Ae();if(r)return{code:r,source:"locale"};let e=Tt();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function Tt(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=xe[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import Ct from"fs";import bt from"path";import{homedir as nn}from"os";var on="country.region.xml",sn=".config",an="deveco-cli";function At(){let r=process.env.DEVECO_CLI_DATA_DIR?x():bt.join(nn(),sn,an);return bt.join(r,on)}function Re(){let r=At();try{if(!Ct.existsSync(r))return null;let t=Ct.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 xt=Re();if(xt)v.setCountryCode(xt);else{let r=we();r&&v.setCountryCode(r.code)}if(!v.isCN())d.info("[telemetry] background upload skipped (non-CN region)");else{let r=cn.join(x(),"TraceLogData",v.countryCode);L.init(r),(async()=>{try{await L.flush(),await L.retryFailed()}catch(e){d.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.13-23.2",
3
+ "version": "1.3.13-23.4",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "supportedDocsApi": 1,
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "dist",
10
10
  "templates",
11
11
  "src/resources",
12
- "NOTICE",
12
+ "THIRD-PARTY-LICENSES",
13
13
  "skills"
14
14
  ],
15
15
  "scripts": {
@@ -65,10 +65,9 @@
65
65
  "smol-toml": "^1.6.1",
66
66
  "socket.io-client": "^4.7.5",
67
67
  "ui-verification-mcp": "0.0.21",
68
- "ws": "^8.21.1",
69
68
  "xpath": "^0.0.35",
70
69
  "zod": "^4.4.3",
71
- "@deveco-test/deveco-cli-knowledgebase": "1.3.13-23.2"
70
+ "@deveco-test/deveco-cli-knowledgebase": "1.3.13-23.4"
72
71
  },
73
72
  "devDependencies": {
74
73
  "@types/adm-zip": "^0.5.8",
@@ -77,7 +76,6 @@
77
76
  "@types/node-forge": "^1.3.14",
78
77
  "@types/proper-lockfile": "^4.1.4",
79
78
  "@types/semver": "^7.7.1",
80
- "@types/ws": "^8.18.2",
81
79
  "design2arkts-engine": "0.1.0"
82
80
  }
83
81
  }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: deveco-cli
3
3
  description: >-
4
- Use 'devecocli' for HarmonyOS apps (scaffold, build, run, debug, devices, emulators, logs, docs, UI inspection, 鸿蒙开发文档, skills), including generating ArkUI pages from Pixso/Figma designs (设计稿还原). Use it if workspace has build-profile.json5 or oh-package.json5, or user mentions HarmonyOS, 鸿蒙, DevEco, ArkTS, ArkUI, docs, 鸿蒙文档, 知识, 搜索, skills, UI, UI测试, 组件调试, 预览器(HarmonyOS PC), 多设备预览器(HarmonyOS PC), 预览器截图, 视觉走查, 截图验证. If user explicitly specifies another tool, skill, or workflow, follow that choice; otherwise use 'devecocli'.
4
+ Use 'devecocli' for HarmonyOS apps (scaffold, build, run, debug, devices, emulators, logs, docs, UI inspection, 鸿蒙开发文档, skills), including generating ArkUI pages from Pixso/Figma designs (设计稿还原). Use it if workspace has build-profile.json5 or oh-package.json5, or user mentions HarmonyOS, 鸿蒙, DevEco, ArkTS, ArkUI, docs, 鸿蒙文档, 知识, 搜索, skills, UI, UI测试, 组件调试. If user explicitly specifies another tool, skill, or workflow, follow that choice; otherwise use 'devecocli'.
5
5
  Also covers on-device testing services: 测试, 检测, 内存泄漏, 稳定性, 性能, 功耗, 兼容性, DevEco Testing. When asked to test an app on a device (性能测试 / 内存泄漏 / 稳定性 / UX / 上架预检 — performance, memory leak, stability, UX, app-store precheck), run 'devecocli testing' instead of hand-rolling hdc, bm dump or SP_daemon commands.
6
6
  ---
7
7
 
@@ -9,12 +9,10 @@ description: >-
9
9
 
10
10
  `devecocli` wraps DevEco Studio's `hvigor`, `ohpm`, `hdc`, emulator toolchain, and bundled skills installer.
11
11
 
12
- Available commands: `build`, `check`, `run`, `debug`, `update`, `device`, `emulator`, `ui`, `skills`, `log`, `verify`, `create`, `init`, `serve`, `docs`, `signature`, `auth`, `design2arkts` (alias `d2a`), `testing`.
12
+ Available commands: `build`, `check`, `run`, `update`, `device`, `emulator`, `ui`, `skills`, `log`, `verify`, `create`, `init`, `serve`, `docs`, `signature`, `auth`, `design2arkts` (alias `d2a`), `testing`.
13
13
 
14
14
  **Sandbox Rule**: Commands tagged `[Outside sandbox]` must be run outside the sandbox.
15
15
 
16
- **Output streams**: Results go to stdout. Debug logs (`DEVECO_CLI_DEBUG=1`), progress, warnings, errors, and upgrade notices go to stderr; use the exit code to determine success. Commands supporting console JSON keep stdout to one JSON value with `--format json`.
17
-
18
16
  ## 1. Code → Build → Deploy → Run → Debug
19
17
 
20
18
  ### `devecocli create`
@@ -61,7 +59,6 @@ Run DevEco Code Linter checks for TS/ArkTS code.
61
59
 
62
60
  ### `devecocli check arkts`
63
61
  Run this command once after a round of edits, right before the build. Catches most ArkTS errors faster than a full build. Do not run it per edit.
64
- - Before writing or editing `.ets`/ArkTS code, and again before running this command, follow the ArkTS/ArkUI coding rules in [docs/arkts-rules.md](docs/arkts-rules.md).
65
62
  - `[files...]`: Specific `.ets` files to check. Defaults to all `.ets` files in the project.
66
63
  - `--fix`: Auto-fix high-confidence errors (e.g., missing `export` keywords) before reporting.
67
64
  - `--project <path>`: Project root directory. Defaults to auto-detection from cwd via `build-profile.json5`.
@@ -177,7 +174,7 @@ Manage connected devices — device info, app management, system control, screen
177
174
 
178
175
 
179
176
  ### `devecocli run` `[Outside sandbox]`
180
- Build, install, and launch. After a successful ability launch (and after a successful `--apply`), runs a **default smoke check**. Success prints `Smoke: PASS`; failures print `Smoke: FAIL_CRASH` or `Smoke: FAIL_BLANK` or `Smoke: FAIL_UI_OVERLAP` (crash log path via `crash_log:`, blank screenshot via `screenshot:`, overlap JSON via `FAIL_UI_OVERLAP:` at `<project>/.hvigor/smoke/<run-id>/smoke-ui-overlap-<ts>.json`) and exit non-zero. Smoke is skipped when there is no ability to launch, and for `--hotreload` / `--hotreload-apply`.
177
+ Build, install, and launch. After a successful ability launch (and after a successful `--apply`), runs a **default smoke check**. Success prints `Smoke: PASS`; failures print `Smoke: FAIL_CRASH` or `Smoke: FAIL_BLANK` (crash log path via `crash_log:`, blank screenshot via `screenshot:`) and exit non-zero. Smoke is skipped when there is no ability to launch, and for `--hotreload` / `--hotreload-apply`.
181
178
  - `--module <m1> [m2...]`: Target module(s) (auto-selected if only one runnable).
182
179
  - `--device <name|serial>`: Target device (Req if multiple connected).
183
180
  - `--product <product>` / `--build-mode <mode>`: Defaults: `default` / `debug`.
@@ -201,33 +198,18 @@ Build, install, and launch. After a successful ability launch (and after a succe
201
198
  - **Artifacts under `.hvigor/`** (shared with `--apply`): `.hvigor/<fileName>` = the changed-file list you write; `.hvigor/hotreload-watch.log` = the watch session's onBuildOutput/compile-errors (written by the background `--hotreload` process; safe to read/delete). The hot-reload marker is `<module>/build/<product>/.hotreload-mode`.
202
199
  *Ex*: background `devecocli run --module entry --hotreload` → (ready) → edit `.fontColor` in `entry/src/main/ets/pages/Index.ets` → write path to `.hvigor/changes.txt` → `devecocli run --module entry --hotreload-apply changes.txt` (UI updates without restart). When done: kill the background process + `devecocli run --hotreload stop`.
203
200
 
204
- ### `devecocli debug` `[Outside sandbox]`
205
- ArkTS debugger (breakpoints, logpoints, variable read/write, event stream) over `hdc fport` + CDP, no IDE needed. All subcommands are short RPC calls to **one global background daemon** (hidden `debug __daemon`, auto-spawned by the first debug command, exits after 30 idle minutes; one session per bundle — `SESSION_EXISTS` on conflict; mutually exclusive with IDE debugging). Everything lives under `~/.devecocli/debug/<userTag>/`: `daemon.json` and `daemon.log` (every CLI↔daemon RPC body).
206
- - **AI invocation (important)**: while the daemon is offline, any debug command — including `status` — may hang the agent shell (the spawned daemon inherits console handles). Run the first call through a file-redirection wrapper without `-Wait`, then poll the file for the `{"ok":...}` line: `Start-Process $env:ComSpec -ArgumentList '/c devecocli debug status > out.txt 2>&1' -WindowStyle Hidden`. Once the daemon is online, short commands return normally. `events --follow` streams forever — run it the same wrapper way (or a bounded background job), or collect evidence via `--logpath` instead. Judge start/attach readiness via `debug status --json` (`state:"starting"` with `phase:"building|installing|launching|connecting"`, ready at `running`/`paused`), not by scraping stdout.
207
- - `debug start [-b <bundle>] [--module <m>] [--ability <a>] [--product <p>] [--device <name|serial>] [--stop-at-entry] [--skip-build] [--logpath <file>] [--json]`: debug build → install → `aa start` (`-D` with `--stop-at-entry` so the app parks at each module entry) → `hdc fport` + CDP. Success `{"ok":true,"sessionId","pid","state",...}`: `paused` + `Break on start` with `--stop-at-entry` (parks stay until `debug resume`), else `running`. `--skip-build` reuses the last debug artifacts. `--logpath <file>` = whole-session NDJSON event journal, flushed per line (a directory auto-resolves to `<dir>/cli-debug.log`; unwritable → `LOGPATH_INVALID` before the build). With `--stop-at-entry`, the command returns `TIMEOUT` if the pause does not arrive in time or `CDP_ERROR` if the debugger disconnects.
208
- - `debug attach -b <bundle> [--pid <n>] [--module <m>] [--device <d>] [--logpath <f>] [--json]`: attach to an already-running app, no rebuild/redeploy; run inside the project (source maps come from `<module>/build/`, elsewhere `INTERNAL: Not in a valid project directory`); non-debuggable app → `ATTACH_FAILED`.
209
- - `debug status [--json]`: `Debug service: online (daemon <version>)` + one line per session — `state`, pause location `@ <path>:<line>`, worker channels (`sN.w<inst>`), `connectServer`; sessions still starting show `starting (<phase>)`.
210
- - `debug stop [--session <sN | sN.w<inst>>]`: end the session (auto-resume if paused, clean its fport rules) — **the app keeps running**. Passing a worker channel id tears down only that channel (response carries `parentSession`/`remainingWorkers`).
211
- - Breakpoints, session-scoped: `bp add --path <project-relative file> --line <n> [--column <c>] [--condition <expr>] [--hit-count <N|=N|>=N|<=N|%N>] [--log <expr>] [--level <debug|info|warn|error>] [--disabled]` → `{"ok":true,"id","kind":"breakpoint"|"logpoint",...}`; bound breakpoints carry the CDP return (`vmId`, resolved artifact `jsUrl:jsLine`), others stay pending until `scriptParsed` binds them (`verified`). Stale-source guard: source mtime newer than `sourceMaps.map` → `SOURCEMAP_RESOLVE_FAILED` (rebuild first). `bp remove (--id | --path [--line] | --all)`, `bp list [--kind ...]`, `bp enable|disable (--id | --path --line | --all)` — table changes broadcast live to every worker channel; disabled breakpoints keep the definition but never trigger. `--condition` gates by JS truthiness (operands evaluated in the VM, compared daemon-side); `--log` = **non-interrupting logpoint**: evaluate → emit `logpoint` event → auto-continue.
212
- - `debug resume [--thread <id|name|all>]` (all threads by default; `NOT_PAUSED` when already running) / `debug pause` (an idle app parks at the next executed statement) / `debug step --into|--over|--out` (needs `paused`; a `--out` landing outside debuggable code may report `TIMEOUT: step out timeout`).
213
- - `debug stack [--frame <i>] [--max <n>]` → `frames[]` with real frame indices (`--frame` = start index, 0 = innermost; `total` = full stack depth); `debug vars [--frame <n>] [--name <varPath>]` → `vars[]` (innermost `[scope]` entry = frame scope); `debug eval <expr> [--frame <n>]` → `result`; `debug set --name <v> --value <expr>` → `oldValue`/`newValue`/`vmApplied`. Paused state only.
214
- - `debug events [--follow] [--filter <type[:level],...>] [--session <id>]`: summary only without `--follow` (no history replay — use `--logpath`); live NDJSON with `--follow`. Event types: `rpc` (per request/response of every session command), `breakpoint` (mutations + async verified/failed binds), `paused` (with `bps[]` when breakpoint-caused), `resumed`, `bp-hit` (with `action:"pass"|"pause"`), `logpoint`, `console`, `terminated`, `auto-stopped` (app exit / CDP channel closed), worker `attached`/`detached`. Raw CDP frames can be journaled by setting `DEBUG_FRAME_LOG=<file>` before the daemon spawns.
215
- - **Real-device VM limits (HarmonyOS NEXT devices, e.g. Mate 60 Pro)**: `Debugger.evaluateOnCallFrame` resolves simple identifiers only — dot-paths (`this.message`) are compensated daemon-side via the `getProperties` chain (`@State` auto-unwrap), but calls (`this.calc(2)`), indexing (`arr[0]`) and unresolvable arithmetic still return `undefined`; `set` never applies — the CLI records an overlay (`vmApplied:false`) scoped to the current pause event **and frame** so `eval`/`vars` read back the set value only for that frame, until the next pause/resume. Read state via `vars`/dot-path `eval`; keep log expressions to bare variables or dot-paths. Emulators evaluate the richer forms. Not a session bug — do not rebuild around it.
216
- - Output contract: human-readable by default, `--json` = one compact JSON line (`events --follow` = NDJSON). Failures are uniformly `{"ok":false,"error":{"code","message"}}` with exit 1 (`NO_SESSION`/`SESSION_EXISTS`/`NOT_PAUSED`/`BP_NOT_FOUND`/`APP_NOT_RUNNING`/`TIMEOUT`/`DAEMON_OFFLINE`/...). Redirected human output ends with its result JSON line — pollable without `--json`.
217
- *Ex*: cold daemon: wrapper-run `debug status` → wrapper `devecocli debug start --stop-at-entry --json` → `debug resume` → `debug bp add --path entry/src/main/ets/pages/Index.ets --line 30` → trigger UI → `debug status`/`stack`/`vars` → `debug resume` → `debug stop`. Evidence: add `--logpath C:\logs\dbg.ndjson` and read the file instead of `events --follow`.
218
-
219
201
  ### `devecocli signature generate` `[Outside sandbox]`
220
- Auto-generate HarmonyOS signing materials (local p12/csr + cloud cert + profile) and write signing config to `build-profile.json5`. Supports `debug` and `release` signing types.
221
- - **Prereq**: Authenticate with `devecocli auth login --no-prompt` if needed and authorized (see Setup); run from a project directory (with `build-profile.json5`); a connected device or emulator is required for device registration (debug only; release signing skips device registration).
202
+ Auto-generate HarmonyOS debug signing materials (local p12/csr + cloud cert + profile) and write signing config to `build-profile.json5`. Release signing is not supported; apply through [AppGallery Connect](https://developer.huawei.com/consumer/cn/doc/doccenter-deveco-studio/ide-publish-app#section1079214271414) and configure release materials manually in `build-profile.json5`.
203
+ - **Prereq**: Authenticate with `devecocli auth login --no-prompt` if needed and authorized (see Setup); run from a project directory (with `build-profile.json5`); a connected device or emulator is required for device registration.
222
204
  - `--product <name>`: Product name for local p12/csr file naming (default: `default`).
223
205
  - `--team-id <id>`: Specify the team-id (default: current user's id).
224
- - `--type <type>`: Signing type: `debug` or `release` (default: `debug`). Release uses real provision endpoint and release certificate type; debug uses test provision and debug certificate.
206
+ - `--type <type>`: Optional compatibility parameter. Only `debug` is accepted (default: `debug`); `release` exits nonzero with guidance to apply through AppGallery Connect.
225
207
  - `--force`: Force regenerate even if existing materials are valid.
226
- - Generates under `~/.ohos/config/`: `.p12` keystore, `.csr`, downloaded `.cer` certificate, `.p7b` profile. Debug and release materials use separate file paths (release paths include `_release` segment).
227
- - Writes `signingConfigs` + `products` entries to `build-profile.json5` with encrypted key/store passwords (AES-128-GCM). Release configs use `<product>_release` as the config name.
228
- - Cloud cert name: `auto_debug_<teamId>.cer` (debug) or `auto_release_<teamId>.cer` (release). Key alias: `debugKey` (debug) or `releaseKey` (release).
208
+ - Generates debug materials under `~/.ohos/config/`: `.p12` keystore, `.csr`, downloaded `.cer` certificate, `.p7b` profile.
209
+ - Writes `signingConfigs` + `products` entries to `build-profile.json5` with encrypted key/store passwords (AES-128-GCM), using the product name as the config name.
210
+ - Cloud cert name: `auto_debug_<teamId>.cer`. Key alias: `debugKey`.
229
211
  - Error handling (aligned with DevEco Studio JAR): 401→re-login, 403→no AGC permission, `205389872`→cert limit, `205389904`→not Harmony user, `205389938`→provision limit, invalid `.cer`→retry.
230
- *Ex*: `devecocli signature generate --product default` / `devecocli signature generate --type release`
212
+ *Ex*: `devecocli signature generate --product default` / `devecocli signature generate --type debug`
231
213
 
232
214
 
233
215
  ### `devecocli log`
@@ -330,7 +312,7 @@ Inspect UI on a connected device. All subcommands accept `--device <name|serial>
330
312
  |---|---|---|
331
313
  | `layout` | Dump ArkUI accessibility layout tree — **visible area only** (on-screen nodes). Requires device API 20+ | `--id <id>`, `--window <windowId>`, `--all-windows`, `--depth <n>` (0=unlimited, 1=root only, 2=root+children), `--format default\|json`, `--mode full\|simplified` |
332
314
  | `window list` | List active windows | `--format default\|json`, `--all` (include system windows) |
333
- | `display list` | List displays with id, width and height (px); source of `--display <displayId>` values for `ui screenshot` (see **UI verification loop**) | `--format default\|json`, `--all` (add screen id, refresh rate, VPR, rotation columns; unreported fields render as `-`, or `null` in json) |
315
+ | `display list` | List displays with id, width and height (px) — source of `--display <displayId>` values for `ui screenshot` | `--format default\|json`, `--all` (add screen id, refresh rate, VPR, rotation columns; unreported fields render as `-`, or `null` in json) |
334
316
  | `screenshot` | Capture a screenshot of the device screen | `--display <displayId>`, required `--path <path>` (existing directory or PNG file path; relative paths supported; writable destination; no overwrite) |
335
317
  | `screenrecord` | Record the screen to an MP4 file (physical devices only; emulators are rejected) | interactive by default, or `start` / `stop` / `status`; required `--path <dir|file.mp4>` for interactive and `start`; `stop --force` stops a recording not started by this CLI; `status --format table\|json` |
336
318
  | `click [x] [y]` | Tap at the specified coordinates or node | `--id <id>` (auto-resolves to center), `--selector <expr>`, `--window <windowId>` (used with `--id` or `--selector`) |
@@ -363,25 +345,6 @@ Inspect UI on a connected device. All subcommands accept `--device <name|serial>
363
345
  - `--mode full`: full layout tree, no filtering.
364
346
  - `--mode simplified` (default): folds meaningless wrapper containers (non-root, no `id`, no text, not interactive) by lifting their surviving children up. `--depth` truncates after folding.
365
347
 
366
- **UI verification loop (预览器截图 / 视觉走查 / 截图验证)** — for verifying UI changes or capturing what the app looks like on any hdc target: a real device or emulator on every host, or the DevEco Studio **previewer** on HarmonyOS native (2in1) PC. One round: build → (re)deploy or refresh the target → screenshot → evaluate → fix → repeat, one fresh screenshot per round, until every intended change is individually confirmed to have taken effect. On the HarmonyOS PC the Studio previewer (多设备预览器) is a local system app that renders the project on a **virtual display** visible to `ui display list` and capturable with `ui screenshot --display`; on Windows/macOS/Linux there is no capturable previewer — the IDE's embedded previewer is a local desktop process, not an hdc target — use the device/emulator loop. For on-device functional UI testing use `devecocli verify`.
367
-
368
- **Real device or emulator** (any host):
369
- 1. `devecocli run` — builds, installs, and launches in one command (auto-selects a single connected target; `--device <name|serial>` when several)
370
- 2. `devecocli ui screenshot --path <existing-dir>/<fresh-name>.png` — captures the main screen by default; `--display <displayId>` targets a specific display (ids from `devecocli ui display list`). The destination directory must already exist and existing files are never overwritten — use a new file name each round.
371
-
372
- **DevEco Studio previewer** (HarmonyOS PC only):
373
- 1. `devecocli build`
374
- 2. Start/refresh the previewer in DevEco Studio — this CLI has no previewer launch command.
375
- 3. Self-connect hdc to the local machine if not already connected: `hdc tconn 127.0.0.1:<port>` (port from Settings → System → Developer options → Wireless debugging).
376
- 4. Resolve the previewer's virtual display id: `devecocli ui display list` — display `0` is the main screen; the previewer appears as an extra entry.
377
- 5. Capture it: `devecocli ui screenshot --display <virtualDisplayId> --path <existing-dir>/<fresh-name>.png`.
378
-
379
- **Virtual display id rules** (previewer loop): ids are dynamically assigned — re-query `ui display list` after **every** previewer restart; never reuse an earlier id. Restarts also leave old virtual displays **lingering**, so the list accumulates stale ids (e.g. `1005/1006/1007`). The authoritative id is the **DisplayId of the app's window** in `devecocli ui window list --all` — the window named after the app (e.g. `myapplication0`), newest pid; IDE windows (`devecostudio0/1`) sit on display `0`. If the installed CLI has no `display` subcommand, take the app window's DisplayId column from `ui window list --all` directly.
380
-
381
- **Screenshot evaluation calibration**: text content, element presence, and relative before/after changes are reliable; **absolute position/alignment claims are not** — evaluators routinely misreport centered content as "offset". Derive position and color facts from pixels (Node's built-in zlib can decode the PNG; a non-background bounding-box center ≈ (50%, 50%) means centered) and let pixel data override conflicting evaluator claims.
382
-
383
- *Ex*: `devecocli ui display list` → `devecocli ui screenshot --display 1005 --path ./shots/round1.png` (directory already exists; new file name per round)
384
-
385
348
  ### `devecocli testing` `[Outside sandbox]`
386
349
 
387
350
  Run DevEco Testing detection services on a connected device.
@@ -490,6 +453,8 @@ Use `devecocli d2a --help` for Pixso/Figma design-to-ArkTS workflows and standal
490
453
 
491
454
  Solution design supports UI pages only; repository analysis covers the target page and its dependencies. The Pixso workflow proceeds from repository understanding to page design. Follow the Controller-returned stage IDs; they are not guaranteed to be consecutive.
492
455
 
456
+ Submit every workflow stage with `devecocli d2a stage-complete --run-dir <runDir> --stage <N> --result passed|blocked [--reason-code <code>]`: it delegates to the same Controller (identical output and exit code) and reports one event per submission — a delivery event for a first-time final completion, a stage-failure event for `blocked` or a non-zero exit. `init`, `status`, `stage-start` and `confirm` still call the Controller script directly.
457
+
493
458
  ## 3. Maintenance
494
459
 
495
460
  - **`devecocli update`** `[Outside sandbox]`: Update CLI to latest version. npm always runs in global-config mode (`NPM_CONFIG_LOCATION=global`): the project `.npmrc` never applies to the update chain (registry/proxy/CA come from user-level config only); mirrors must be configured in the user-level `~/.npmrc`.
@@ -507,9 +472,6 @@ Solution design supports UI pages only; repository analysis covers the target pa
507
472
  `devecocli build` -> `devecocli emulator list` -> `devecocli emulator start "Name"` -> `devecocli run`
508
473
  - **Diagnose crash**:
509
474
  `devecocli log --crash --bundle-name <bundle>` (device), or `devecocli log --crash --path <faultlog file|dir> --format report` (local analysis), or `devecocli log --stack --path <sample_stacks file>` (freeze hotspot analysis)
510
- - **Verify UI changes with screenshots (视觉走查)**:
511
- `devecocli run` -> `devecocli ui screenshot --path <existing-dir>/<fresh-name>.png` -> evaluate & fix -> repeat
512
- Previewer variant (HarmonyOS PC only): refresh the previewer in DevEco Studio (`hdc tconn 127.0.0.1:<port>` first) -> `devecocli ui display list` (re-query after every previewer restart) -> `devecocli ui screenshot --display <id> --path <existing-dir>/<fresh-name>.png` -> repeat
513
475
  - **Release build**:
514
476
  `devecocli build --product oversea --build-mode release`
515
477
  - **First-time signing setup** (login authorized; user completes browser authentication):