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

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 (38) hide show
  1. package/README.md +155 -25
  2. package/THIRD-PARTY-LICENSES +32 -3
  3. package/dist/cli.js +231 -214
  4. package/dist/internal/telemetry-upload-background.js +10 -10
  5. package/package.json +4 -2
  6. package/skills/deveco-cli/SKILL.md +56 -8
  7. package/skills/index.json +2 -2
  8. package/templates/application/template.json +8 -0
  9. package/templates/native-cpp/AppScope/app.json5 +10 -0
  10. package/templates/native-cpp/AppScope/resources/base/element/string.json +8 -0
  11. package/templates/native-cpp/AppScope/resources/base/media/layered_image.json +7 -0
  12. package/templates/native-cpp/build-profile.json5 +43 -0
  13. package/templates/native-cpp/code-linter.json5 +32 -0
  14. package/templates/native-cpp/entry/build-profile.json5 +48 -0
  15. package/templates/native-cpp/entry/gitignore.txt +6 -0
  16. package/templates/native-cpp/entry/hvigorfile.ts +6 -0
  17. package/templates/native-cpp/entry/obfuscation-rules.txt +20 -0
  18. package/templates/native-cpp/entry/oh-package.json5 +11 -0
  19. package/templates/native-cpp/entry/src/main/cpp/CMakeLists.txt +15 -0
  20. package/templates/native-cpp/entry/src/main/cpp/napi_init.cpp +67 -0
  21. package/templates/native-cpp/entry/src/main/cpp/types/libentry/Index.d.ts +16 -0
  22. package/templates/native-cpp/entry/src/main/cpp/types/libentry/oh-package.json5 +6 -0
  23. package/templates/native-cpp/entry/src/main/ets/entryability/EntryAbility.ets +63 -0
  24. package/templates/native-cpp/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +31 -0
  25. package/templates/native-cpp/entry/src/main/ets/pages/Index.ets +26 -0
  26. package/templates/native-cpp/entry/src/main/module.json5 +50 -0
  27. package/templates/native-cpp/entry/src/main/resources/base/element/color.json +8 -0
  28. package/templates/native-cpp/entry/src/main/resources/base/element/float.json +8 -0
  29. package/templates/native-cpp/entry/src/main/resources/base/element/string.json +16 -0
  30. package/templates/native-cpp/entry/src/main/resources/base/media/layered_image.json +7 -0
  31. package/templates/native-cpp/entry/src/main/resources/base/profile/backup_config.json +3 -0
  32. package/templates/native-cpp/entry/src/main/resources/base/profile/main_pages.json +5 -0
  33. package/templates/native-cpp/entry/src/main/resources/dark/element/color.json +8 -0
  34. package/templates/native-cpp/gitignore.txt +13 -0
  35. package/templates/native-cpp/hvigor/hvigor-config.json5 +23 -0
  36. package/templates/native-cpp/hvigorfile.ts +6 -0
  37. package/templates/native-cpp/oh-package.json5 +10 -0
  38. package/templates/native-cpp/template.json +8 -0
@@ -1,8 +1,8 @@
1
- import _r from"path";import*as R from"fs";import*as ve from"path";import{homedir as ct}from"os";import*as ge from"fs";import*as v from"path";function z(r){let e=v.resolve(r),t=[],n=e;for(;;)try{let i=ge.realpathSync(n);return t.length===0?i:v.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=v.dirname(n);if(o===n)return e;t.push(v.basename(n)),n=o}}function q(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function he(r){let e=q(r);if(!e)throw new Error("Path must not be empty.");return z(e)}var ut="deveco-cli",ye,K=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function lt(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":q(r))||ve.join(ct(),".local","share",ut);try{return he(t)}catch(n){throw new K(n instanceof Error?n.message:String(n))}}function C(){if(ye!==void 0)return ye;let r=lt();try{if(R.existsSync(r))return R.realpathSync(r)}catch{}return r}import rt from"crypto";import m from"fs";import V from"os";import y from"path";import dt from"https";var Ee={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var N=class r{static ENDPOINT=Ee.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),n=t?.code??t?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(e,t,n,i){let o=new URL(e);return new Promise((s,a)=>{let l=dt.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},g=>{let h=[];g.on("data",S=>h.push(S)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(h).toString("utf8")})})});l.on("timeout",()=>{l.destroy(new Error("request timeout"))}),l.on("error",a),l.write(n),l.end()})}};var Se={identity:r=>r,camelCase:r=>r,snakeCase:r=>r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},W=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??Se.identity,n=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=n[o]??t(o);i[a]=this.transform(s)}return i}},be=new W({namingStrategy:Se.snakeCase,fieldNames:{}});import P from"crypto";import I from"fs";import ft from"path";var k="aes-256-gcm",mt=12,gt="deveco-cli-trace-file",ht="trace-file-secret",Ce=32;function Te(r){try{let e=I.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Ce?e:null}catch{return null}}function Ae(r){let e=ft.join(r,ht),t=Te(e);if(t)return X(t);let n=P.randomBytes(Ce).toString("base64");try{I.mkdirSync(r,{recursive:!0});try{I.writeFileSync(e,n,{flag:"wx"})}catch{let i=Te(e);if(i)return X(i);I.writeFileSync(e,n)}}catch{}return X(n)}function X(r){return P.createHash("sha256").update(gt).update(r).digest()}function we(r,e){let t=P.randomBytes(mt),n=P.createCipheriv(k,e,t),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o={version:1,algorithm:k,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(o)}function xe(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!yt(t))return r;try{let n=P.createDecipheriv(k,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function yt(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===k&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as d from"fs";import*as M from"path";import*as D from"os";import*as b from"path";import on from"json5";var un=64*1024;function Re(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??b.join(D.homedir(),"AppData","Local");return b.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?b.join(D.homedir(),"Library","Logs","devecocli-mcp-server"):b.join(D.homedir(),".local","share","devecocli-mcp-server","logs")}var Pe="mcp-server.log",vt="mcp-server",Et={maxSize:10*1024*1024,maxFiles:4},Y=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...Et,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Re(),this.currentLogFile=M.join(this.logDir,Pe),d.existsSync(this.logDir)||d.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}getRotatedFileName(e,t){return M.join(this.logDir,`${vt}-${e}.log.${t}`)}fileExists(e){try{return d.accessSync(e,d.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=d.readdirSync(this.logDir),t=[];for(let i of e)if(i===Pe||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=M.join(this.logDir,i),s=d.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<t.length;i++)try{d.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&d.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&d.renameSync(o,s)}let n=this.getRotatedFileName(e,1);d.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=d.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=d.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{d.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="object"?JSON.stringify(l,null,2):String(l)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${o}
2
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let l=Buffer.from(a);d.writeSync(this.fd,l),this.checkRotation(l.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{d.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},L=null;function St(r=!1){L&&L.dispose(),L=new Y(r)}function O(){return L||St(!1),L}var f={debug:(r,...e)=>O().debug(r,...e),info:(r,...e)=>O().info(r,...e),warn:(r,...e)=>O().warn(r,...e),error:(r,...e)=>O().error(r,...e)};import Le from"fs";import bt from"path";var F=300*1e3,B=3600*1e3,_e=10080*60*1e3,A=8*1024*1024,Ne=3600*1e3,De=".pending",Tt=/\.reclaim-\d+-\d+$/;function $(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var Ct="upload-state.json";function Ie(r){return bt.join(r,Ct)}function At(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function J(r){try{let e=Le.readFileSync(Ie(r),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return At()}}function Z(r,e){try{Le.writeFileSync(Ie(r),JSON.stringify(e),"utf8")}catch{}}function ke(r){let e=J(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Z(r,e))}function Oe(r){let e=J(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,Z(r,e)}function Me(r){let e=J(r);e.lastRetryAt=Date.now(),Z(r,e)}function Fe(r){let e=r.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function Q(r){if(!r.startsWith("telemetry-"))return null;let e=Tt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(De))return null;let n=t.slice(0,-De.length);return n.endsWith(".txt")?n:null}function Be(r){return Q(r)!==null}import wt from"crypto";import U from"fs";import xt from"path";var Rt="install-id";function Pt(r){return xt.join(r,Rt)}function $e(r){try{let e=U.readFileSync(r,"utf8").trim();return Dt(e)?e:null}catch{return null}}function Dt(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r)}function Ue(r){let e=Pt(r),t=$e(e);if(t)return t;let n=wt.randomUUID();try{U.mkdirSync(r,{recursive:!0});try{U.writeFileSync(e,n,{flag:"wx"})}catch{let i=$e(e);if(i)return i;U.writeFileSync(e,n)}}catch{}return n}import Ut from"axios";var Ge={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ee={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Lt={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function _t(r){try{return new URL(r)}catch{return null}}function G(r){var e=(typeof r=="string"?_t(r):r)||{},t=e.protocol,n=e.host,i=e.port;if(typeof n!="string"||!n||typeof t!="string"||(t=t.split(":",1)[0],n=n.replace(/:\d*$/,""),i=parseInt(i)||Lt[t]||0,!Nt(n,i)))return"";var o=te(t+"_proxy")||te("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Nt(r,e){var t=te("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(n){if(!n)return!0;var i=n.match(/^(.+):(\d+)$/),o=i?i[1]:n,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!r.endsWith(o)):r!==o}):!0}function te(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}import{spawn as Ve}from"child_process";import*as T from"fs";import*as ze from"os";import*as H from"path";var qe=6e4;async function It(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await He(r,"ProxyServer");if(!e)return null;let t=await He(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function He(r,e){return new Promise(t=>{let n=Ve("reg.exe",["query",r,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";n.stdout.on("data",o=>{i+=o.toString()}),n.on("error",()=>t(null)),n.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function kt(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function Ot(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function je(r){let e={},t=0,n="";for(let i of r.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),n=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:n,headers:e}}function Mt(r,e,t,n){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((r.timeoutMs??qe)/1e3)))];return r.method&&r.method!=="GET"&&i.push("-X",r.method),r.data!==void 0&&i.push("--data-binary",r.data),i.push(...Ft(r.headers,r.data!==void 0)),n?(i.push("--dump-header",t),i.push("--output",n)):i.push("--include"),i.push(r.url),i}function Ft(r,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),n=[],i=!1;for(let[o,s]of Object.entries(r??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||n.push("-H",`${o}: ${s}`)}return e&&!i&&n.push("-H","Content-Type: application/json"),n}function Bt(r,e,t){if(t){let g=T.readFileSync(e,"utf8"),h=T.readFileSync(t),S=je(g);return{statusCode:S.statusCode,statusText:S.statusText,body:h.toString("base64"),headers:S.headers,bodyBuffer:h}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let i=r.slice(n),o=i.indexOf(`\r
1
+ import Vr from"path";import*as L from"fs";import*as Re from"path";import{homedir as Et}from"os";import*as Ae from"fs";import*as E from"path";function Y(r){let e=E.resolve(r),t=[],n=e;for(;;)try{let o=Ae.realpathSync(n);return t.length===0?o:E.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=E.dirname(n);if(i===n)return e;t.push(E.basename(n)),n=i}}function J(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function xe(r){let e=J(r);if(!e)throw new Error("Path must not be empty.");return Y(e)}var vt="deveco-cli",we,Z=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function St(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":J(r))||Re.join(Et(),".local","share",vt);try{return xe(t)}catch(n){throw new Z(n instanceof Error?n.message:String(n))}}function b(){if(we!==void 0)return we;let r=St();try{if(L.existsSync(r))return L.realpathSync(r)}catch{}return r}import dt from"crypto";import m from"fs";import X from"os";import h from"path";import Ct from"https";var Pe={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var k=class r{static ENDPOINT=Pe.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 l=Ct.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 y=[];g.on("data",D=>y.push(D)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(y).toString("utf8")})})});l.on("timeout",()=>{l.destroy(new Error("request timeout"))}),l.on("error",a),l.write(n),l.end()})}};var A=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function Q(r){if(r instanceof A)return r.traceMessage;if(r instanceof Error){let e=r.code;return typeof e=="string"&&e!==""?e:r.name}return"UnknownError"}function ee(r,e){return`${r}:${e}`}var x=class extends A{category;constructor(e,t,n,o){super(t,n,o),this.name="CategorizedTraceError",this.category=e}};function T(...r){return e=>r.includes(e.name)}function M(r,...e){return t=>{let n=t.code;return t.name===r&&typeof n=="string"&&e.includes(n)}}function bt(r){return r.code==="ETIMEDOUT"||/timeout/i.test(r.name)}function At(r){let e=r.code;return r.name==="ScreenRecordError"&&typeof e=="string"&&e.endsWith("_TIMEOUT")}var xt=[{category:"Timeout",match:bt},{category:"Internal",match:T("ExecaError")},{category:"RuntimeCondition",match:T("CacheDirError","DocPathSafetyError")},{category:"InvalidArgument",match:T("SelectorParseError")},{category:"InvalidArgument",match:T("InvalidApiLevelError")},{category:"InvalidArgument",match:T("TemplateNotFoundError")},{category:"InvalidArgument",match:T("InvalidArgumentError")},{category:"InvalidArgument",match:M("ScreenRecordError","INVALID_ARGUMENT","INVALID_RECORDING_PATH")},{category:"Timeout",match:At},{category:"InvalidArgument",match:M("FaultLogError","INVALID_ARGUMENTS","INVALID_INPUT","INPUT_OVERSIZED")},{category:"RuntimeCondition",match:M("FaultLogError","FILE_NOT_FOUND","UNRECOGNIZED_LOG")},{category:"Internal",match:M("FaultLogError","INTERNAL_ERROR")},{category:"RuntimeCondition",match:T("GrsError")}];function wt(r){return xt.find(t=>t.match(r))?.category??"Other"}function te(r){if(r instanceof x)return ee(r.category,r.traceMessage);let e=r instanceof Error?wt(r):"Other";return ee(e,Q(r))}var De={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()},re=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??De.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}},Le=new re({namingStrategy:De.snakeCase,fieldNames:{}});import _ from"crypto";import F from"fs";import Rt from"path";var B="aes-256-gcm",Pt=12,Dt="deveco-cli-trace-file",Lt="trace-file-secret",Ne=32;function _e(r){try{let e=F.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Ne?e:null}catch{return null}}function Ie(r){let e=Rt.join(r,Lt),t=_e(e);if(t)return ne(t);let n=_.randomBytes(Ne).toString("base64");try{F.mkdirSync(r,{recursive:!0});try{F.writeFileSync(e,n,{flag:"wx"})}catch{let o=_e(e);if(o)return ne(o);F.writeFileSync(e,n)}}catch{}return ne(n)}function ne(r){return _.createHash("sha256").update(Dt).update(r).digest()}function Oe(r,e){let t=_.randomBytes(Pt),n=_.createCipheriv(B,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i={version:1,algorithm:B,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(i)}function ke(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!_t(t))return r;try{let n=_.createDecipheriv(B,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===B&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as d from"fs";import*as U from"path";import*as N from"os";import*as S from"path";import bn from"json5";var Rn=64*1024;function Me(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(N.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(N.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(N.homedir(),".local","share","devecocli-mcp-server","logs")}var Fe="mcp-server.log",Nt="mcp-server",It={maxSize:10*1024*1024,maxFiles:4},oe=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={...It,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Me(),this.currentLogFile=U.join(this.logDir,Fe),d.existsSync(this.logDir)||d.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${o}`}getRotatedFileName(e,t){return U.join(this.logDir,`${Nt}-${e}.log.${t}`)}fileExists(e){try{return d.accessSync(e,d.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=d.readdirSync(this.logDir),t=[];for(let o of e)if(o===Fe||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=U.join(this.logDir,o),s=d.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{d.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)&&d.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)&&d.renameSync(i,s)}let n=this.getRotatedFileName(e,1);d.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=d.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=d.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{d.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let o=n.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="object"?JSON.stringify(l,null,2):String(l)).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 l=Buffer.from(a);d.writeSync(this.fd,l),this.checkRotation(l.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{d.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},I=null;function Ot(r=!1){I&&I.dispose(),I=new oe(r)}function $(){return I||Ot(!1),I}var f={debug:(r,...e)=>$().debug(r,...e),info:(r,...e)=>$().info(r,...e),warn:(r,...e)=>$().warn(r,...e),error:(r,...e)=>$().error(r,...e)};import $e from"fs";import kt from"path";var G=300*1e3,H=3600*1e3,Ue=10080*60*1e3,w=8*1024*1024,Ge=3600*1e3,Be=".pending",Mt=/\.reclaim-\d+-\d+$/;function j(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var Ft="upload-state.json";function He(r){return kt.join(r,Ft)}function Bt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ie(r){try{let e=$e.readFileSync(He(r),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return Bt()}}function se(r,e){try{$e.writeFileSync(He(r),JSON.stringify(e),"utf8")}catch{}}function je(r){let e=ie(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),se(r,e))}function Ve(r){let e=ie(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,se(r,e)}function ze(r){let e=ie(r);e.lastRetryAt=Date.now(),se(r,e)}function qe(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 ae(r){if(!r.startsWith("telemetry-"))return null;let e=Mt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(Be))return null;let n=t.slice(0,-Be.length);return n.endsWith(".txt")?n:null}function Ke(r){return ae(r)!==null}import $t from"crypto";import V from"fs";import Ut from"path";var Gt="install-id";function Ht(r){return Ut.join(r,Gt)}function We(r){try{let e=V.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 Xe(r){let e=Ht(r),t=We(e);if(t)return t;let n=$t.randomUUID();try{V.mkdirSync(r,{recursive:!0});try{V.writeFileSync(e,n,{flag:"wx"})}catch{let o=We(e);if(o)return o;V.writeFileSync(e,n)}}catch{}return n}import tr from"axios";var Ye={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ce={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 Vt={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function zt(r){try{return new URL(r)}catch{return null}}function z(r){var e=(typeof r=="string"?zt(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)||Vt[t]||0,!qt(n,o)))return"";var i=ue(t+"_proxy")||ue("all_proxy");return i&&i.indexOf("://")===-1&&(i=t+"://"+i),i}function qt(r,e){var t=ue("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 ue(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}function q(r){try{let e=new URL(r);return`${e.protocol}//${e.host}`}catch{return"<redacted>"}}import{spawn as Qe}from"child_process";import*as C from"fs";import*as et from"os";import*as K from"path";var tt=6e4;async function Kt(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Je(r,"ProxyServer");if(!e)return null;let t=await Je(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Je(r,e){return new Promise(t=>{let n=Qe("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 Wt(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function Xt(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ze(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 Yt(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??tt)/1e3)))];return r.method&&r.method!=="GET"&&o.push("-X",r.method),r.data!==void 0&&o.push("--data-binary",r.data),o.push(...Jt(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 Jt(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 Zt(r,e,t){if(t){let g=C.readFileSync(e,"utf8"),y=C.readFileSync(t),D=Ze(g);return{statusCode:D.statusCode,statusText:D.statusText,body:y.toString("base64"),headers:D.headers,bodyBuffer:y}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let o=r.slice(n),i=o.indexOf(`\r
3
3
  \r
4
- `);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),l=je(s);return{statusCode:l.statusCode,statusText:l.statusText,body:a,headers:l.headers}}async function Ke(r){if(process.platform!=="win32")return null;let e=kt()??await It();if(!e)return null;let t;r.binary&&(t=T.mkdtempSync(H.join(ze.tmpdir(),"curl-")));let n=t?H.join(t,"header.tmp"):void 0,i=t?H.join(t,"body.tmp"):void 0;try{let o=Mt(r,e,n,i),s=await $t(o,r.timeoutMs);return!s||s.code!==0?null:Bt(s.stdout,n,i)}catch{return null}finally{t&&T.rmSync(t,{recursive:!0,force:!0})}}function $t(r,e){let t=Ot();return new Promise(n=>{let i=Ve(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??qe);i.stdout.on("data",l=>{o+=l.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),i.on("close",l=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:l??-1,stdout:o})})})}function Gt(r){let e=new URL(r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var re=class{client;constructor(){let e={timeout:Ge.HTTP_TIMEOUT_MS,headers:{"User-Agent":ee.USER_AGENT,"accept-language":ee.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Ut.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=G(t.url??"");return t.proxy=n?Gt(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`,i=new Error(`${t.message}
5
- ${n}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"GET",t)}}async post(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,signal:t?.signal,maxContentLength:t?.maxContentLength,maxBodyLength:t?.maxBodyLength,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw n}}async postAllowFailure(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}async deleteAllowFailure(e,t){try{let n=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{return await this.requestBinary(e,t)}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw n}}async requestBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(n.data);return{statusCode:n.status,statusText:n.statusText??"",buffer:i,body:i.toString("utf8")}}async withCurlFallback(e,t,n,i){let o=await this.tryCurlFallback(e,t,n,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,n,i,o=!1){if(Ht(i)||process.platform!=="win32"||!(e instanceof Error)||!jt(e))return null;let s,a=t;return n==="GET"?i?.params&&(a=Vt(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Ke({url:a,method:n,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},ne=new re;function Ht(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function jt(r){if(r.response?.status===407)return!0;let e=r.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:r.code==="SELF_SIGNED_CERT_IN_CHAIN"||r.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||r.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||r.code==="CERT_HAS_EXPIRED"||r.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function Vt(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let n=t.toString();if(!n)return r;let i=r.includes("?")?"&":"?";return`${r}${i}${n}`}import{AsyncLocalStorage as zt}from"async_hooks";var qt=new zt;function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;qt.getStore()?console.error(`[DEBUG] ${e}`):console.log(`[DEBUG] ${e}`)}}import Kt from"fs";import Wt from"http";import Xt from"https";import Yt from"path";import We from"tls";import se from"crypto";import{URL as Jt}from"url";import{yellow as Zt}from"colorette";var Qt=`-----BEGIN CERTIFICATE-----
4
+ `);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),l=Ze(s);return{statusCode:l.statusCode,statusText:l.statusText,body:a,headers:l.headers}}async function rt(r){if(process.platform!=="win32")return null;let e=Wt()??await Kt();if(!e)return null;let t;r.binary&&(t=C.mkdtempSync(K.join(et.tmpdir(),"curl-")));let n=t?K.join(t,"header.tmp"):void 0,o=t?K.join(t,"body.tmp"):void 0;try{let i=Yt(r,e,n,o),s=await Qt(i,r.timeoutMs);return!s||s.code!==0?null:Zt(s.stdout,n,o)}catch{return null}finally{t&&C.rmSync(t,{recursive:!0,force:!0})}}function Qt(r,e){let t=Xt();return new Promise(n=>{let o=Qe(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="",s=!1,a=setTimeout(()=>{s||(s=!0,o.kill())},e??tt);o.stdout.on("data",l=>{i+=l.toString()}),o.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),o.on("close",l=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:l??-1,stdout:i})})})}function pe(r){let e=new URL(r),t=nt(e.username,r),n=nt(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 nt(r,e){try{return decodeURIComponent(r)}catch{throw new Error(`Invalid proxy URL ${JSON.stringify(q(e))}: malformed percent-encoding in credentials. Percent-encode special characters (e.g. '@' as '%40') in the proxy URL.`)}}function rr(r,e){return r==="ETIMEDOUT"||r==="ECONNABORTED"&&/timeout/i.test(e)}function nr(r){let e=`Network connection failed (${r.code}). Please check your proxy configuration or network settings`,t=new x(rr(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 le=class{client;constructor(){let e={timeout:Ye.HTTP_TIMEOUT_MS,headers:{"User-Agent":ce.USER_AGENT,"accept-language":ce.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=tr.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=z(t.url??"");return t.proxy=n?pe(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{throw nr(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(or(o)||process.platform!=="win32"||!(e instanceof Error)||!ir(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)),rt({url:a,method:n,data:s,headers:o?.headers,timeoutMs:o?.timeout,binary:i})}},de=new le;function or(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function ir(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 ar from"fs";import cr from"http";import ur from"https";import lr from"path";import ot from"tls";import ge 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-----`,er=new se.X509Certificate(Qt),Xe=[{cert:er}];function tr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new se.X509Certificate(n)})}catch{}return e}var Ye=new Set,j;function rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(j&&j.envValue===r)return j.anchors;let e=r?nr(r):[],t=e.length?[...Xe,...e]:Xe;return j={envValue:r,anchors:t},t}function nr(r){try{let e=tr(Kt.readFileSync(r,"utf8"));return e.length===0&&Je(r,"no parseable certificate found"),e}catch(e){return Je(r,e instanceof Error?e.message:String(e)),[]}}function Je(r,e){Ye.has(r)||(Ye.add(r),console.warn(Zt(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Yt.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function ir(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let i=n.fingerprint256||n.fingerprint||"";if(!i||t.has(i))break;t.add(i);try{e.push(new se.X509Certificate(n.raw))}catch{break}let o=n.issuerCertificate??null;if(o===r)break;n=o}return e}function or(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!sr(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=ar(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function sr(r,e){for(let n of e){let i=r.findIndex(o=>o.fingerprint256===n.cert.fingerprint256);if(i>=0&&Ze(r,i))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&Ze(r,r.length-1))return!0}catch{}return!1}function Ze(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function ar(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!ur(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function cr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=ir(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):or(n,e,rr())}function ur(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let i of t.split(",")){let o=i.trim();if(!o.startsWith("DNS:"))continue;let s=o.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),l=n.slice(0,-a.length);if(n.endsWith(a)&&l.length>0&&!l.includes("."))return!0}}return!1}var lr=8e3,ie=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let n of this.destroyers)try{n()}catch{}this.callback(e,t)}}},oe=class extends Xt.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??lr}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=G(o),a=new ie(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,i,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let i=We.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,n),i}createConnectionViaProxy(e,t,n,i,o){let s;try{s=new Jt(t)}catch{o.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),l=this.buildProxyHeaders(s,n,i);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let g=Wt.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:l});o.onDestroy(()=>g.destroy()),g.on("connect",(h,S)=>{if(h.statusCode!==200){S.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}o.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,o,n)}),g.on("error",h=>{o.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,i){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=We.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,n,i)}buildProxyHeaders(e,t,n){let i={Host:`${t}:${n}`};if(e.username||e.password){let o=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(o).toString("base64")}`}return i}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let i=cr(e,n);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},ae=new oe({keepAlive:!0});var ce=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],w=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var pr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],dr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",fr="devecostudio",mr=8e3;async function ue(r){let e=[],t="";for(let o of pr){let s=await gr(o,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new w("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new w("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function gr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${fr}`;p(()=>`[GRS] POST ${t}`);try{let n=await ne.post(t,{headers:{"User-Agent":dr},httpsAgent:ae,timeout:mr}),i=ne.parseJson(n);return i.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):hr(i.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let i=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${i}`),{outcome:"network",detail:i}}}function hr(r){return ce.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import Qe from"fs";import yr from"path";var vr="com.huawei.devecostudio.region",Er={[vr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},Sr=1440*60*1e3,et=new Set(["CN","HK","MO"]),le=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return et.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=Er,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await br(this.countryCode);if(e){this.services=e.services,this.resolved=!0,p(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}p(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await ue(this.countryCode);this.services=t,this.resolved=!0,await Tr(this.countryCode,t)}},E=new le;function tt(r){return yr.join(C(),`grs_${r}.json`)}async function br(r){try{let e=await Qe.promises.readFile(tt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Sr?null:t}catch{return null}}async function Tr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await Qe.promises.writeFile(tt(r),JSON.stringify(t),"utf8")}catch{}}var _=class r{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new N;storageDir="";failedDir="";installId="";get disabled(){return $()||!E.isCN()}traceFileKey=Buffer.alloc(0);sessionId=rt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.11-Test.6",this.nodeVersion=process.version,this.installId=Ue(e).replace(/-/g,""),this.traceFileKey=Ae(e),m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0}),f.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return f.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=we(JSON.stringify(o),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
40
- `,"utf8"),ke(this.storageDir)}catch{}}buildTraceEvent(e,t,n,i){let o=`${r.EVENT_PREFIX}${e.event}`,s=be.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:rt.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:n,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=V.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=V.release().split(".");return(parseInt(e[e.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return V.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(V.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}currentFile(){return y.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.debug("[telemetry] scheduler not started (telemetry disabled)");return}f.debug(`[telemetry] scheduler started (flush every ${F/1e3}s, retry failed every ${B/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},F)},F),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},B)},B)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),f.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return f.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return Oe(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return f.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await m.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>y.join(this.failedDir,o)),i=!0;for(let o of n){let s=y.basename(o),a=Fe(s);if(a!==null){if(e-a>_e){try{await m.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||f.warn("[telemetry] retry failed"),Me(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await m.promises.readdir(t)}catch{continue}for(let i of n)Be(i)&&await this.reclaimOrphan(y.join(t,i),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<Ne)return;n=g.size}catch{return}let i=y.dirname(e),o=Q(y.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=y.join(i,o),l=A-await this.fileSize(a);if(n>l){try{await m.promises.unlink(s)}catch{}f.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${l})`);return}if(await this.mergeOrphanInto(s,a)){f.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}f.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let i=y.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await m.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await m.promises.appendFile(t,await m.promises.readFile(e))}catch(n){return f.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){f.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await m.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await m.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await m.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>y.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>A){f.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${A}), dropped without uploading`);try{await m.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await m.promises.rename(e,n)}catch{return!1}await this.touch(n);let i;try{i=await m.promises.readFile(n,"utf8")}catch{return!1}let o=i.split(`
41
- `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await m.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,o)}collectDecryptBatch(e,t){let n=[],i=16,o=t;for(;o<e.length&&n.length<r.MAX_BATCH;){let s=xe(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&i+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),i+=a,o++}return{batch:n,next:o}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let i=n,{batch:o,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let l=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(l,this.installId)}catch{}if(!g){f.warn("[telemetry] upload failed");let h=t.slice(i).join(`
39
+ -----END CERTIFICATE-----`,fr=new ge.X509Certificate(dr),it=[{cert:fr}];function mr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new ge.X509Certificate(n)})}catch{}return e}var st=new Set,W;function gr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(W&&W.envValue===r)return W.anchors;let e=r?hr(r):[],t=e.length?[...it,...e]:it;return W={envValue:r,anchors:t},t}function hr(r){try{let e=mr(ar.readFileSync(r,"utf8"));return e.length===0&&at(r,"no parseable certificate found"),e}catch(e){return at(r,e instanceof Error?e.message:String(e)),[]}}function at(r,e){st.has(r)||(st.add(r),console.warn(pr(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${lr.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function yr(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 ge.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function Er(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!vr(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=Sr(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function vr(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&ct(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)&&ct(r,r.length-1))return!0}catch{}return!1}function ct(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 Sr(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(!Cr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function Tr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=yr(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):Er(n,e,gr())}function Cr(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),l=n.slice(0,-a.length);if(n.endsWith(a)&&l.length>0&&!l.includes("."))return!0}}return!1}var br=8e3,fe=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)}}},me=class extends ur.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??br}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=z(i),a=new fe(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=ot.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}parseProxyOrSettle(e,t){try{return pe(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 l=cr.request({host:s.host,port:s.port,method:"CONNECT",path:`${n}:${o}`,headers:a});i.onDestroy(()=>l.destroy()),l.on("connect",(g,y)=>{if(g.statusCode!==200){y.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${g.statusCode} ${g.statusMessage||""}`));return}i.onDestroy(()=>y.destroy()),this.startTlsOverTunnel(e,y,i,n)}),l.on("error",g=>{i.settle(new Error(`[GRS] Proxy connection failed: ${g.message}`))}),l.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=ot.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=Tr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},he=new me({keepAlive:!0});var ye=[{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"}],R=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var Ar=["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"],xr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",wr="devecostudio",Rr=8e3;async function Ee(r){let e=[],t="";for(let i of Ar){let s=await Pr(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 R("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: ${q(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 R("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function Pr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${wr}`;p(()=>`[GRS] POST ${t}`);try{let n=await de.post(t,{headers:{"User-Agent":xr},httpsAgent:he,timeout:Rr}),o=de.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):Dr(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 Dr(r){return ye.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import ut from"fs";import Lr from"path";var _r="com.huawei.devecostudio.region",Nr={[_r]:{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"}},Ir=1440*60*1e3,lt=new Set(["CN","HK","MO"]),ve=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return lt.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=Nr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Or(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 Ee(this.countryCode);this.services=t,this.resolved=!0,await kr(this.countryCode,t)}},v=new ve;function pt(r){return Lr.join(b(),`grs_${r}.json`)}async function Or(r){try{let e=await ut.promises.readFile(pt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Ir?null:t}catch{return null}}async function kr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await ut.promises.writeFile(pt(r),JSON.stringify(t),"utf8")}catch{}}var O=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 k;storageDir="";failedDir="";installId="";get disabled(){return j()||!v.isCN()}traceFileKey=Buffer.alloc(0);sessionId=dt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=h.join(e,"failed"),this.cliVersion="1.3.12-Test.2",this.nodeVersion=process.version,this.installId=Xe(e).replace(/-/g,""),this.traceFileKey=Ie(e),m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0}),f.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return f.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let 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=te(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=Oe(JSON.stringify(i),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
40
+ `,"utf8"),je(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=Le.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:dt.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=X.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=X.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 X.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(X.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 h.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.debug("[telemetry] scheduler not started (telemetry disabled)");return}f.debug(`[telemetry] scheduler started (flush every ${G/1e3}s, retry failed every ${H/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},G)},G),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},H)},H)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),f.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return f.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return Ve(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return f.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await m.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>h.join(this.failedDir,i)),o=!0;for(let i of n){let s=h.basename(i),a=qe(s);if(a!==null){if(e-a>Ue){try{await m.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||f.warn("[telemetry] retry failed"),ze(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)Ke(o)&&await this.reclaimOrphan(h.join(t,o),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<Ge)return;n=g.size}catch{return}let o=h.dirname(e),i=ae(h.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=h.join(o,i),l=w-await this.fileSize(a);if(n>l){try{await m.promises.unlink(s)}catch{}f.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${l})`);return}if(await this.mergeOrphanInto(s,a)){f.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}f.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let o=h.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 f.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){f.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await m.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await m.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await m.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>h.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>w){f.warn(`[telemetry] ${h.basename(e)} is ${t} bytes (> ${w}), 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=ke(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 l=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(l,this.installId)}catch{}if(!g){f.warn("[telemetry] upload failed");let y=t.slice(o).join(`
42
42
  `)+`
43
- `;return await this.moveToFailed(e,h),!1}}try{await m.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let i=JSON.parse(n);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=y.basename(e,".pending"),i=y.join(this.failedDir,n),o=t.split(`
44
- `).filter(Boolean),s=A-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&f.warn(`[telemetry] failed file capped at ${A} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await m.promises.appendFile(i,a.join(`
43
+ `;return await this.moveToFailed(e,y),!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=h.basename(e,".pending"),o=h.join(this.failedDir,n),i=t.split(`
44
+ `).filter(Boolean),s=w-await this.fileSize(o),a=this.takeNewestWithinBudget(i,s);a.length<i.length&&f.warn(`[telemetry] failed file capped at ${w} 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=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,n.push(e[o])}return n.reverse(),n}};var x=new _;import{execFile as io,spawn as oo}from"child_process";import{existsSync as ao,readdirSync as co,readFileSync as uo}from"fs";import{spawn as Co}from"child_process";import{existsSync as wo}from"fs";import{dirname as Ro,join as Po}from"path";import{fileURLToPath as Lo}from"url";var Ar=new Set(["C","POSIX"]);function pe(){let r=wr();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),Ar.has(r))return p("[region] locale=C/POSIX\uFF0C\u89C6\u4E3A\u65E0\u4FE1\u53F7\uFF0C\u4EA4\u7531\u65F6\u533A\u515C\u5E95"),null;let e=r.split(".")[0],t=xr(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function wr(){let r=process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG;if(r)return r.trim();try{return Intl.DateTimeFormat().resolvedOptions().locale||null}catch{return null}}function xr(r){let e=r.split(/[-_]/);if(e.length<2)return null;for(let t=e.length-1;t>=0;t--){let n=e[t];if(/^[A-Za-z]{2}$/.test(n))return n.toUpperCase()}return null}var de={"Asia/Shanghai":"CN","Asia/Urumqi":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Pyongyang":"KP","Asia/Ulaanbaatar":"MN","Asia/Singapore":"SG","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Manila":"PH","Asia/Kuala_Lumpur":"MY","Asia/Kuching":"MY","Asia/Ho_Chi_Minh":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Yangon":"MM","Asia/Brunei":"BN","Asia/Dili":"TL","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Mumbai":"IN","Asia/Delhi":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Colombo":"LK","Asia/Kathmandu":"NP","Asia/Thimphu":"BT","Asia/Male":"MV","Asia/Almaty":"KZ","Asia/Aqtobe":"KZ","Asia/Qyzylorda":"KZ","Asia/Tashkent":"UZ","Asia/Dushanbe":"TJ","Asia/Bishkek":"KG","Asia/Ashgabat":"TM","Asia/Dubai":"AE","Asia/Riyadh":"SA","Asia/Qatar":"QA","Asia/Bahrain":"BH","Asia/Kuwait":"KW","Asia/Muscat":"OM","Asia/Aden":"YE","Asia/Baghdad":"IQ","Asia/Tehran":"IR","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Beirut":"LB","Asia/Damascus":"SY","Asia/Amman":"JO","Asia/Kabul":"AF","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Tbilisi":"GE","Asia/Nicosia":"CY","Europe/London":"GB","Europe/Dublin":"IE","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Europe/Amsterdam":"NL","Europe/Brussels":"BE","Europe/Vienna":"AT","Europe/Zurich":"CH","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Helsinki":"FI","Europe/Warsaw":"PL","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Moscow":"RU","Europe/Kaliningrad":"RU","Europe/Lisbon":"PT","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Kyiv":"UA","Europe/Kiev":"UA","Europe/Minsk":"BY","Europe/Bucharest":"RO","Europe/Sofia":"BG","Europe/Belgrade":"RS","Europe/Zagreb":"HR","Europe/Ljubljana":"SI","Europe/Sarajevo":"BA","Europe/Skopje":"MK","Europe/Tirane":"AL","Europe/Riga":"LV","Europe/Tallinn":"EE","Europe/Vilnius":"LT","Europe/Chisinau":"MD","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","America/Juneau":"US","America/Honolulu":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Halifax":"CA","America/Edmonton":"CA","America/Winnipeg":"CA","America/Mexico_City":"MX","America/Sao_Paulo":"BR","America/Argentina/Buenos_Aires":"AR","America/Buenos_Aires":"AR","America/Santiago":"CL","America/Lima":"PE","America/Bogota":"CO","America/Caracas":"VE","America/Guayaquil":"EC","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Havana":"CU","America/Santo_Domingo":"DO","America/Jamaica":"JM","America/Port-au-Prince":"HT","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Hobart":"AU","Pacific/Auckland":"NZ","Pacific/Fiji":"FJ","Pacific/Guam":"GU","Africa/Cairo":"EG","Africa/Lagos":"NG","Africa/Johannesburg":"ZA","Africa/Nairobi":"KE","Africa/Casablanca":"MA","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Accra":"GH","Africa/Addis_Ababa":"ET","Africa/Dar_es_Salaam":"TZ","Africa/Khartoum":"SD","Africa/Tripoli":"LY"};function fe(){let r=pe();if(r)return{code:r,source:"locale"};let e=nt();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function nt(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=de[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import it from"fs";import ot from"path";import{homedir as Rr}from"os";var Pr="country.region.xml",Dr=".config",Lr="deveco-cli";function st(){let r=process.env.DEVECO_CLI_DATA_DIR?C():ot.join(Rr(),Dr,Lr);return ot.join(r,Pr)}function me(){let r=st();try{if(!it.existsSync(r))return null;let t=it.readFileSync(r,"utf8").match(/<countryregion\s+name="([A-Za-z]{2})"/);return t?t[1].toUpperCase():(p(()=>`[region] country.region.xml malformed: ${r}`),null)}catch(e){return p(()=>`[region] failed to read country.region.xml: ${e.message}`),null}}var at=me();if(at)E.setCountryCode(at);else{let r=fe();r&&E.setCountryCode(r.code)}if(!E.isCN())f.info("[telemetry] background upload skipped (non-CN region)");else{let r=_r.join(C(),"TraceLogData",E.countryCode);x.init(r),(async()=>{try{await x.flush(),await x.retryFailed()}catch(e){f.warn("[telemetry] background upload error:",e),process.exit(1)}})()}
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 P=new O;import{execFile as Pi,spawn as Di}from"child_process";import{existsSync as _i,readdirSync as Ni,readFileSync as Ii}from"fs";import{spawn as qi}from"child_process";import{existsSync as Wi}from"fs";import{dirname as Yi,join as Ji}from"path";import{fileURLToPath as Qi}from"url";var Fr=new Set(["C","POSIX"]);function Se(){let r=Br();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),Fr.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=$r(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function Br(){let r=process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG;if(r)return r.trim();try{return Intl.DateTimeFormat().resolvedOptions().locale||null}catch{return null}}function $r(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 Te={"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 Ce(){let r=Se();if(r)return{code:r,source:"locale"};let e=ft();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function ft(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=Te[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import mt from"fs";import gt from"path";import{homedir as Ur}from"os";var Gr="country.region.xml",Hr=".config",jr="deveco-cli";function ht(){let r=process.env.DEVECO_CLI_DATA_DIR?b():gt.join(Ur(),Hr,jr);return gt.join(r,Gr)}function be(){let r=ht();try{if(!mt.existsSync(r))return null;let t=mt.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 yt=be();if(yt)v.setCountryCode(yt);else{let r=Ce();r&&v.setCountryCode(r.code)}if(!v.isCN())f.info("[telemetry] background upload skipped (non-CN region)");else{let r=Vr.join(b(),"TraceLogData",v.countryCode);P.init(r),(async()=>{try{await P.flush(),await P.retryFailed()}catch(e){f.warn("[telemetry] background upload error:",e),process.exit(1)}})()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/deveco-cli-common",
3
- "version": "1.3.11-Test.6",
3
+ "version": "1.3.12-Test.2",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "supportedDocsApi": 1,
6
6
  "license": "MIT",
@@ -65,9 +65,10 @@
65
65
  "smol-toml": "^1.6.1",
66
66
  "socket.io-client": "^4.7.5",
67
67
  "ui-verification-mcp": "0.0.20",
68
+ "ws": "^8.21.1",
68
69
  "xpath": "^0.0.35",
69
70
  "zod": "^4.4.3",
70
- "@deveco-test/deveco-cli-knowledgebase": "1.3.11-Test.6"
71
+ "@deveco-test/deveco-cli-knowledgebase": "1.3.12-Test.2"
71
72
  },
72
73
  "devDependencies": {
73
74
  "@types/adm-zip": "^0.5.8",
@@ -76,6 +77,7 @@
76
77
  "@types/node-forge": "^1.3.14",
77
78
  "@types/proper-lockfile": "^4.1.4",
78
79
  "@types/semver": "^7.7.1",
80
+ "@types/ws": "^8.18.2",
79
81
  "design2arkts-engine": "0.1.0"
80
82
  }
81
83
  }
@@ -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测试, 组件调试. 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测试, 组件调试, 预览器(HarmonyOS PC), 多设备预览器(HarmonyOS PC), 预览器截图, 视觉走查, 截图验证. 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,21 +9,31 @@ 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`, `update`, `device`, `emulator`, `ui`, `skills`, `log`, `verify`, `create`, `init`, `serve`, `docs`, `signature`, `auth`, `design2arkts` (alias `d2a`), `testing`.
12
+ Available commands: `build`, `check`, `run`, `debug`, `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
+
16
18
  ## 1. Code → Build → Deploy → Run → Debug
17
19
 
18
20
  ### `devecocli create`
19
- Scaffold a new HarmonyOS project.
21
+ Scaffold a new HarmonyOS project. Built-in templates: `empty-ability` (default) and `native-cpp` (C++/NAPI); run `create list` to see all.
20
22
  - `--app-name <name>` (Req): 1–200 chars, `^[a-zA-Z][a-zA-Z0-9_]*$`
21
23
  - `--project-path <path>`: Auto-created if omitted (`./<app-name>`). Must be empty if exists.
22
24
  - `--bundle-name <bundle>`: Default `com.example.<appname-lowercase>`. 7–128 chars, ≥3 segments.
23
- - `--api-level <level>`: int ≥17 (default: auto or 23).
25
+ - `--api-level <level>`: int ≥17 (default: max API of the installed DevEco Studio/HarmonyOS SDK; falls back to 23 when unavailable).
24
26
  - `--device-types <types...>`: One or more device types written to `module.json5` (default: `phone`). Supported: `phone`, `tablet`, `2in1`, `car`, `wearable`, `tv`. Unknown values fail with the supported list.
27
+ - `--template <name>`: Template logical name (default: `empty-ability`). `native-cpp` generates a project with C++/NAPI sources under `entry/src/main/cpp/`. Unknown names fail with the available template list.
25
28
  *Ex*: `devecocli create --app-name MyApp --project-path ./CustomDir --api-level 23`
26
29
  *Ex*: `devecocli create --app-name MyApp --device-types tablet`
30
+ *Ex*: `devecocli create --template native-cpp --app-name Shop`
31
+
32
+ ### `devecocli create list`
33
+ List available project templates.
34
+ - `--format <default|json>`: `default` renders a Name/Description table; `json` prints a parseable array (fields: `name`, `bundleType`, `displayName`, `description`, `deviceTypes`).
35
+ *Ex*: `devecocli create list`
36
+ *Ex*: `devecocli create list --format json`
27
37
 
28
38
  ### `devecocli build` `[Outside sandbox]`
29
39
  Compile and package project/modules. (Defaults: `--product default`, `--build-mode debug`)
@@ -190,6 +200,21 @@ Build, install, and launch. After a successful ability launch (and after a succe
190
200
  - **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`.
191
201
  *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`.
192
202
 
203
+ ### `devecocli debug` `[Outside sandbox]`
204
+ 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).
205
+ - **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.
206
+ - `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.
207
+ - `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`.
208
+ - `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>)`.
209
+ - `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`).
210
+ - 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.
211
+ - `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`).
212
+ - `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.
213
+ - `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.
214
+ - **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.
215
+ - 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`.
216
+ *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`.
217
+
193
218
  ### `devecocli signature generate` `[Outside sandbox]`
194
219
  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.
195
220
  - **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).
@@ -304,6 +329,7 @@ Inspect UI on a connected device. All subcommands accept `--device <name|serial>
304
329
  |---|---|---|
305
330
  | `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` |
306
331
  | `window list` | List active windows | `--format default\|json`, `--all` (include system windows) |
332
+ | `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) |
307
333
  | `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) |
308
334
  | `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` |
309
335
  | `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`) |
@@ -336,6 +362,25 @@ Inspect UI on a connected device. All subcommands accept `--device <name|serial>
336
362
  - `--mode full`: full layout tree, no filtering.
337
363
  - `--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.
338
364
 
365
+ **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`.
366
+
367
+ **Real device or emulator** (any host):
368
+ 1. `devecocli run` — builds, installs, and launches in one command (auto-selects a single connected target; `--device <name|serial>` when several)
369
+ 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.
370
+
371
+ **DevEco Studio previewer** (HarmonyOS PC only):
372
+ 1. `devecocli build`
373
+ 2. Start/refresh the previewer in DevEco Studio — this CLI has no previewer launch command.
374
+ 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).
375
+ 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.
376
+ 5. Capture it: `devecocli ui screenshot --display <virtualDisplayId> --path <existing-dir>/<fresh-name>.png`.
377
+
378
+ **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.
379
+
380
+ **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.
381
+
382
+ *Ex*: `devecocli ui display list` → `devecocli ui screenshot --display 1005 --path ./shots/round1.png` (directory already exists; new file name per round)
383
+
339
384
  ### `devecocli testing` `[Outside sandbox]`
340
385
 
341
386
  Run DevEco Testing detection services on a connected device.
@@ -380,7 +425,7 @@ MUTUALLY EXCLUSIVE modes for setup:
380
425
  - `--path <path>`: Direct skill install path; cannot combine with `--agent`, `--project` or `--mcp`.
381
426
  - `--with-homegraph`: With `--mcp` only. Also install the `homegraph` CLI and write a sibling `homegraph` MCP entry; records an opt-in marker so `devecocli update` can upgrade it later. Errors if used without `--mcp`.
382
427
  *MCP Rules*: Configured MCP agents support global (no `--project`) and project-level setup; `qoder` is unsupported.
383
- *Skill agents*: See README.md, “Skill 支持的智能体”. All supported agents allow global and project installation. If an agent is not detected, specify `--agent`.
428
+ *Skill agents*: See README.md, “`init` 支持的 Skill 安装目标”. If an agent is not detected, specify `--agent`.
384
429
 
385
430
  **Existing Skill paths and MCP entries are skipped by default. To update them or convert copied Skill installations to symlinks, rerun `devecocli init -f` (or `--force`); old content and local edits will be deleted.** This flag also allows missing target directories to be created. Correct links are kept and follow CLI updates; failed linking falls back to copying. `skills remove` rejects bundled skill names and never touches the npm package. Bundled skills newly added by a CLI upgrade are installed by rerunning `devecocli init` (already-installed links follow package updates automatically).
386
431
 
@@ -416,7 +461,7 @@ Extracted skills are stored in <CLI data directory>/skills/store/<name> globally
416
461
 
417
462
  ### `devecocli plugin`
418
463
  Manage whitelisted npm-packaged AI agent plugins (official registry only; the whitelist `npmPackage` coordinate may carry a `@tag` suffix to select a dist-tag, e.g. `@scope/pkg@cli` — defaults to `latest`).
419
- - `list [-l|--long]`: List whitelisted plugins and locally downloaded versions in a `Name / Version / Status` table (one row per cached version, ascending; `not installed` when none); `--long` appends `NpmPackage` and `Desc` columns.
464
+ - `list [-l|--long]`: List whitelisted plugin names, one per line (matching `skills list`); `--long` appends each plugin's description.
420
465
  - `install <name> [--agent <a,b…>] [--project <path>] [-f]`: Download the package into the CLI data directory, then run the plugin's `install` hook per target agent (detected agents ∩ plugin `supportedAgents`; a plugin omitting `supportedAgents` defaults to all known agents, while an explicitly empty/unknown list fails contract validation). `--force` runs the previous version's `uninstall` hook first. With an explicit `--agent` plus `--project`, missing target skills dirs (including the `.<agent>` root) are created before hooks run, matching `init --project --agent`.
421
466
  - `update <name> [--agent <a,b…>] [--project <path>]`: Fetch the latest version and run the `update` hook (`from`/`to` provided; `from` is the highest pre-download store version — `from === to` means no local version or latest already cached, treat as repair/first install). With an explicit `--agent` plus `--project`, missing target skills dirs (including the `.<agent>` root) are created before hooks run, same as `install`.
422
467
  - `uninstall <name> [--agent <a,b…>] [--project <path>]`: Run the `uninstall` hook of the highest loadable local version. Never deletes cached packages (`<dataDir>/plugins/store/<name>/`) or plugin data (`<dataDir>/plugins/data/<name>/`); remove those manually if needed.
@@ -462,6 +507,9 @@ Solution design supports UI pages only; repository analysis covers the target pa
462
507
  `devecocli build` -> `devecocli emulator list` -> `devecocli emulator start "Name"` -> `devecocli run`
463
508
  - **Diagnose crash**:
464
509
  `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
465
513
  - **Release build**:
466
514
  `devecocli build --product oversea --build-mode release`
467
515
  - **First-time signing setup** (login authorized; user completes browser authentication):
@@ -490,5 +538,5 @@ Solution design supports UI pages only; repository analysis covers the target pa
490
538
  - **`当前 DevEco Testing 版本不支持 testing`**: The installed client is too old. Run `devecocli testing update`, then retry.
491
539
  - **`[ERROR] 前置确认未通过`**: `run` hit the confirmation prompt in a non-interactive shell. Add `--yes`.
492
540
  - **`run` killed mid-test**: The bash timeout was shorter than the test. Re-run with a longer timeout; a killed run produces no report.
493
- - **"Skills marketplace is not available in your region"**: Expected when running `skills list/find/add` outside Chinese mainland (incl. HK/MO). Installed skills still work; `skills remove` and `init` don't touch the network.
494
- - **"CLI online services are not available in your region"**: Commands needing cloud services (login/signature/agreement) abort when GRS is unreachable or the region has no config; local-only commands (`create`/`build`/`device`) are unaffected. Suggest checking `HTTP_PROXY`/`HTTPS_PROXY`. GRS verifies server certificates on every connection, proxied or not — a proxy that re-signs TLS (corporate inspection) fails closed unless its CA is listed in a `NODE_EXTRA_CA_CERTS` PEM file. Use `DEVECO_CLI_DEBUG=1` to inspect country-code detection and GRS resolution. Telemetry is CN-only (silently disabled elsewhere).
541
+ - **"CLI online services are not available in your region"**: Cloud-service commands (login/signature/agreement, `skills list/find/add`) abort when the region is outside the CN/HK/MO whitelist; local-only commands (`create`/`build`/`device`, `skills remove`/`init`) and already-installed skills are unaffected. login/signature/agreement additionally depend on GRS: they also abort when GRS is unreachable or has no config for the region — suggest checking `HTTP_PROXY`/`HTTPS_PROXY`. GRS verifies server certificates on every connection, proxied or not — a proxy that re-signs TLS (corporate inspection) fails closed unless its CA is listed in a `NODE_EXTRA_CA_CERTS` PEM file. Use `DEVECO_CLI_DEBUG=1` to inspect country-code detection and GRS resolution. Telemetry is CN-only (silently disabled elsewhere).
542
+ - **"Marketplace unavailable"** (`skills list`/`find`): The skills marketplace is a fixed address (`matrix.openharmony.cn`), not resolved via GRS. When the market request fails, both commands warn and fall back to bundled-only output, exiting 0; `skills add` of a marketplace skill fails instead. Already-installed skills keep working.
package/skills/index.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
- "generatedAt": "2026-11-06T09:26:43.746Z",
2
+ "generatedAt": "2026-11-12T12:08:33.696Z",
3
3
  "skills": [
4
4
  {
5
5
  "name": "deveco-cli",
6
- "description": "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'. 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
+ "description": "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'. 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."
7
7
  },
8
8
  {
9
9
  "name": "hmos-arkui-develop-skill",
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "empty-ability",
3
+ "displayName": "Empty Ability",
4
+ "description": "This template implements the basic Hello World functions.",
5
+ "deviceTypes": ["phone"],
6
+ "minApiLevel": 17,
7
+ "bundleType": "app"
8
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "app": {
3
+ "bundleName": "com.example.myapplication",
4
+ "vendor": "example",
5
+ "versionCode": 1000000,
6
+ "versionName": "1.0.0",
7
+ "icon": "$media:layered_image",
8
+ "label": "$string:app_name"
9
+ }
10
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "string": [
3
+ {
4
+ "name": "app_name",
5
+ "value": "MyApplication"
6
+ }
7
+ ]
8
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "layered-image":
3
+ {
4
+ "background" : "$media:background",
5
+ "foreground" : "$media:foreground"
6
+ }
7
+ }
@@ -0,0 +1,43 @@
1
+ {
2
+ "app": {
3
+ "signingConfigs": [],
4
+ "products": [
5
+ {
6
+ "name": "default",
7
+ "signingConfig": "default",
8
+ "targetSdkVersion": "6.0.2(22)",
9
+ "compatibleSdkVersion": "6.0.2(22)",
10
+ "runtimeOS": "HarmonyOS",
11
+ "buildOption": {
12
+ "nativeCompiler": "BiSheng",
13
+ "strictMode": {
14
+ "caseSensitiveCheck": true,
15
+ "useNormalizedOHMUrl": true
16
+ }
17
+ }
18
+ }
19
+ ],
20
+ "buildModeSet": [
21
+ {
22
+ "name": "debug"
23
+ },
24
+ {
25
+ "name": "release"
26
+ }
27
+ ]
28
+ },
29
+ "modules": [
30
+ {
31
+ "name": "entry",
32
+ "srcPath": "./entry",
33
+ "targets": [
34
+ {
35
+ "name": "default",
36
+ "applyToProducts": [
37
+ "default"
38
+ ]
39
+ }
40
+ ]
41
+ }
42
+ ]
43
+ }