@deveco-test/deveco-cli-openharmony-arm64 0.4.0-TD.5.3 → 0.4.0-TD.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +4 -4
- package/dist/internal/telemetry-upload-background.js +1 -1
- package/index.zip +0 -0
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -5,7 +5,7 @@ var HS=Object.defineProperty;var US=(n,e)=>{for(var t in e)HS(n,t,{get:e[t],enum
|
|
|
5
5
|
`)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),v=new Date(o,i,s,a,c,l,h);return v.getTime()>t.getTime()+1440*60*1e3&&v.setFullYear(o-1),v}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let o=0;o<t.length;o++){let i=t[o];if(!r.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Ce.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Ce.resolve(Ce.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Ce.normalize(e),o=Ce.relative(r,t);if(o.split(Ce.sep)[0]===".."||Ce.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Ce.isAbsolute(e)}static isPathContained(e,t){let r=Ce.resolve(t,e),o=Ce.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=Jc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=Ce.resolve(o,e),s;try{s=Jc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};import Yp from"crypto";import X from"fs";import cs from"os";import Ge from"path";import WS from"https";var Ep={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Xi=class n{static ENDPOINT=Ep.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:o}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(o)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,o){let i=new URL(e);return new Promise((s,a)=>{let c=WS.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},l=>{let d=[];l.on("data",h=>d.push(h)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var Pp={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},Kc=class{constructor(e={}){this.config=e}config;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??Pp.identity,r=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=r[i]??t(i);o[a]=this.transform(s)}return o}},Cp=new Kc({namingStrategy:Pp.snakeCase,fieldNames:{}});import Po from"crypto";import Zi from"fs";import VS from"path";var Qi="aes-256-gcm",GS=12,qS="deveco-cli-trace-file",zS="trace-file-secret",Dp=32;function Ip(n){try{let e=Zi.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Dp?e:null}catch{return null}}function Ap(n){let e=VS.join(n,zS),t=Ip(e);if(t)return Xc(t);let r=Po.randomBytes(Dp).toString("base64");try{Zi.mkdirSync(n,{recursive:!0});try{Zi.writeFileSync(e,r,{flag:"wx"})}catch{let o=Ip(e);if(o)return Xc(o);Zi.writeFileSync(e,r)}}catch{}return Xc(r)}function Xc(n){return Po.createHash("sha256").update(qS).update(n).digest()}function Tp(n,e){let t=Po.randomBytes(GS),r=Po.createCipheriv(Qi,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i={version:1,algorithm:Qi,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(i)}function Rp(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!YS(t))return n;try{let r=Po.createDecipheriv(Qi,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function YS(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Qi&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as j from"fs";import*as is from"path";import ie from"fs";import*as es from"os";import*as K from"path";import JS from"json5";import*as kp from"os";function b(){return Zc().toLowerCase().includes("openharmony")}function Zc(){return kp.platform()}var xp=3;function ts(n){if(!ie.existsSync(n)||!ie.statSync(n).isDirectory())return!1;let e=ie.existsSync(K.join(n,"build-profile.json5")),t=ie.existsSync(K.join(n,"hvigorfile.js"))||ie.existsSync(K.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=ie.readFileSync(K.join(n,"build-profile.json5"),"utf-8");return JS.parse(r).app!==void 0}catch{return!1}}function Qc(n,e,t){if(e>=t)return null;let r=KS(n),o=XS(r);if(o)return o;for(let i of r){let s=Qc(i,e+1,t);if(s)return s}return null}function KS(n){try{let e=ie.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(K.join(n,r.name));return t}catch{return[]}}function XS(n){for(let e of n)if(ts(e))return e;return null}function Nt(n){if(!n||n.trim()==="")return null;let e=K.resolve(n),t;try{t=ie.realpathSync(e)}catch{t=e}if(!ie.existsSync(t))return null;if(ts(t))return t;let r=t;for(let o=1;o<=3;o++){let i=K.dirname(r);if(i===r)break;if(ts(i))return i;r=i}if(ie.statSync(t).isDirectory()){let o=Qc(t,0,xp);if(o)return o}return null}function ns(n){if(!n||n.trim()==="")return null;let e=K.resolve(n),t;try{t=ie.realpathSync(e)}catch{t=e}return!ie.existsSync(t)||!ie.statSync(t).isDirectory()?null:ts(t)?t:Qc(t,0,xp)}var el=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function gr(n){return K.join(n,...el)}function Np(n){return new Promise(e=>setTimeout(e,n))}var ZS=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Bn(n){let e=K.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&ZS.has(e)}function rs(n){return K.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function he(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function QS(n){return he(n)}function Wn(n){let e=QS(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function on(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??K.join(es.homedir(),"AppData","Local");return K.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?K.join(es.homedir(),"Library","Logs","devecocli-mcp-server"):K.join(es.homedir(),".local","share","devecocli-mcp-server","logs")}function Lp(n,e){let t=eb(e),r=tb(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=nb(t,n,s);return rb(e,a),o}function eb(n){let e;try{e=ie.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function tb(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function nb(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function rb(n,e){try{ie.mkdirSync(K.dirname(n),{recursive:!0})}catch{}try{ie.writeFileSync(n,e.join(`
|
|
6
6
|
`)+`
|
|
7
7
|
`,"utf8")}catch{}}function tl(n,e,t="[Cleanup]"){try{let r=K.dirname(n);if(!ie.existsSync(r))return;let o=Date.now();for(let i of ie.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&ob(K.join(r,i.name),o,e,t)}catch{}}function ob(n,e,t,r){try{let{mtimeMs:o}=ie.statSync(n);if(e-o<=t)return;ie.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}var Op="mcp-server.log",ib="mcp-server",sb={maxSize:10*1024*1024,maxFiles:4},nl=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...sb,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=on(),this.currentLogFile=is.join(this.logDir,Op),j.existsSync(this.logDir)||j.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return is.join(this.logDir,`${ib}-${e}.log.${t}`)}fileExists(e){try{return j.accessSync(e,j.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=j.readdirSync(this.logDir),t=[];for(let o of e)if(o===Op||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=is.join(this.logDir,o),s=j.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{j.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)&&j.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)&&j.renameSync(i,s)}let r=this.getRotatedFileName(e,1);j.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=j.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=j.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{j.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,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let o=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
|
|
8
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);j.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{j.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Xe=null;function Vn(n=!1){Xe&&Xe.dispose(),Xe=new nl(n)}function Mp(){Xe&&(Xe.dispose(),Xe=null)}function _p(){Xe&&Xe.flush()}function Fp(){return Xe?.getLogFilePath()??null}function jp(){return Xe?.getLogDirectory()??null}function os(){return Xe||Vn(!1),Xe}var g={debug:(n,...e)=>os().debug(n,...e),info:(n,...e)=>os().info(n,...e),warn:(n,...e)=>os().warn(n,...e),error:(n,...e)=>os().error(n,...e)};import Co from"fs";import rl from"path";var Io=300*1e3,Do=3600*1e3,ol=10080*60*1e3,yr=8*1024*1024,il=3600*1e3,$p=".pending",ab=/\.reclaim-\d+-\d+$/;function Ze(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var cb="upload-state.json";function Up(n){return rl.join(n,cb)}function lb(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ss(n){try{let e=Co.readFileSync(Up(n),"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 lb()}}function sl(n,e){try{Co.writeFileSync(Up(n),JSON.stringify(e),"utf8")}catch{}}function Bp(n){let e=ss(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),sl(n,e))}function Wp(n){let e=ss(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,sl(n,e)}function Vp(n){let e=ss(n);e.lastRetryAt=Date.now(),sl(n,e)}function al(n){let e=n.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 cl(n){if(!n.startsWith("telemetry-"))return null;let e=ab.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith($p))return null;let r=t.slice(0,-$p.length);return r.endsWith(".txt")?r:null}function ll(n){return cl(n)!==null}function db(n,e=Date.now()){try{return e-Co.statSync(n).mtimeMs>=il}catch{return!1}}function Hp(n,e=Date.now()){let t;try{t=Co.readdirSync(n)}catch{return!1}return t.some(r=>ll(r)&&db(rl.join(n,r),e))}function ub(n,e=Date.now()){if(Hp(n,e))return!0;let t=rl.join(n,"failed");if(Hp(t,e))return!0;let r;try{r=Co.readdirSync(t)}catch{return!1}for(let o of r){if(!o.startsWith("telemetry-")||!o.endsWith(".txt"))continue;let i=al(o);if(i!==null&&e-i<=ol)return!0}return!1}function Gp(n,e=Date.now()){let t=ss(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Io||ub(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Do))}import pb from"crypto";import as from"fs";import mb from"path";var fb="install-id";function hb(n){return mb.join(n,fb)}function qp(n){try{let e=as.readFileSync(n,"utf8").trim();return gb(e)?e:null}catch{return null}}function gb(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function zp(n){let e=hb(n),t=qp(e);if(t)return t;let r=pb.randomUUID();try{as.mkdirSync(n,{recursive:!0});try{as.writeFileSync(e,r,{flag:"wx"})}catch{let o=qp(e);if(o)return o;as.writeFileSync(e,r)}}catch{}return r}var Ao=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Xi;storageDir="";failedDir="";installId="";disabled=Ze();traceFileKey=Buffer.alloc(0);sessionId=Yp.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Ge.join(e,"failed"),this.cliVersion="0.4.0-TD.5.
|
|
8
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);j.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{j.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Xe=null;function Vn(n=!1){Xe&&Xe.dispose(),Xe=new nl(n)}function Mp(){Xe&&(Xe.dispose(),Xe=null)}function _p(){Xe&&Xe.flush()}function Fp(){return Xe?.getLogFilePath()??null}function jp(){return Xe?.getLogDirectory()??null}function os(){return Xe||Vn(!1),Xe}var g={debug:(n,...e)=>os().debug(n,...e),info:(n,...e)=>os().info(n,...e),warn:(n,...e)=>os().warn(n,...e),error:(n,...e)=>os().error(n,...e)};import Co from"fs";import rl from"path";var Io=300*1e3,Do=3600*1e3,ol=10080*60*1e3,yr=8*1024*1024,il=3600*1e3,$p=".pending",ab=/\.reclaim-\d+-\d+$/;function Ze(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var cb="upload-state.json";function Up(n){return rl.join(n,cb)}function lb(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ss(n){try{let e=Co.readFileSync(Up(n),"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 lb()}}function sl(n,e){try{Co.writeFileSync(Up(n),JSON.stringify(e),"utf8")}catch{}}function Bp(n){let e=ss(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),sl(n,e))}function Wp(n){let e=ss(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,sl(n,e)}function Vp(n){let e=ss(n);e.lastRetryAt=Date.now(),sl(n,e)}function al(n){let e=n.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 cl(n){if(!n.startsWith("telemetry-"))return null;let e=ab.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith($p))return null;let r=t.slice(0,-$p.length);return r.endsWith(".txt")?r:null}function ll(n){return cl(n)!==null}function db(n,e=Date.now()){try{return e-Co.statSync(n).mtimeMs>=il}catch{return!1}}function Hp(n,e=Date.now()){let t;try{t=Co.readdirSync(n)}catch{return!1}return t.some(r=>ll(r)&&db(rl.join(n,r),e))}function ub(n,e=Date.now()){if(Hp(n,e))return!0;let t=rl.join(n,"failed");if(Hp(t,e))return!0;let r;try{r=Co.readdirSync(t)}catch{return!1}for(let o of r){if(!o.startsWith("telemetry-")||!o.endsWith(".txt"))continue;let i=al(o);if(i!==null&&e-i<=ol)return!0}return!1}function Gp(n,e=Date.now()){let t=ss(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Io||ub(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Do))}import pb from"crypto";import as from"fs";import mb from"path";var fb="install-id";function hb(n){return mb.join(n,fb)}function qp(n){try{let e=as.readFileSync(n,"utf8").trim();return gb(e)?e:null}catch{return null}}function gb(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function zp(n){let e=hb(n),t=qp(e);if(t)return t;let r=pb.randomUUID();try{as.mkdirSync(n,{recursive:!0});try{as.writeFileSync(e,r,{flag:"wx"})}catch{let o=qp(e);if(o)return o;as.writeFileSync(e,r)}}catch{}return r}var Ao=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Xi;storageDir="";failedDir="";installId="";disabled=Ze();traceFileKey=Buffer.alloc(0);sessionId=Yp.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Ge.join(e,"failed"),this.cliVersion="0.4.0-TD.5.4",this.nodeVersion=process.version,this.installId=zp(e).replace(/-/g,""),this.traceFileKey=Ap(e),X.mkdirSync(e,{recursive:!0}),X.mkdirSync(this.failedDir,{recursive:!0}),g.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,g.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,g.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,g.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");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 r=t,o=Date.now();try{let i=await r(),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,r,o){let i=this.buildTraceEvent(e,t,r,o);try{let s=Tp(JSON.stringify(i),this.traceFileKey);await X.promises.appendFile(this.currentFile(),s+`
|
|
9
9
|
`,"utf8"),Bp(this.storageDir)}catch{}}buildTraceEvent(e,t,r,o){let i=`${n.EVENT_PREFIX}${e.event}`,s=Cp.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:Yp.randomUUID(),trace_os_version:n.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:r,error_code:o,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=cs.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=cs.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 cs.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(cs.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return Ge.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){g.debug("[telemetry] scheduler not started (telemetry disabled)");return}g.debug(`[telemetry] scheduler started (flush every ${Io/1e3}s, retry failed every ${Do/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Io)},Io),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Do)},Do)}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),g.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return Wp(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let e=Date.now(),t;try{t=await X.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>Ge.join(this.failedDir,i)),o=!0;for(let i of r){let s=Ge.basename(i),a=al(s);if(a!==null){if(e-a>ol){try{await X.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||g.warn("[telemetry] retry failed"),Vp(this.storageDir),o}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await X.promises.readdir(t)}catch{continue}for(let o of r)ll(o)&&await this.reclaimOrphan(Ge.join(t,o),e)}}async reclaimOrphan(e,t){let r;try{let l=await X.promises.stat(e);if(t-l.mtimeMs<il)return;r=l.size}catch{return}let o=Ge.dirname(e),i=cl(Ge.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=Ge.join(o,i),c=yr-await this.fileSize(a);if(r>c){try{await X.promises.unlink(s)}catch{}g.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){g.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}g.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let o=Ge.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await X.promises.rename(e,o)}catch{return null}return await this.touch(o),o}async mergeOrphanInto(e,t){try{await X.promises.appendFile(t,await X.promises.readFile(e))}catch(r){return g.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await X.promises.unlink(e)}catch(r){g.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(e){try{return(await X.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await X.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await X.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>Ge.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>yr){g.warn(`[telemetry] ${Ge.basename(e)} is ${t} bytes (> ${yr}), dropped without uploading`);try{await X.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await X.promises.rename(e,r)}catch{return!1}await this.touch(r);let o;try{o=await X.promises.readFile(r,"utf8")}catch{return!1}let i=o.split(`
|
|
10
10
|
`).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await X.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,i)}collectDecryptBatch(e,t){let r=[],o=16,i=t;for(;i<e.length&&r.length<n.MAX_BATCH;){let s=Rp(e[i],this.traceFileKey);if(s===null){i++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&o+a>n.MAX_PAYLOAD_BYTES)break;r.push(s),o+=a,i++}return{batch:r,next:i}}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let o=r,{batch:i,next:s}=this.collectDecryptBatch(t,r);r=s;let a=this.buildPayloadItems(i);if(a.length===0)continue;let c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){g.warn("[telemetry] upload failed");let d=t.slice(o).join(`
|
|
11
11
|
`)+`
|
|
@@ -73,7 +73,7 @@ Available runnable modules:
|
|
|
73
73
|
Installing artifacts to ${Dt(e)?"local machine":"device "+e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(Bo(`
|
|
74
74
|
Application '${t}': ${s}`))}else console.log(`
|
|
75
75
|
Application '${t}' installed successfully (no ability to launch).`)}function FP(n){let e={event:D.CommandExecuted,args:["run",...n.module?["--module"]:[],...n.device?["--device"]:[],...n.product?["--product"]:[],...n.buildMode?["--build-mode"]:[],...n.ability?["--ability"]:[],...n.uninstall?["--uninstall"]:[],...n.skipBuild?["--skip-build"]:[],...n.apply?["--apply"]:[],...n.hotreload?["--hotreload"]:[],...n.hotreloadApply?["--hotreload-apply"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.module&&(e.module_count=n.module.length),e}var Ul=new xP("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/");b()||Ul.option("--hotreload [action]",'Start hot-reload mode (build+deploy with daemon, then exit). Use "stop" to shut down the hvigor daemon.').option("--hotreload-apply <fileName>","Hot-reload changed files (.hvigor/<fileName> list) via daemon hot compile + signed hqf + quickfix, without restarting the app.");Ul.action(async n=>{let e=FP(n),t=Date.now(),r=!0,o=null;try{let i=await UP(n,e);i&&(i.ohpmMemoryMb&&(e.ohpm_install_memory=i.ohpmMemoryMb),i.syncMemoryMb&&(e.hvigor_sync_memory=i.syncMemoryMb),i.buildMemoryMb&&(e.hvigor_build_memory=i.buildMemoryMb))}catch(i){r=!1,o=Y(i),console.error(NP(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}});async function jP(n,e,t,r,o){let i=new ln(e,n.rootDir),s=new Le(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:k}of t)for(let ae of n.collectNonHarDependentModuleList(w))a.add(`${ae}@${k}`),c.add(ae);let l=[...a],d=Oo(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)Ns.generate(n.rootDir,w,r,e);let v=await Ft(n.rootDir,()=>Mo(i,s,r,o,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
|
|
76
|
-
`+Bo("Build completed successfully.")),v}async function $P(n,e,t,r,o){let i=new $t(t),s=se.from(t),a=r[0]?.moduleName||o[0];await tf(n,e,t,i,s,a)}function HP(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new T(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}}async function UP(n,e){let t=J.discover(process.cwd());console.warn(Us("Ensure the project source is trusted before proceeding."));let r=await A.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await WP(n,t,r);return}if(n.hotreload){await BP(n,t,r);return}if(n.apply){await GP(n,t,r);return}return of(n,t,r)}async function BP(n,e,t){if(n.hotreload==="stop"){await Qm(t,e);return}let o=Hl(e,n.module).map($l),{moduleName:i,targetName:s}=o[0];Ml(n.module,i);let a=new $t(t),c=se.from(t),l=await Ws(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let v=e.getBundleName(),w=nf(e,o,n.ability);Ls.generate(e.rootDir,i,h,t);let k=new Le(t,e.rootDir);console.log(Bo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await k.ensureDaemonRunning();let ae=[`${i}@${h}`];for(let lt of e.collectNonHarDependentModuleList(i))ae.includes(`${lt}@${h}`)||ae.push(`${lt}@${h}`);console.log(Bo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Ve=new Ar(e.rootDir,t);await Ve.startWatchSession({moduleSpecs:ae,productName:h});let ct=Zm(e,i,s,d,h);await rf(a,l,v,ct,w,!!n.uninstall),console.log(Bo("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),Ve.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function WP(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=Hl(e,n.module),{moduleName:i}=$l(o[0]);Ml(n.module,i);let s=se.from(t),a=await Ws(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Xm(e,i,r);let d=[`${i}@${c}`],h=await Km({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function VP(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(i)){o.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))o.add(c)}return[...o]}async function of(n,e,t){let r=Hl(e,n.module),o=r.map($l),i=se.from(t);if(await ef(n.device,i)){await $P(n,e,t,o,r);return}HP(e,o);let s=new $t(t),a=await Ws(i,n.device),c=!b()&&(a.includes("127.0.0.1")||a.includes("localhost")),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",h;n.skipBuild||(h=await jP(e,t,o,l,d));let v=VP(e,o,c,l),w=e.getBundleName(),k=nf(e,o,n.ability);return await rf(s,a,w,v,k,!!n.uninstall),h}async function GP(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Bs.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=Bs.join(e.rootDir,".hvigor",r),i=se.from(t),s=await Ws(i,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(v=>e.getModuleType(v.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new xs(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(Us("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(v){console.warn(Us(`[Apply] \u5931\u8D25\uFF1A${v.message}`)),console.warn(Us("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await of(n,e,t)}var sf=Ul;import{Command as qP}from"commander";import{green as af,red as cf,cyan as Bl}from"colorette";import{execa as lf}from"execa";function zP(){return"hmos"}function YP(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-openharmony-arm64"}function JP(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"0.4.0-TD.5.
|
|
76
|
+
`+Bo("Build completed successfully.")),v}async function $P(n,e,t,r,o){let i=new $t(t),s=se.from(t),a=r[0]?.moduleName||o[0];await tf(n,e,t,i,s,a)}function HP(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new T(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}}async function UP(n,e){let t=J.discover(process.cwd());console.warn(Us("Ensure the project source is trusted before proceeding."));let r=await A.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await WP(n,t,r);return}if(n.hotreload){await BP(n,t,r);return}if(n.apply){await GP(n,t,r);return}return of(n,t,r)}async function BP(n,e,t){if(n.hotreload==="stop"){await Qm(t,e);return}let o=Hl(e,n.module).map($l),{moduleName:i,targetName:s}=o[0];Ml(n.module,i);let a=new $t(t),c=se.from(t),l=await Ws(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let v=e.getBundleName(),w=nf(e,o,n.ability);Ls.generate(e.rootDir,i,h,t);let k=new Le(t,e.rootDir);console.log(Bo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await k.ensureDaemonRunning();let ae=[`${i}@${h}`];for(let lt of e.collectNonHarDependentModuleList(i))ae.includes(`${lt}@${h}`)||ae.push(`${lt}@${h}`);console.log(Bo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Ve=new Ar(e.rootDir,t);await Ve.startWatchSession({moduleSpecs:ae,productName:h});let ct=Zm(e,i,s,d,h);await rf(a,l,v,ct,w,!!n.uninstall),console.log(Bo("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),Ve.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function WP(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=Hl(e,n.module),{moduleName:i}=$l(o[0]);Ml(n.module,i);let s=se.from(t),a=await Ws(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Xm(e,i,r);let d=[`${i}@${c}`],h=await Km({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function VP(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(i)){o.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))o.add(c)}return[...o]}async function of(n,e,t){let r=Hl(e,n.module),o=r.map($l),i=se.from(t);if(await ef(n.device,i)){await $P(n,e,t,o,r);return}HP(e,o);let s=new $t(t),a=await Ws(i,n.device),c=!b()&&(a.includes("127.0.0.1")||a.includes("localhost")),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",h;n.skipBuild||(h=await jP(e,t,o,l,d));let v=VP(e,o,c,l),w=e.getBundleName(),k=nf(e,o,n.ability);return await rf(s,a,w,v,k,!!n.uninstall),h}async function GP(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Bs.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=Bs.join(e.rootDir,".hvigor",r),i=se.from(t),s=await Ws(i,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(v=>e.getModuleType(v.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new xs(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(Us("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(v){console.warn(Us(`[Apply] \u5931\u8D25\uFF1A${v.message}`)),console.warn(Us("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await of(n,e,t)}var sf=Ul;import{Command as qP}from"commander";import{green as af,red as cf,cyan as Bl}from"colorette";import{execa as lf}from"execa";function zP(){return"hmos"}function YP(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-openharmony-arm64"}function JP(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"0.4.0-TD.5.4"}var KP={event:D.CommandExecuted,args:["update"]};async function Wl(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(KP,r).catch(()=>{})}async function XP(n,e,t){let r=Y(t);console.error(cf(`Failed to update ${n}`));let o=t instanceof Error?t.message:"";o&&console.error(cf(o)),await Wl(e,!1,r),process.exit(1)}var ZP=new qP("update").description("Update deveco-cli to latest").action(async()=>{let n=YP(),e=JP(),t=zP(),r=Date.now();console.log(Bl("Checking for updates..."));try{let{stdout:o}=await lf("npm",["view",n,`dist-tags.${t}`]),i=o.trim();if(!i||i===e){console.log(af(`
|
|
77
77
|
${n} is already up to date (v${e}, tag: ${t})`)),await Wl(r,!0,null);return}console.log(Bl(`
|
|
78
78
|
New version found: ${i} (current: ${e})`)),console.log(Bl(`Updating ${n}...`)),await lf("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
|
|
79
79
|
`+af(`${n} updated successfully to version ${i}.`)),await Wl(r,!0,null)}catch(o){await XP(n,r,o)}}),df=ZP;import{Command as AC}from"commander";import{execa as Gs}from"execa";function Ie(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as QP}from"child_process";var eC=2500;function tC(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function nC(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,eC);n.once("error",d=>c(d.message)),tC(n,l,s,a,c,i)}function uf(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=QP(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),nC(s,i,r,o)})}import*as Tr from"path";function rC(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function oC(n){let e=n.instancePath?.trim();if(e)return Tr.dirname(Tr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Tr.dirname(Tr.normalize(t)).replace(/\\/g,"/"):""}function iC(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function pf(n,e){return e?[...n,"-bootmode",e]:n}function sC(n,e,t){let r=[pf(["-start",n],t)],o=oC(e);if(o)for(let i of iC(e.imageRoot))r.push(pf(["-hvd",n,"-path",o,...i],t));return rC(r)}async function mf(n,e,t,r){let o=new Error("No start strategy ran"),i=sC(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function Vl(n){return(await se.withHdcPath(n).listDevices()).map(t=>t.serial).filter(_o)}async function Gl(n){let e=await Vl(n);return e.length===0?[]:(await Promise.all(e.map(r=>Ts(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ff(n,e){return(await Gl(n)).includes(e)}import*as kr from"path";import{existsSync as aC,statSync as cC}from"fs";function Rr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function lC(n){let e=Rr(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function dC(n){return Rr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function uC(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=kr.dirname(kr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=kr.join(t,r.name);aC(o)&&cC(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function pC(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=dC(t),o=Rr(t,["deviceType","DeviceType","devicetype"]),i=Rr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:lC(t),path:Rr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Rr(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function mC(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function hf(n){let t=pC(n)??mC(n);return uC(t),t}function ql(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function fC(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function hC(n){if(!fC(n))return null;let e=ql(n,["osVersion","OsVersion","OSVersion"]),t=ql(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=ql(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Vs(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=hC(o);i&&r.push(i)}return r}catch{return[]}}function gf(n){let t=Vs(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var yf=/no images are available/i,gC="7.0.0",yC={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"]};function ft(n){return n.normalize("NFKC").trim().toLowerCase()}function vC(n,e){let t=n.deviceType?.trim(),r=t?yC[ft(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function wC(n){let e=n.message||"";return yf.test(e)}function SC(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Wo(n,e){return`${n} ${e.join(" ")}`.trim()}function bC(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var xr=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${Wo(this.emulatorPath,e)}`),Gs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return uf(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return hf(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(Ie(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=Ie(e),o=t.find(a=>Ie(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await mf(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
@@ -1312,7 +1312,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1312
1312
|
`):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of o){await dT(cT);try{let l=await this.checkFile(c);r.push(lT(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let i=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1313
1313
|
`)),r.length>0&&s.push(r.join(`
|
|
1314
1314
|
`));let a=s.join(`
|
|
1315
|
-
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Wn(e),r=await Sn.promises.readFile(e,"utf8"),o=rs(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,o=[];for(let i of e){let s=Xr.resolve(Xr.isAbsolute(i)?i:Xr.join(r,i));if(!Sn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!Sn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Bn(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(Sn.realpathSync(s))}catch{o.push(s)}}return o}};function lT(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function dT(n){return new Promise(e=>setTimeout(e,n))}import*as Qr from"fs";import*as Va from"path";var Zr=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Jr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return Wa(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Jr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Wa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Jr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Wa("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Wn(e),o=await Qr.promises.readFile(e,"utf8"),i=rs(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Va.isAbsolute(e)?e:Va.join(this.manager.projectRoot,e);return!Qr.existsSync(t)||!Qr.statSync(t).isFile()||!Bn(t)?null:t}};import{spawn as uT}from"child_process";import*as qa from"fs";import*as kg from"path";var pT=30*1e3,mT=30*1e3,Ga=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new gn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new hn(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,Qe),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},mT);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${V(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=uT(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Sr(this.config.workspaceRoot),t=pt(e),r=kg.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.4.0-TD.5.3"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=pT){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:N,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:N,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:N,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{qa.existsSync(this.config.logPath)||qa.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),pt(r)}}catch{}return e}};import*as mi from"path";import*as Kt from"fs";var fi=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===A.OPENHARMONY_STUDIO_ROOT)return;let e=gr(this.projectRoot);if(!Kt.existsSync(e))return;let t=Kt.readFileSync(e,"utf8");if(!t.includes(Is))return;let r=t.replaceAll(Is,this.config.toolProvider.sdkPath);Kt.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Is} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(qn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await Ss(e,async()=>{try{return await Im(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Qe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Nt(this.config.workspaceRoot);this.resolvedRoot=e?he(e):he(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Cs(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=mi.dirname(gr(this.resolvedRoot));try{Kt.mkdirSync(o,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new Ga({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=mi.join(on(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=mi.join(e,"lsp-log",t);return Kt.mkdirSync(r,{recursive:!0}),he(r)}catch{return"auto"}}};function xg(n){let e=Es(n);return f.info(`[SyncGuard] ${e.reason}`),e}var Od=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(Od||{}),Lg=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(Lg||{}),kt=3,Nd=600*1e3,Ld=100,za=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e){this.config=e,Vn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=Nt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new fT({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Td(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:fe.object({target:fe.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:fe.object({files:fe.array(fe.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=fe.object({file:fe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:fe.number().describe("Line number (0-based)"),character:fe.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:fe.object({query:fe.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:fe.object({file:fe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:fe.object({file:fe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:fe.number().describe("Line number (0-based)"),character:fe.number().describe("Character offset in the line (0-based)"),direction:fe.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=bn.join(bn.dirname(e),"standardIndex","index.js"),r=Ng.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=x.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1315
|
+
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Wn(e),r=await Sn.promises.readFile(e,"utf8"),o=rs(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,o=[];for(let i of e){let s=Xr.resolve(Xr.isAbsolute(i)?i:Xr.join(r,i));if(!Sn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!Sn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Bn(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(Sn.realpathSync(s))}catch{o.push(s)}}return o}};function lT(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function dT(n){return new Promise(e=>setTimeout(e,n))}import*as Qr from"fs";import*as Va from"path";var Zr=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Jr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return Wa(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Jr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Wa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Jr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Wa("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Wn(e),o=await Qr.promises.readFile(e,"utf8"),i=rs(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Va.isAbsolute(e)?e:Va.join(this.manager.projectRoot,e);return!Qr.existsSync(t)||!Qr.statSync(t).isFile()||!Bn(t)?null:t}};import{spawn as uT}from"child_process";import*as qa from"fs";import*as kg from"path";var pT=30*1e3,mT=30*1e3,Ga=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new gn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new hn(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,Qe),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},mT);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${V(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=uT(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Sr(this.config.workspaceRoot),t=pt(e),r=kg.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.4.0-TD.5.4"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=pT){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:N,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:N,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:N,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{qa.existsSync(this.config.logPath)||qa.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),pt(r)}}catch{}return e}};import*as mi from"path";import*as Kt from"fs";var fi=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===A.OPENHARMONY_STUDIO_ROOT)return;let e=gr(this.projectRoot);if(!Kt.existsSync(e))return;let t=Kt.readFileSync(e,"utf8");if(!t.includes(Is))return;let r=t.replaceAll(Is,this.config.toolProvider.sdkPath);Kt.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Is} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(qn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await Ss(e,async()=>{try{return await Im(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Qe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Nt(this.config.workspaceRoot);this.resolvedRoot=e?he(e):he(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Cs(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=mi.dirname(gr(this.resolvedRoot));try{Kt.mkdirSync(o,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new Ga({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=mi.join(on(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=mi.join(e,"lsp-log",t);return Kt.mkdirSync(r,{recursive:!0}),he(r)}catch{return"auto"}}};function xg(n){let e=Es(n);return f.info(`[SyncGuard] ${e.reason}`),e}var Od=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(Od||{}),Lg=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(Lg||{}),kt=3,Nd=600*1e3,Ld=100,za=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e){this.config=e,Vn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=Nt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new fT({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Td(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:fe.object({target:fe.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:fe.object({files:fe.array(fe.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=fe.object({file:fe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:fe.number().describe("Line number (0-based)"),character:fe.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:fe.object({query:fe.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:fe.object({file:fe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:fe.object({file:fe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:fe.number().describe("Line number (0-based)"),character:fe.number().describe("Character offset in the line (0-based)"),direction:fe.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=bn.join(bn.dirname(e),"standardIndex","index.js"),r=Ng.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=x.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1316
1316
|
`)}],isError:!0}:null}let r=e.filter(o=>bn.isAbsolute(o));return r.length>0?(g.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
|
|
1317
1317
|
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Ld)return g.warn(`check tool called with ${t.length} files (max: ${Ld})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Ld}.`}],isError:!0};let{etsFiles:r,cppFiles:o,unsupported:i}=gT(t);i.length>0&&g.warn(`Unsupported file types in check request: ${i.join(", ")}`);let s=i.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1318
1318
|
`),s.join(`
|
|
@@ -1427,4 +1427,4 @@ Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVe
|
|
|
1427
1427
|
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let o of t)try{let i=await QM(o,n),s=await e_(o,n);i.length>0&&r.push({udid:i,type:s})}catch{m(`Failed to get device info for ${o}, skipping`)}return r}async function QM(n,e){m(`Executing: ${e} -t ${n} shell bm get -u`);let{stdout:t}=await mp(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
|
|
1428
1428
|
`);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=r.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function e_(n,e){let t="hw_sc.build.os.deviceType";m(`Executing: ${e} -c -t ${n} shell getprop ${t}`);let{stdout:r}=await mp(e,["-c","-t",n,"shell","getprop",t],{stdio:["ignore","pipe","pipe"]});return t_(r)}function t_(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import fr from"fs";import{createHash as n_}from"crypto";import{Buffer as xS}from"buffer";import{createPublicKey as r_,X509Certificate as fp}from"crypto";import{readFileSync as o_}from"fs";import hr from"node-forge";async function NS(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${re.BASE_URL}${re.PROVISION_ADD_TEST_PATH}`,h=i_(t,r),v=await a_(n,d,a||[],r,s,h,i||[]);if(!v||!v.profileInfo||!v.profileInfo.provisionFileUrl)throw m("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let w=v.profileInfo,ae=(await u_(n,w.provisionFileUrl)).urlList,Ve=v.profileInfo.id;if(ae&&ae.length>0){let ct=await dS(t,o),lt=ct.profilePath;if(!await p_(ae,lt))throw await kS(n,Ve),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await kS(n,Ve),fr.existsSync(ct.certPath)&&fr.existsSync(lt)&&fr.existsSync(ct.p12Path)){let zc=fr.readFileSync(ct.certPath,"utf8"),Yc=fr.readFileSync(lt,"utf8");return m_(Yc,zc,ct.p12Path,c,l)||d_(lt),lt}}throw new Error(E.ADD_PROFILE_FAIL)}function i_(n,e){let t=n?`${n}_`:"";return`${s_(`${t}${e}_${e}`)}`}function s_(n){return n_("sha256").update(n).digest("hex").substring(0,16)}async function a_(n,e,t,r,o,i,s){c_(r);let a=gp(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await O.postAllowFailure(e,{headers:a,params:c});if(!l)throw m("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw hp(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw m(`add provision fail: ${l.data}`),l_(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:h}}}function hp(n,e,t){return n===St.FORBIDDEN?e===Ee.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===St.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(Ee.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function c_(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Be.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function l_(n,e){if(n.includes(Ee.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(Ee.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function kS(n,e){if(!e||e.trim().length===0)return;let t=`${re.BASE_URL}${re.PROVISION_DELETE_PATH}?id=${e}`,r=await O.deleteAllowFailure(t,{headers:gp(n)});if(r.statusCode!==200)throw hp(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&m(`delete provision failed: ${r.data}`)}function d_(...n){for(let e of n)try{fr.existsSync(e)&&fr.unlinkSync(e)}catch(t){m(`delete local sign file error: ${t.message}`)}}async function u_(n,e){let t=`${re.BASE_URL}${re.CERT_DOWNLOAD_URL_PATH}`,r=gp(n),o={sourceUrls:e},i=await O.postAllowFailure(t,{headers:r,params:o});if(!i)throw m("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw hp(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw m("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function p_(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await qi(t,e),!0}function m_(n,e,t,r,o){return f_(n,e),r=r||Be.TARGET_FRIENDLY_NAME,o=o||"",h_(e,t,r,o),!0}function f_(n,e){if(e.lastIndexOf(Be.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Be.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function h_(n,e,t,r){let o=n.matchAll(Be.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=g_(l),h=new Date(d.validFrom),v=new Date(d.validTo);if(s<h||s>v){let w=`Certificate is not valid, Valid from ${h} to ${v}`;throw console.warn(`checkCertificateInValidityPeriod: ${w}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!v_(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function g_(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new fp(t);let r=xS.from(t,"base64");return new fp(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function y_(n){if(n.cert){let e=hr.pki.publicKeyToPem(n.cert.publicKey);return r_(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=hr.asn1.toDer(n.asn1).getBytes(),t=xS.from(e,"binary");return new fp(t).publicKey.export({type:"spki",format:"der"})}catch(e){return m(`Failed to parse cert from asn1: ${e}`),null}return null}function v_(n,e,t,r){try{let o=o_(n),i=hr.asn1.fromDer(hr.util.createBuffer(o)),c=hr.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:hr.pki.oids.certBag})[hr.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=y_(l);if(!h)continue;if(r.some(w=>{let k=w.publicKey.export({type:"spki",format:"der"});return h.equals(k)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return m(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function gp(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var OS="https://developer.huawei.com",w_={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},S_="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function b_(n){let e=w_[n];return e?`${OS}${e}`:void 0}function E_(){return`${OS}${S_}`}var P_={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function LS(n,e){return(P_[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function C_(n){return Array.from(n).join(", ")}function MS(n,e){if(n.size===0)return;let t=$n.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let v=b_(h.permissionName);v!=null&&(h.permissionHelpUrlKey=v)}let o=new Set;for(let h of r)o.add(h.permissionDisplayName);let i=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let v=h.permissionInsteadName??h.permissionDisplayName;i.add(`${v} (${h.permissionHelpUrlKey})`)}let s=E_(),a=LS("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=LS("acl.permissions.warn",[C_(o),l,c]);console.log(d)}var Bc=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=J.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(oe.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:oe.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import I_ from"fs";import _S from"path";var Wc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(oe.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=_S.join(t,"default","openharmony","toolchains","lib",r);if(!I_.existsSync(o)){let i=_S.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Vc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Re.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Re.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(oe.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(oe.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(oe.TEAM_INFO_FAILED);try{if((await mn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(oe.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(oe.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(oe.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(oe.REALNAME_REQUIRED)):{passed:!0,message:""}:e(oe.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await mn();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return m(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(oe.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(oe.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function D_(n){try{let{teamList:e}=await mn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function A_(n){let e=await Re.getUserInfo(),t=await Re.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await D_(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Uc(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Gc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t,r=!1){if(r)return m("[EnvCheck] Scenario 4 Device check: --udid provided, skipping device detection"),{passed:!0,message:""};try{let o=await A_(t);return o.length>0?(m(`[EnvCheck] Scenario 4 Device check: ${o.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""}):(m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc"),(await se.from(this.toolProvider).listDevices()).length>0?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(oe.DEVICE_MISSING)))}catch(o){return m(`[EnvCheck] Scenario 4 Device check failed: ${o.message}`),e(oe.DEVICE_DETECT_FAILED)}}};var qc=class{projectChecker=new Bc;toolchainChecker=null;authChecker=new Vc;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await A.new();return this.toolchainChecker=new Wc(e),this.deviceChecker=new Gc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(oe.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId,e.hasManualDevices??!1))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function x_(n){if(vp.existsSync(n)){let e=vp.readFileSync(n,"utf-8");return k_.parse(e)}return{app:{signingConfigs:[],products:[]}}}function N_(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function L_(n){if(n.keyPwd===n.storePassword){let r=await jn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await jn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await jn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function O_(n,e,t){let r=FS.join(n,"build-profile.json5"),o=x_(r);N_(o);let i=t??"default",{keyPassword:s,storePassword:a}=await L_(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:bt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(h=>h.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(h=>h.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),vp.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function M_(n){let e=await Re.getUserInfo(),t=await Re.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function __(n){let e=n.product||"default",t=qu(n.udid??[]);await new qc().preflight({productName:e,teamId:n.teamId,hasManualDevices:t.length>0}),console.log("Executing signature generate command");let o=await M_(n),i=await A.new(),{shouldRegenerate:s}=await Ji.shouldRegenerate({force:n.force??!1,teamId:o.teamId,productName:n.product,manualUdids:t.map(a=>a.udid)},i);if(!s){console.log(yp("Signature generation completed successfully."));return}await j_(n,o,i,t),console.log(yp("Signature generation completed successfully."))}function F_(n){console.log(`Profile covers ${n.length} device(s):`);for(let e of n){let t=e.source==="manual"&&e.typeInferred?"manual, type inferred":e.source;console.log(` ${e.udid} ${e.type.padEnd(12)} (${t})`)}}async function j_(n,e,t,r){let o=await op(e,n.product),i=$_(n,e,o,t),{allDeviceIds:s,devices:a}=await AS(e,t.hdcPath,r);i.allDeviceIds=s,await NS(e,i),F_(a);let c=J.discover(process.cwd()).rootDir;await O_(c,o,n.product??"default"),console.log(yp(`Signing config written to ${FS.join(c,"build-profile.json5")}`))}function $_(n,e,t,r){let o=process.cwd(),i=J.discover(o),s=$c(i,r);return MS(s,i),{productName:n.product||"default",bundleName:i.getBundleName(),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var jS=new T_("signature").description("Generate application signature.");jS.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").option("--udid <udid...>",'Add device UDID(s) that are not connected. Repeatable or comma-separated; append ":<type>" to declare phone|wearable|liteWearable|tv (default: phone).').action(async n=>{let e={event:D.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[],...n.udid?["--udid",String(zu(n.udid))]:[]]},t=Date.now(),r=!0,o=null;try{await __(n)}catch(i){r=!1,o=Y(i),console.error(R_(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await I.track(e,i)}});var $S=jS;if(!Ze())try{I.init(Sp.join(Xt(),"TraceLogData")),I.startScheduler()}catch(n){g.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Ze())try{let n=await A.new();I.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?I.setCltVersion(e):I.setStudioVersion(e))}catch(n){g.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();le.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1429
1429
|
|
|
1430
|
-
Privacy: ${bo.PRIVACY_URL}`).version("0.4.0-TD.5.
|
|
1430
|
+
Privacy: ${bo.PRIVACY_URL}`).version("0.4.0-TD.5.4");le.addCommand(Rm);le.addCommand(sf);le.addCommand(df);le.addCommand(Cf);le.addCommand(bh);le.addCommand(zh);le.addCommand(Xh);le.addCommand(cg);le.addCommand(yg);le.addCommand(Fg);le.addCommand(Yv);le.addCommand($S);le.addCommand(Zw);le.addCommand(ww);b()||le.addCommand(Zf);var wp=process.argv.slice(2);wp.length>=2&&wp[wp.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var U_=new Set(["update","auth"]);le.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==le;)t=t.parent;U_.has(t.name())||await A.checkVersion()});le.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{dl(Sp.join(Xt(),"TraceLogData"))}catch(n){g.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(H_(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import Wt from"path";import*as S from"fs";import*as Y from"path";import{homedir as xt}from"os";import*as W from"fs";import*as g from"path";function J(n){let t=g.resolve(n),e=[],r=t;for(;;)try{let i=W.realpathSync(r);return e.length===0?i:g.join(i,...e.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=g.dirname(r);if(o===r)return t;e.push(g.basename(r)),r=o}}function N(n){let t=n.trim();return(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1).trim()),t}function K(n){let t=N(n);if(!t)throw new Error("Path must not be empty.");return J(t)}var Et="deveco-cli",X,$=class extends Error{constructor(t){super(t),this.name="CliDataDirError"}};function wt(){let n=process.env.DEVECO_CLI_DATA_DIR,e=(n===void 0||n===""?"":N(n))||Y.join(xt(),".local","share",Et);try{return K(e)}catch(r){throw new $(r instanceof Error?r.message:String(r))}}function G(){if(X!==void 0)return X;let n=wt();try{if(S.existsSync(n))return S.realpathSync(n)}catch{}return n}import bt from"crypto";import c from"fs";import P from"os";import m from"path";import Ct from"https";var q={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var D=class n{static ENDPOINT=q.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(t,e){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:e.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(t,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(t,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(t){try{let e=JSON.parse(t),r=e?.code??e?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(t,e,r,i){let o=new URL(t);return new Promise((s,l)=>{let p=Ct.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:e,timeout:i},h=>{let w=[];h.on("data",Tt=>w.push(Tt)),h.on("end",()=>{s({code:h.statusCode??0,body:Buffer.concat(w).toString("utf8")})})});p.on("timeout",()=>{p.destroy(new Error("request timeout"))}),p.on("error",l),p.write(r),p.end()})}};var Z={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},M=class{constructor(t={}){this.config=t}config;serialize(t){let e=this.transform(t);return this.config.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}toObject(t){return this.transform(t)}transform(t){if(t==null)return t;if(Array.isArray(t))return t.map(o=>this.transform(o));if(typeof t!="object")return t;let e=this.config.namingStrategy??Z.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(t)){let l=r[o]??e(o);i[l]=this.transform(s)}return i}},Q=new M({namingStrategy:Z.snakeCase,fieldNames:{}});import b from"crypto";import C from"fs";import Lt from"path";var L="aes-256-gcm",_t=12,Ft="deveco-cli-trace-file",At="trace-file-secret",et=32;function tt(n){try{let t=C.readFileSync(n,"utf8").trim();return t&&Buffer.from(t,"base64").length===et?t:null}catch{return null}}function rt(n){let t=Lt.join(n,At),e=tt(t);if(e)return j(e);let r=b.randomBytes(et).toString("base64");try{C.mkdirSync(n,{recursive:!0});try{C.writeFileSync(t,r,{flag:"wx"})}catch{let i=tt(t);if(i)return j(i);C.writeFileSync(t,r)}}catch{}return j(r)}function j(n){return b.createHash("sha256").update(Ft).update(n).digest()}function nt(n,t){let e=b.randomBytes(_t),r=b.createCipheriv(L,t,e),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:L,ciphertext:i.toString("base64"),iv:e.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function it(n,t){let e;try{e=JSON.parse(n)}catch{return null}if(!kt(e))return n;try{let r=b.createDecipheriv(L,t,Buffer.from(e.iv,"base64"));return r.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([r.update(Buffer.from(e.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function kt(n){if(!n||typeof n!="object")return!1;let t=n;return t.version===1&&t.algorithm===L&&typeof t.ciphertext=="string"&&typeof t.iv=="string"&&typeof t.authTag=="string"}import*as a from"fs";import*as A from"path";import*as _ from"os";import*as y from"path";import ye from"json5";import*as ot from"os";function B(){return Ot().toLowerCase().includes("openharmony")}function Ot(){return ot.platform()}var Se=[B()?".bitfun":".idea",".deveco",B()?".cxx":"cxx","compile_commands.json"];function st(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??y.join(_.homedir(),"AppData","Local");return y.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?y.join(_.homedir(),"Library","Logs","devecocli-mcp-server"):y.join(_.homedir(),".local","share","devecocli-mcp-server","logs")}var at="mcp-server.log",It="mcp-server",Rt={maxSize:10*1024*1024,maxFiles:4},U=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(t,e){this.rotationOptions={...Rt,...e},this.minLevel=t?"debug":"info",t?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=st(),this.currentLogFile=A.join(this.logDir,at),a.existsSync(this.logDir)||a.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${i}`}getRotatedFileName(t,e){return A.join(this.logDir,`${It}-${t}.log.${e}`)}fileExists(t){try{return a.accessSync(t,a.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let t=a.readdirSync(this.logDir),e=[];for(let i of t)if(i===at||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=A.join(this.logDir,i),s=a.statSync(o);e.push({name:i,mtime:s.mtime,path:o})}e.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<e.length;i++)try{a.unlinkSync(e[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let t=this.getCurrentDateString(),e=this.getRotatedFileName(t,this.rotationOptions.maxFiles);this.fileExists(e)&&a.unlinkSync(e);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(t,i),s=this.getRotatedFileName(t,i+1);this.fileExists(o)&&a.renameSync(o,s)}let r=this.getRotatedFileName(t,1);a.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let t=a.statSync(this.currentLogFile);this.currentFileSize=t.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=a.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{a.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(t){let e=this.getCurrentDateString();this.currentDate&&this.currentDate!==e&&(this.rotateLog(),this.currentDate=e),this.currentFileSize+=t,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(t,e,...r){if(this.mode==="silent"||n.LEVEL_ORDER[t]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(p=>p instanceof Error?`${p.name}: ${p.message}`:typeof p=="object"?JSON.stringify(p,null,2):String(p)).join(" "),o=i?`${e} ${i}`:e,l=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${t.toUpperCase()}] ${o}
|
|
2
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},T=null;function Pt(n=!1){T&&T.dispose(),T=new U(n)}function F(){return T||Pt(!1),T}var u={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import ct from"fs";import Nt from"path";var k=300*1e3,O=3600*1e3,ut=10080*60*1e3,v=8*1024*1024,pt=3600*1e3,lt=".pending",$t=/\.reclaim-\d+-\d+$/;function I(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var Mt="upload-state.json";function ft(n){return Nt.join(n,Mt)}function jt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function V(n){try{let t=ct.readFileSync(ft(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return jt()}}function z(n,t){try{ct.writeFileSync(ft(n),JSON.stringify(t),"utf8")}catch{}}function dt(n){let t=V(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),z(n,t))}function mt(n){let t=V(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,z(n,t)}function gt(n){let t=V(n);t.lastRetryAt=Date.now(),z(n,t)}function ht(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function H(n){if(!n.startsWith("telemetry-"))return null;let t=$t.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(lt))return null;let r=e.slice(0,-lt.length);return r.endsWith(".txt")?r:null}function yt(n){return H(n)!==null}import Bt from"crypto";import R from"fs";import Ut from"path";var Vt="install-id";function zt(n){return Ut.join(n,Vt)}function vt(n){try{let t=R.readFileSync(n,"utf8").trim();return Ht(t)?t:null}catch{return null}}function Ht(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function St(n){let t=zt(n),e=vt(t);if(e)return e;let r=Bt.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=vt(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var x=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new D;storageDir="";failedDir="";installId="";disabled=I();traceFileKey=Buffer.alloc(0);sessionId=bt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){u.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=m.join(t,"failed"),this.cliVersion="0.4.0-TD.5.
|
|
2
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},T=null;function Pt(n=!1){T&&T.dispose(),T=new U(n)}function F(){return T||Pt(!1),T}var u={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import ct from"fs";import Nt from"path";var k=300*1e3,O=3600*1e3,ut=10080*60*1e3,v=8*1024*1024,pt=3600*1e3,lt=".pending",$t=/\.reclaim-\d+-\d+$/;function I(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var Mt="upload-state.json";function ft(n){return Nt.join(n,Mt)}function jt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function V(n){try{let t=ct.readFileSync(ft(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return jt()}}function z(n,t){try{ct.writeFileSync(ft(n),JSON.stringify(t),"utf8")}catch{}}function dt(n){let t=V(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),z(n,t))}function mt(n){let t=V(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,z(n,t)}function gt(n){let t=V(n);t.lastRetryAt=Date.now(),z(n,t)}function ht(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function H(n){if(!n.startsWith("telemetry-"))return null;let t=$t.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(lt))return null;let r=e.slice(0,-lt.length);return r.endsWith(".txt")?r:null}function yt(n){return H(n)!==null}import Bt from"crypto";import R from"fs";import Ut from"path";var Vt="install-id";function zt(n){return Ut.join(n,Vt)}function vt(n){try{let t=R.readFileSync(n,"utf8").trim();return Ht(t)?t:null}catch{return null}}function Ht(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function St(n){let t=zt(n),e=vt(t);if(e)return e;let r=Bt.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=vt(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var x=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new D;storageDir="";failedDir="";installId="";disabled=I();traceFileKey=Buffer.alloc(0);sessionId=bt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){u.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=m.join(t,"failed"),this.cliVersion="0.4.0-TD.5.4",this.nodeVersion=process.version,this.installId=St(t).replace(/-/g,""),this.traceFileKey=rt(t),c.mkdirSync(t,{recursive:!0}),c.mkdirSync(this.failedDir,{recursive:!0}),u.debug(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,u.debug(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,u.debug(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,u.debug(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!e){await this.record(t,0,!0,null);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code);return}let r=e,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(t,s,!0,null),o}catch(o){let s=Date.now()-i,l=this.toErrorCode(o);throw await this.record(t,s,!1,l),o}}async record(t,e,r,i){let o=this.buildTraceEvent(t,e,r,i);try{let s=nt(JSON.stringify(o),this.traceFileKey);await c.promises.appendFile(this.currentFile(),s+`
|
|
3
3
|
`,"utf8"),dt(this.storageDir)}catch{}}buildTraceEvent(t,e,r,i){let o=`${n.EVENT_PREFIX}${t.event}`,s=Q.toObject(t);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:bt.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:e,success:r,error_code:i,event_detail:s}}}toErrorCode(t){return t instanceof Error?t.code??t.name:"UnknownError"}resolveOsArch(){let t=P.arch();return t==="x64"?"amd64":t}resolveOsName(){switch(process.platform){case"win32":{let t=P.release().split(".");return(parseInt(t[t.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return P.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(P.totalmem()/1024)}KB`}formatVersion(t){return t?`${t}_${this.resolveOsSuffix()}`:""}dateString(){let t=new Date,e=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${e}-${r}`}currentFile(){return m.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){u.debug("[telemetry] scheduler not started (telemetry disabled)");return}u.debug(`[telemetry] scheduler started (flush every ${k/1e3}s, retry failed every ${O/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},k)},k),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},O)},O)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),u.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let t=await this.listPendingFiles(),e=!0;for(let r of t)await this.flushFile(r)||(e=!1);return mt(this.storageDir),e}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let t=Date.now(),e;try{e=await c.promises.readdir(this.failedDir)}catch{return!0}let r=e.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>m.join(this.failedDir,o)),i=!0;for(let o of r){let s=m.basename(o),l=ht(s);if(l!==null){if(t-l>ut){try{await c.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||u.warn("[telemetry] retry failed"),gt(this.storageDir),i}async reclaimStalePending(){let t=Date.now();for(let e of[this.storageDir,this.failedDir]){let r;try{r=await c.promises.readdir(e)}catch{continue}for(let i of r)yt(i)&&await this.reclaimOrphan(m.join(e,i),t)}}async reclaimOrphan(t,e){let r;try{let h=await c.promises.stat(t);if(e-h.mtimeMs<pt)return;r=h.size}catch{return}let i=m.dirname(t),o=H(m.basename(t));if(o===null)return;let s=await this.claimOrphan(t,i,o);if(s===null)return;let l=m.join(i,o),p=v-await this.fileSize(l);if(r>p){try{await c.promises.unlink(s)}catch{}u.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${p})`);return}if(await this.mergeOrphanInto(s,l)){u.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}u.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(t,e,r){let i=m.join(e,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await c.promises.rename(t,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(t,e){try{await c.promises.appendFile(e,await c.promises.readFile(t))}catch(r){return u.warn(`[telemetry] merge orphan pending failed: ${t} -> ${e}: ${r instanceof Error?r.message:String(r)}`),!1}try{await c.promises.unlink(t)}catch(r){u.warn(`[telemetry] merged but failed to remove orphan pending: ${t}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(t){try{return(await c.promises.stat(t)).size}catch{return 0}}async touch(t){let e=new Date;try{await c.promises.utimes(t,e,e)}catch{}}runExclusive(t){let e=()=>t(),r=this.flushChain.then(e,e);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let t;try{t=await c.promises.readdir(this.storageDir)}catch{return[]}return t.filter(e=>e.startsWith("telemetry-")&&e.endsWith(".txt")).map(e=>m.join(this.storageDir,e)).sort()}async flushFile(t){let e=await this.fileSize(t);if(e>v){u.warn(`[telemetry] ${m.basename(t)} is ${e} bytes (> ${v}), dropped without uploading`);try{await c.promises.unlink(t)}catch{}return!0}let r=t+".pending";try{await c.promises.rename(t,r)}catch{return!1}await this.touch(r);let i;try{i=await c.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
|
|
4
4
|
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await c.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(t,e){let r=[],i=16,o=e;for(;o<t.length&&r.length<n.MAX_BATCH;){let s=it(t[o],this.traceFileKey);if(s===null){o++;continue}let l=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+l>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=l,o++}return{batch:r,next:o}}async uploadInBatches(t,e){let r=0;for(;r<e.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(e,r);r=s;let l=this.buildPayloadItems(o);if(l.length===0)continue;let p=JSON.stringify(l),h=!1;try{h=await this.uploader.upload(p,this.installId)}catch{}if(!h){u.warn("[telemetry] upload failed");let w=e.slice(i).join(`
|
|
5
5
|
`)+`
|
package/index.zip
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deveco-test/deveco-cli-openharmony-arm64",
|
|
3
|
-
"version": "0.4.0-TD.5.
|
|
3
|
+
"version": "0.4.0-TD.5.4",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"os": [
|
|
43
43
|
"openharmony"
|
|
44
44
|
],
|
|
45
|
-
"cpu":[
|
|
45
|
+
"cpu": [
|
|
46
46
|
"arm64"
|
|
47
47
|
],
|
|
48
48
|
"keywords": [
|