@deveco-test/deveco-cli-common 1.3.12-Test.1 → 1.3.12-Test.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -20
- package/THIRD-PARTY-LICENSES +3 -3
- package/dist/cli.js +207 -207
- package/dist/internal/telemetry-upload-background.js +10 -10
- package/package.json +2 -2
- package/skills/deveco-cli/SKILL.md +11 -3
- package/skills/index.json +1 -1
- package/templates/application/template.json +8 -0
- package/templates/native-cpp/AppScope/app.json5 +10 -0
- package/templates/native-cpp/AppScope/resources/base/element/string.json +8 -0
- package/templates/native-cpp/AppScope/resources/base/media/layered_image.json +7 -0
- package/templates/native-cpp/build-profile.json5 +43 -0
- package/templates/native-cpp/code-linter.json5 +32 -0
- package/templates/native-cpp/entry/build-profile.json5 +48 -0
- package/templates/native-cpp/entry/gitignore.txt +6 -0
- package/templates/native-cpp/entry/hvigorfile.ts +6 -0
- package/templates/native-cpp/entry/obfuscation-rules.txt +20 -0
- package/templates/native-cpp/entry/oh-package.json5 +11 -0
- package/templates/native-cpp/entry/src/main/cpp/CMakeLists.txt +15 -0
- package/templates/native-cpp/entry/src/main/cpp/napi_init.cpp +67 -0
- package/templates/native-cpp/entry/src/main/cpp/types/libentry/Index.d.ts +16 -0
- package/templates/native-cpp/entry/src/main/cpp/types/libentry/oh-package.json5 +6 -0
- package/templates/native-cpp/entry/src/main/ets/entryability/EntryAbility.ets +63 -0
- package/templates/native-cpp/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +31 -0
- package/templates/native-cpp/entry/src/main/ets/pages/Index.ets +26 -0
- package/templates/native-cpp/entry/src/main/module.json5 +50 -0
- package/templates/native-cpp/entry/src/main/resources/base/element/color.json +8 -0
- package/templates/native-cpp/entry/src/main/resources/base/element/float.json +8 -0
- package/templates/native-cpp/entry/src/main/resources/base/element/string.json +16 -0
- package/templates/native-cpp/entry/src/main/resources/base/media/layered_image.json +7 -0
- package/templates/native-cpp/entry/src/main/resources/base/profile/backup_config.json +3 -0
- package/templates/native-cpp/entry/src/main/resources/base/profile/main_pages.json +5 -0
- package/templates/native-cpp/entry/src/main/resources/dark/element/color.json +8 -0
- package/templates/native-cpp/gitignore.txt +13 -0
- package/templates/native-cpp/hvigor/hvigor-config.json5 +23 -0
- package/templates/native-cpp/hvigorfile.ts +6 -0
- package/templates/native-cpp/oh-package.json5 +10 -0
- package/templates/native-cpp/template.json +8 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
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}},
|
|
1
|
+
import zr from"path";import*as L from"fs";import*as we from"path";import{homedir as gt}from"os";import*as Ce from"fs";import*as E from"path";function X(r){let e=E.resolve(r),t=[],n=e;for(;;)try{let o=Ce.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 Y(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function be(r){let e=Y(r);if(!e)throw new Error("Path must not be empty.");return X(e)}var ht="deveco-cli",Ae,J=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function yt(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":Y(r))||we.join(gt(),".local","share",ht);try{return be(t)}catch(n){throw new J(n instanceof Error?n.message:String(n))}}function A(){if(Ae!==void 0)return Ae;let r=yt();try{if(L.existsSync(r))return L.realpathSync(r)}catch{}return r}import ut from"crypto";import f from"fs";import W from"os";import y from"path";import vt from"https";var xe={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var k=class r{static ENDPOINT=xe.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=vt.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 h=[];g.on("data",T=>h.push(T)),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 w=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function Z(r){if(r instanceof w)return r.traceMessage;if(r instanceof Error){let e=r.code;return typeof e=="string"&&e!==""?e:r.name}return"UnknownError"}function Q(r,e){return`${r}:${e}`}var x=class extends w{category;constructor(e,t,n,o){super(t,n,o),this.name="CategorizedTraceError",this.category=e}};function C(...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 Tt(r){return r.code==="ETIMEDOUT"||/timeout/i.test(r.name)}function St(r){let e=r.code;return r.name==="ScreenRecordError"&&typeof e=="string"&&e.endsWith("_TIMEOUT")}var Ct=[{category:"Timeout",match:Tt},{category:"Internal",match:C("ExecaError")},{category:"RuntimeCondition",match:C("CacheDirError","DocPathSafetyError")},{category:"InvalidArgument",match:C("SelectorParseError")},{category:"InvalidArgument",match:C("InvalidApiLevelError")},{category:"InvalidArgument",match:C("TemplateNotFoundError")},{category:"InvalidArgument",match:C("InvalidArgumentError")},{category:"InvalidArgument",match:M("ScreenRecordError","INVALID_ARGUMENT","INVALID_RECORDING_PATH")},{category:"Timeout",match:St},{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:C("GrsError")}];function bt(r){return Ct.find(t=>t.match(r))?.category??"Other"}function ee(r){if(r instanceof x)return Q(r.category,r.traceMessage);let e=r instanceof Error?bt(r):"Other";return Q(e,Z(r))}var Re={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()},te=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??Re.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}},Pe=new te({namingStrategy:Re.snakeCase,fieldNames:{}});import _ from"crypto";import F from"fs";import At from"path";var B="aes-256-gcm",wt=12,xt="deveco-cli-trace-file",Rt="trace-file-secret",Le=32;function De(r){try{let e=F.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Le?e:null}catch{return null}}function _e(r){let e=At.join(r,Rt),t=De(e);if(t)return re(t);let n=_.randomBytes(Le).toString("base64");try{F.mkdirSync(r,{recursive:!0});try{F.writeFileSync(e,n,{flag:"wx"})}catch{let o=De(e);if(o)return re(o);F.writeFileSync(e,n)}}catch{}return re(n)}function re(r){return _.createHash("sha256").update(xt).update(r).digest()}function Ie(r,e){let t=_.randomBytes(wt),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 Ne(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!Pt(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 Pt(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 I from"os";import*as S from"path";import An from"json5";var Pn=64*1024;function Oe(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(I.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(I.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(I.homedir(),".local","share","devecocli-mcp-server","logs")}var ke="mcp-server.log",Dt="mcp-server",Lt={maxSize:10*1024*1024,maxFiles:4},ne=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={...Lt,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Oe(),this.currentLogFile=U.join(this.logDir,ke),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,`${Dt}-${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===ke||/^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}},N=null;function _t(r=!1){N&&N.dispose(),N=new ne(r)}function $(){return N||_t(!1),N}var m={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 Fe from"fs";import It from"path";var G=300*1e3,H=3600*1e3,Be=10080*60*1e3,R=8*1024*1024,$e=3600*1e3,Me=".pending",Nt=/\.reclaim-\d+-\d+$/;function j(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var Ot="upload-state.json";function Ue(r){return It.join(r,Ot)}function kt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function oe(r){try{let e=Fe.readFileSync(Ue(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 kt()}}function ie(r,e){try{Fe.writeFileSync(Ue(r),JSON.stringify(e),"utf8")}catch{}}function Ge(r){let e=oe(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),ie(r,e))}function He(r){let e=oe(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,ie(r,e)}function je(r){let e=oe(r);e.lastRetryAt=Date.now(),ie(r,e)}function Ve(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 se(r){if(!r.startsWith("telemetry-"))return null;let e=Nt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(Me))return null;let n=t.slice(0,-Me.length);return n.endsWith(".txt")?n:null}function ze(r){return se(r)!==null}import Mt from"crypto";import V from"fs";import Ft from"path";var Bt="install-id";function $t(r){return Ft.join(r,Bt)}function qe(r){try{let e=V.readFileSync(r,"utf8").trim();return Ut(e)?e:null}catch{return null}}function Ut(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 Ke(r){let e=$t(r),t=qe(e);if(t)return t;let n=Mt.randomUUID();try{V.mkdirSync(r,{recursive:!0});try{V.writeFileSync(e,n,{flag:"wx"})}catch{let o=qe(e);if(o)return o;V.writeFileSync(e,n)}}catch{}return n}import Zt from"axios";var We={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ae={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 Gt={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Ht(r){try{return new URL(r)}catch{return null}}function z(r){var e=(typeof r=="string"?Ht(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)||Gt[t]||0,!jt(n,o)))return"";var i=ce(t+"_proxy")||ce("all_proxy");return i&&i.indexOf("://")===-1&&(i=t+"://"+i),i}function jt(r,e){var t=ce("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 ce(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}import{spawn as Je}from"child_process";import*as b from"fs";import*as Ze from"os";import*as q from"path";var Qe=6e4;async function Vt(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Xe(r,"ProxyServer");if(!e)return null;let t=await Xe(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Xe(r,e){return new Promise(t=>{let n=Je("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 zt(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function qt(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ye(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 Kt(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??Qe)/1e3)))];return r.method&&r.method!=="GET"&&o.push("-X",r.method),r.data!==void 0&&o.push("--data-binary",r.data),o.push(...Wt(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 Wt(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 Xt(r,e,t){if(t){let g=b.readFileSync(e,"utf8"),h=b.readFileSync(t),T=Ye(g);return{statusCode:T.statusCode,statusText:T.statusText,body:h.toString("base64"),headers:T.headers,bodyBuffer:h}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let o=r.slice(n),i=o.indexOf(`\r
|
|
3
3
|
\r
|
|
4
|
-
`);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),l=
|
|
5
|
-
${e}`,r.code??"Unknown",{cause:r});return t.code=r.code,t.response=r.response,t}var
|
|
4
|
+
`);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),l=Ye(s);return{statusCode:l.statusCode,statusText:l.statusText,body:a,headers:l.headers}}async function et(r){if(process.platform!=="win32")return null;let e=zt()??await Vt();if(!e)return null;let t;r.binary&&(t=b.mkdtempSync(q.join(Ze.tmpdir(),"curl-")));let n=t?q.join(t,"header.tmp"):void 0,o=t?q.join(t,"body.tmp"):void 0;try{let i=Kt(r,e,n,o),s=await Yt(i,r.timeoutMs);return!s||s.code!==0?null:Xt(s.stdout,n,o)}catch{return null}finally{t&&b.rmSync(t,{recursive:!0,force:!0})}}function Yt(r,e){let t=qt();return new Promise(n=>{let o=Je(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="",s=!1,a=setTimeout(()=>{s||(s=!0,o.kill())},e??Qe);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 Qt(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)}}}function er(r,e){return r==="ETIMEDOUT"||r==="ECONNABORTED"&&/timeout/i.test(e)}function tr(r){let e=`Network connection failed (${r.code}). Please check your proxy configuration or network settings`,t=new x(er(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 ue=class{client;constructor(){let e={timeout:We.HTTP_TIMEOUT_MS,headers:{"User-Agent":ae.USER_AGENT,"accept-language":ae.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Zt.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?Qt(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{throw tr(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(rr(o)||process.platform!=="win32"||!(e instanceof Error)||!nr(e))return null;let s,a=t;return n==="GET"?o?.params&&(a=or(t,o.params)):o?.params!==void 0&&o.params!==null&&(s=typeof o.params=="string"?o.params:JSON.stringify(o.params)),et({url:a,method:n,data:s,headers:o?.headers,timeoutMs:o?.timeout,binary:i})}},le=new ue;function rr(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function nr(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 or(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[i,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${i}[]`,String(a));else t.append(i,String(s));let n=t.toString();if(!n)return r;let o=r.includes("?")?"&":"?";return`${r}${o}${n}`}import{AsyncLocalStorage as ir}from"async_hooks";var sr=new ir;function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;sr.getStore()?console.error(`[DEBUG] ${e}`):console.log(`[DEBUG] ${e}`)}}import ar from"fs";import cr from"http";import ur from"https";import lr from"path";import tt from"tls";import me from"crypto";import{URL as pr}from"url";import{yellow as dr}from"colorette";var mr=`-----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-----`,pr=new le.X509Certificate(lr),Qe=[{cert:pr}];function dr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new le.X509Certificate(n)})}catch{}return e}var et=new Set,q;function fr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(q&&q.envValue===r)return q.anchors;let e=r?mr(r):[],t=e.length?[...Qe,...e]:Qe;return q={envValue:r,anchors:t},t}function mr(r){try{let e=dr(or.readFileSync(r,"utf8"));return e.length===0&&tt(r,"no parseable certificate found"),e}catch(e){return tt(r,e instanceof Error?e.message:String(e)),[]}}function tt(r,e){et.has(r)||(et.add(r),console.warn(ur(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${ar.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function gr(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 le.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function hr(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!yr(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=Er(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function yr(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&rt(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)&&rt(r,r.length-1))return!0}catch{}return!1}function rt(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 Er(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(!Sr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function vr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=gr(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):hr(n,e,fr())}function Sr(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 Tr=8e3,ce=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)}}},ue=class extends sr.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Tr}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=V(i),a=new ce(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=Ze.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}createConnectionViaProxy(e,t,n,o,i){let s;try{s=new cr(t)}catch{i.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),l=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${o}`);let g=ir.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${o}`,headers:l});i.onDestroy(()=>g.destroy()),g.on("connect",(h,S)=>{if(h.statusCode!==200){S.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}i.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,i,n)}),g.on("error",h=>{i.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=Ze.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`};if(e.username||e.password){let i=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(i).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=vr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},pe=new ue({keepAlive:!0});var de=[{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 Cr=["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"],br="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",Ar="devecostudio",wr=8e3;async function fe(r){let e=[],t="";for(let i of Cr){let s=await xr(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 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,o=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). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function xr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Ar}`;p(()=>`[GRS] POST ${t}`);try{let n=await ae.post(t,{headers:{"User-Agent":br},httpsAgent:pe,timeout:wr}),o=ae.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):Rr(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 Rr(r){return de.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import nt from"fs";import Pr from"path";var Dr="com.huawei.devecostudio.region",Lr={[Dr]:{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"}},_r=1440*60*1e3,ot=new Set(["CN","HK","MO"]),me=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return ot.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=Lr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Nr(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 fe(this.countryCode);this.services=t,this.resolved=!0,await Ir(this.countryCode,t)}},v=new me;function it(r){return Pr.join(b(),`grs_${r}.json`)}async function Nr(r){try{let e=await nt.promises.readFile(it(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>_r?null:t}catch{return null}}async function Ir(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await nt.promises.writeFile(it(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 H()||!v.isCN()}traceFileKey=Buffer.alloc(0);sessionId=st.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.12-Test.1",this.nodeVersion=process.version,this.installId=Ve(e).replace(/-/g,""),this.traceFileKey=Pe(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=this.toErrorCode(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=De(JSON.stringify(i),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
|
|
40
|
-
`,"utf8"),
|
|
41
|
-
`).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await
|
|
39
|
+
-----END CERTIFICATE-----`,fr=new me.X509Certificate(mr),rt=[{cert:fr}];function gr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new me.X509Certificate(n)})}catch{}return e}var nt=new Set,K;function hr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(K&&K.envValue===r)return K.anchors;let e=r?yr(r):[],t=e.length?[...rt,...e]:rt;return K={envValue:r,anchors:t},t}function yr(r){try{let e=gr(ar.readFileSync(r,"utf8"));return e.length===0&&ot(r,"no parseable certificate found"),e}catch(e){return ot(r,e instanceof Error?e.message:String(e)),[]}}function ot(r,e){nt.has(r)||(nt.add(r),console.warn(dr(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${lr.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function Er(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 me.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function vr(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!Tr(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 Tr(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&it(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)&&it(r,r.length-1))return!0}catch{}return!1}function it(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(!br(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=Er(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):vr(n,e,hr())}function br(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 Ar=8e3,pe=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)}}},de=class extends ur.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Ar}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=z(i),a=new pe(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=tt.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}createConnectionViaProxy(e,t,n,o,i){let s;try{s=new pr(t)}catch{i.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),l=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${o}`);let g=cr.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${o}`,headers:l});i.onDestroy(()=>g.destroy()),g.on("connect",(h,T)=>{if(h.statusCode!==200){T.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}i.onDestroy(()=>T.destroy()),this.startTlsOverTunnel(e,T,i,n)}),g.on("error",h=>{i.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=tt.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`};if(e.username||e.password){let i=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(i).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=Cr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},fe=new de({keepAlive:!0});var ge=[{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"}],P=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var wr=["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",Rr="devecostudio",Pr=8e3;async function he(r){let e=[],t="";for(let i of wr){let s=await Dr(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 P("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: ${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 P("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function Dr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Rr}`;p(()=>`[GRS] POST ${t}`);try{let n=await le.post(t,{headers:{"User-Agent":xr},httpsAgent:fe,timeout:Pr}),o=le.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):Lr(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 Lr(r){return ge.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import st from"fs";import _r from"path";var Ir="com.huawei.devecostudio.region",Nr={[Ir]:{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"}},Or=1440*60*1e3,at=new Set(["CN","HK","MO"]),ye=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return at.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 kr(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 he(this.countryCode);this.services=t,this.resolved=!0,await Mr(this.countryCode,t)}},v=new ye;function ct(r){return _r.join(A(),`grs_${r}.json`)}async function kr(r){try{let e=await st.promises.readFile(ct(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Or?null:t}catch{return null}}async function Mr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await st.promises.writeFile(ct(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=ut.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){m.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.12-Test.3",this.nodeVersion=process.version,this.installId=Ke(e).replace(/-/g,""),this.traceFileKey=_e(e),f.mkdirSync(e,{recursive:!0}),f.mkdirSync(this.failedDir,{recursive:!0}),m.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,m.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,m.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,m.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return m.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=ee(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=Ie(JSON.stringify(i),this.traceFileKey);await f.promises.appendFile(this.currentFile(),s+`
|
|
40
|
+
`,"utf8"),Ge(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=Pe.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:ut.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=W.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=W.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 W.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(W.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){m.debug("[telemetry] scheduler not started (telemetry disabled)");return}m.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),m.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return m.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 He(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return m.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await f.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>y.join(this.failedDir,i)),o=!0;for(let i of n){let s=y.basename(i),a=Ve(s);if(a!==null){if(e-a>Be){try{await f.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||m.warn("[telemetry] retry failed"),je(this.storageDir),o}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await f.promises.readdir(t)}catch{continue}for(let o of n)ze(o)&&await this.reclaimOrphan(y.join(t,o),e)}}async reclaimOrphan(e,t){let n;try{let g=await f.promises.stat(e);if(t-g.mtimeMs<$e)return;n=g.size}catch{return}let o=y.dirname(e),i=se(y.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=y.join(o,i),l=R-await this.fileSize(a);if(n>l){try{await f.promises.unlink(s)}catch{}m.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${l})`);return}if(await this.mergeOrphanInto(s,a)){m.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}m.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let o=y.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await f.promises.rename(e,o)}catch{return null}return await this.touch(o),o}async mergeOrphanInto(e,t){try{await f.promises.appendFile(t,await f.promises.readFile(e))}catch(n){return m.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await f.promises.unlink(e)}catch(n){m.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 f.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await f.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 f.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>R){m.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${R}), dropped without uploading`);try{await f.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await f.promises.rename(e,n)}catch{return!1}await this.touch(n);let o;try{o=await f.promises.readFile(n,"utf8")}catch{return!1}let i=o.split(`
|
|
41
|
+
`).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await f.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=Ne(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){m.warn("[telemetry] upload failed");let h=t.slice(o).join(`
|
|
42
42
|
`)+`
|
|
43
|
-
`;return await this.moveToFailed(e,h),!1}}try{await
|
|
44
|
-
`).filter(Boolean),s=
|
|
43
|
+
`;return await this.moveToFailed(e,h),!1}}try{await f.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let o=JSON.parse(n);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=y.basename(e,".pending"),o=y.join(this.failedDir,n),i=t.split(`
|
|
44
|
+
`).filter(Boolean),s=R-await this.fileSize(o),a=this.takeNewestWithinBudget(i,s);a.length<i.length&&m.warn(`[telemetry] failed file capped at ${R} bytes, dropped ${i.length-a.length} older events`);try{a.length>0&&await f.promises.appendFile(o,a.join(`
|
|
45
45
|
`)+`
|
|
46
|
-
`,"utf8")}catch{return}try{await
|
|
46
|
+
`,"utf8")}catch{return}try{await f.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let n=[],o=0;for(let i=e.length-1;i>=0;i--){let s=Buffer.byteLength(e[i],"utf8")+1;if(o+s>t)break;o+=s,n.push(e[i])}return n.reverse(),n}};var D=new O;import{execFile as xi,spawn as Ri}from"child_process";import{existsSync as Di,readdirSync as Li,readFileSync as _i}from"fs";import{spawn as Vi}from"child_process";import{existsSync as qi}from"fs";import{dirname as Wi,join as Xi}from"path";import{fileURLToPath as Ji}from"url";var Br=new Set(["C","POSIX"]);function Ee(){let r=$r();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),Br.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=Ur(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function $r(){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 Ur(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 ve={"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 Te(){let r=Ee();if(r)return{code:r,source:"locale"};let e=lt();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function lt(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=ve[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import pt from"fs";import dt from"path";import{homedir as Gr}from"os";var Hr="country.region.xml",jr=".config",Vr="deveco-cli";function mt(){let r=process.env.DEVECO_CLI_DATA_DIR?A():dt.join(Gr(),jr,Vr);return dt.join(r,Hr)}function Se(){let r=mt();try{if(!pt.existsSync(r))return null;let t=pt.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 ft=Se();if(ft)v.setCountryCode(ft);else{let r=Te();r&&v.setCountryCode(r.code)}if(!v.isCN())m.info("[telemetry] background upload skipped (non-CN region)");else{let r=zr.join(A(),"TraceLogData",v.countryCode);D.init(r),(async()=>{try{await D.flush(),await D.retryFailed()}catch(e){m.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.12-Test.
|
|
3
|
+
"version": "1.3.12-Test.3",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"supportedDocsApi": 1,
|
|
6
6
|
"license": "MIT",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"ui-verification-mcp": "0.0.20",
|
|
68
68
|
"xpath": "^0.0.35",
|
|
69
69
|
"zod": "^4.4.3",
|
|
70
|
-
"@deveco-test/deveco-cli-knowledgebase": "1.3.12-Test.
|
|
70
|
+
"@deveco-test/deveco-cli-knowledgebase": "1.3.12-Test.3"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
73
|
"@types/adm-zip": "^0.5.8",
|
|
@@ -16,14 +16,22 @@ Available commands: `build`, `check`, `run`, `update`, `device`, `emulator`, `ui
|
|
|
16
16
|
## 1. Code → Build → Deploy → Run → Debug
|
|
17
17
|
|
|
18
18
|
### `devecocli create`
|
|
19
|
-
Scaffold a new HarmonyOS project.
|
|
19
|
+
Scaffold a new HarmonyOS project. Built-in templates: `empty-ability` (default) and `native-cpp` (C++/NAPI); run `create list` to see all.
|
|
20
20
|
- `--app-name <name>` (Req): 1–200 chars, `^[a-zA-Z][a-zA-Z0-9_]*$`
|
|
21
21
|
- `--project-path <path>`: Auto-created if omitted (`./<app-name>`). Must be empty if exists.
|
|
22
22
|
- `--bundle-name <bundle>`: Default `com.example.<appname-lowercase>`. 7–128 chars, ≥3 segments.
|
|
23
|
-
- `--api-level <level>`: int ≥17 (default:
|
|
23
|
+
- `--api-level <level>`: int ≥17 (default: max API of the installed DevEco Studio/HarmonyOS SDK; falls back to 23 when unavailable).
|
|
24
24
|
- `--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.
|
|
25
|
+
- `--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
26
|
*Ex*: `devecocli create --app-name MyApp --project-path ./CustomDir --api-level 23`
|
|
26
27
|
*Ex*: `devecocli create --app-name MyApp --device-types tablet`
|
|
28
|
+
*Ex*: `devecocli create --template native-cpp --app-name Shop`
|
|
29
|
+
|
|
30
|
+
### `devecocli create list`
|
|
31
|
+
List available project templates.
|
|
32
|
+
- `--format <default|json>`: `default` renders a Name/Description table; `json` prints a parseable array (fields: `name`, `bundleType`, `displayName`, `description`, `deviceTypes`).
|
|
33
|
+
*Ex*: `devecocli create list`
|
|
34
|
+
*Ex*: `devecocli create list --format json`
|
|
27
35
|
|
|
28
36
|
### `devecocli build` `[Outside sandbox]`
|
|
29
37
|
Compile and package project/modules. (Defaults: `--product default`, `--build-mode debug`)
|
|
@@ -381,7 +389,7 @@ MUTUALLY EXCLUSIVE modes for setup:
|
|
|
381
389
|
- `--path <path>`: Direct skill install path; cannot combine with `--agent`, `--project` or `--mcp`.
|
|
382
390
|
- `--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`.
|
|
383
391
|
*MCP Rules*: Configured MCP agents support global (no `--project`) and project-level setup; `qoder` is unsupported.
|
|
384
|
-
*Skill agents*: See README.md,
|
|
392
|
+
*Skill agents*: See README.md, “`init` 支持的 Skill 安装目标”. If an agent is not detected, specify `--agent`.
|
|
385
393
|
|
|
386
394
|
**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).
|
|
387
395
|
|
package/skills/index.json
CHANGED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"files": [
|
|
3
|
+
"**/*.ets"
|
|
4
|
+
],
|
|
5
|
+
"ignore": [
|
|
6
|
+
"**/src/ohosTest/**/*",
|
|
7
|
+
"**/src/test/**/*",
|
|
8
|
+
"**/src/mock/**/*",
|
|
9
|
+
"**/node_modules/**/*",
|
|
10
|
+
"**/oh_modules/**/*",
|
|
11
|
+
"**/build/**/*",
|
|
12
|
+
"**/.preview/**/*"
|
|
13
|
+
],
|
|
14
|
+
"ruleSet": [
|
|
15
|
+
"plugin:@performance/recommended",
|
|
16
|
+
"plugin:@typescript-eslint/recommended"
|
|
17
|
+
],
|
|
18
|
+
"rules": {
|
|
19
|
+
"@security/no-unsafe-aes": "error",
|
|
20
|
+
"@security/no-unsafe-hash": "error",
|
|
21
|
+
"@security/no-unsafe-mac": "warn",
|
|
22
|
+
"@security/no-unsafe-dh": "error",
|
|
23
|
+
"@security/no-unsafe-dsa": "error",
|
|
24
|
+
"@security/no-unsafe-ecdsa": "error",
|
|
25
|
+
"@security/no-unsafe-rsa-encrypt": "error",
|
|
26
|
+
"@security/no-unsafe-rsa-sign": "error",
|
|
27
|
+
"@security/no-unsafe-rsa-key": "error",
|
|
28
|
+
"@security/no-unsafe-dsa-key": "error",
|
|
29
|
+
"@security/no-unsafe-dh-key": "error",
|
|
30
|
+
"@security/no-unsafe-3des": "error"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiType": "stageMode",
|
|
3
|
+
"buildOption": {
|
|
4
|
+
"resOptions": {
|
|
5
|
+
"copyCodeResource": {
|
|
6
|
+
"enable": false
|
|
7
|
+
}
|
|
8
|
+
},
|
|
9
|
+
"externalNativeOptions": {
|
|
10
|
+
"path": "./src/main/cpp/CMakeLists.txt",
|
|
11
|
+
"arguments": "",
|
|
12
|
+
"cppFlags": "",
|
|
13
|
+
"abiFilters": [
|
|
14
|
+
"arm64-v8a",
|
|
15
|
+
"x86_64"
|
|
16
|
+
]
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"buildOptionSet": [
|
|
20
|
+
{
|
|
21
|
+
"name": "release",
|
|
22
|
+
"arkOptions": {
|
|
23
|
+
"obfuscation": {
|
|
24
|
+
"ruleOptions": {
|
|
25
|
+
"enable": false,
|
|
26
|
+
"files": [
|
|
27
|
+
"./obfuscation-rules.txt"
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"nativeLib": {
|
|
33
|
+
"debugSymbol": {
|
|
34
|
+
"strip": true,
|
|
35
|
+
"exclude": []
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
],
|
|
40
|
+
"targets": [
|
|
41
|
+
{
|
|
42
|
+
"name": "default"
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"name": "ohosTest",
|
|
46
|
+
}
|
|
47
|
+
]
|
|
48
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Define project specific obfuscation rules here.
|
|
2
|
+
# You can include the obfuscation configuration files in the current module's build-profile.json5.
|
|
3
|
+
|
|
4
|
+
# Obfuscation options:
|
|
5
|
+
# -disable-obfuscation: disable all obfuscations
|
|
6
|
+
# -enable-property-obfuscation: obfuscate the property names
|
|
7
|
+
# -enable-toplevel-obfuscation: obfuscate the names in the global scope
|
|
8
|
+
# -compact: remove unnecessary blank spaces and all line feeds
|
|
9
|
+
# -remove-log: remove all console.* statements
|
|
10
|
+
# -print-namecache: print the name cache that contains the mapping from the old names to new names
|
|
11
|
+
# -apply-namecache: reuse the given cache file
|
|
12
|
+
|
|
13
|
+
# Keep options:
|
|
14
|
+
# -keep-property-name: specifies property names that you want to keep
|
|
15
|
+
# -keep-global-name: specifies names that you want to keep in the global scope
|
|
16
|
+
|
|
17
|
+
-enable-property-obfuscation
|
|
18
|
+
-enable-toplevel-obfuscation
|
|
19
|
+
-enable-filename-obfuscation
|
|
20
|
+
-enable-export-obfuscation
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# the minimum version of CMake.
|
|
2
|
+
cmake_minimum_required(VERSION 3.5.0)
|
|
3
|
+
project(MyApplication)
|
|
4
|
+
|
|
5
|
+
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
|
|
6
|
+
|
|
7
|
+
if(DEFINED PACKAGE_FIND_FILE)
|
|
8
|
+
include(${PACKAGE_FIND_FILE})
|
|
9
|
+
endif()
|
|
10
|
+
|
|
11
|
+
include_directories(${NATIVERENDER_ROOT_PATH}
|
|
12
|
+
${NATIVERENDER_ROOT_PATH}/include)
|
|
13
|
+
|
|
14
|
+
add_library(entry SHARED napi_init.cpp)
|
|
15
|
+
target_link_libraries(entry PUBLIC libace_napi.z.so)
|