@deveco-test/deveco-cli-common 1.3.5-Test.4 → 1.3.10-Test.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -18
- package/dist/cli.js +201 -151
- package/dist/internal/telemetry-upload-background.js +1 -1
- package/package.json +7 -3
- package/skills/deveco-cli/SKILL.md +48 -21
- package/src/resources/uitest/uitest_agent_v1.1.9.so +0 -0
- package/src/resources/uitest/uitest_agent_v1.1.9.x86_64.so +0 -0
- package/src/resources/uitest/uitest_agent_v1.2.2.so +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,103 +1,112 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>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 i=t.getFullYear(),o=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",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),y=new Date(i,o,s,a,c,l,g);return y.getTime()>t.getTime()+1440*60*1e3&&y.setFullYear(i-1),y}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 i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}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 i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return p(`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(ke.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=ke.resolve(ke.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=ke.normalize(e),i=ke.relative(r,t);if(i.split(ke.sep)[0]===".."||ke.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||ke.isAbsolute(e)}static isPathContained(e,t){let r=ke.resolve(t,e),i=ke.relative(t,r);return n.isPathEscaping(i)?{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 i;try{i=zc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=ke.resolve(i,e),s;try{s=zc.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import Jp from"crypto";import re from"fs";import os from"os";import Qe from"path";import PS from"https";var yp={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var zo=class n{static ENDPOINT=yp.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:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(i)}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,i){let o=new URL(e);return new Promise((s,a)=>{let c=PS.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",g=>d.push(g)),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 vp={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()},Jc=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??vp.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=r[o]??t(o);i[a]=this.transform(s)}return i}},wp=new Jc({namingStrategy:vp.snakeCase,fieldNames:{}});import Ti from"crypto";import Jo from"fs";import CS from"path";var Yo="aes-256-gcm",kS=12,IS="deveco-cli-trace-file",AS="trace-file-secret",bp=32;function Sp(n){try{let e=Jo.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===bp?e:null}catch{return null}}function Ep(n){let e=CS.join(n,AS),t=Sp(e);if(t)return Yc(t);let r=Ti.randomBytes(bp).toString("base64");try{Jo.mkdirSync(n,{recursive:!0});try{Jo.writeFileSync(e,r,{flag:"wx"})}catch{let i=Sp(e);if(i)return Yc(i);Jo.writeFileSync(e,r)}}catch{}return Yc(r)}function Yc(n){return Ti.createHash("sha256").update(IS).update(n).digest()}function Pp(n,e){let t=Ti.randomBytes(kS),r=Ti.createCipheriv(Yo,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:Yo,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function Cp(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!DS(t))return n;try{let r=Ti.createDecipheriv(Yo,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 DS(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Yo&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as H from"fs";import*as rs from"path";import X from"fs";import{spawn as RS}from"child_process";import*as Ko from"os";import*as O from"path";import TS from"json5";var Kc="Huawei";var Rp=3;function Xo(n){if(!X.existsSync(n)||!X.statSync(n).isDirectory())return!1;let e=X.existsSync(O.join(n,"build-profile.json5")),t=X.existsSync(O.join(n,"hvigorfile.js"))||X.existsSync(O.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=X.readFileSync(O.join(n,"build-profile.json5"),"utf-8");return TS.parse(r).app!==void 0}catch{return!1}}function Xc(n,e,t){if(e>=t)return null;let r=xS(n),i=NS(r);if(i)return i;for(let o of r){let s=Xc(o,e+1,t);if(s)return s}return null}function xS(n){try{let e=X.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(O.join(n,r.name));return t}catch{return[]}}function NS(n){for(let e of n)if(Xo(e))return e;return null}function Wt(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}if(!X.existsSync(t))return null;if(Xo(t))return t;let r=t;for(let i=1;i<=3;i++){let o=O.dirname(r);if(o===r)break;if(Xo(o))return o;r=o}if(X.statSync(t).isDirectory()){let i=Xc(t,0,Rp);if(i)return i}return null}function Zo(n){if(!n||n.trim()==="")return null;let e=O.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}return!X.existsSync(t)||!X.statSync(t).isDirectory()?null:Xo(t)?t:Xc(t,0,Rp)}var kp="DevEco Studio";function Tp(){if(process.platform==="win32"){let n=[O.join("C:\\Program Files",Kc,kp),O.join("C:\\Program Files (x86)",Kc,kp)];return Ip(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",O.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Ip(n)}return null}function Ip(n){for(let e of n)if(X.existsSync(e))return e;return null}function Cn(n,e){let t=e?O.join("standardIndex","index.js"):"index.js";return X.existsSync(O.join(n,"ace-server"))?O.join(n,"ace-server","out",t):O.join(n,"out",t)}function Qo(n){return X.existsSync(Cn(n,!0))}var LS=5e3,MS=64*1024,Ap=new Map;function xp(n,e){let t=OS(n),r=Ap.get(t);if(r)return r;let i=_S(n,e).catch(()=>!1);return Ap.set(t,i),i}function OS(n){let e=O.resolve(n).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function Dp(n){try{let e=JSON.parse(n.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function _S(n,e){let t=Cn(n,!0);if(!X.existsSync(t))return Promise.resolve(!1);let r=e||process.execPath||"node",i=[t,"--list-protocols"];return h.debug(`Executing: ${r} ${i.join(" ")}`),new Promise(o=>{let s=RS(r,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=g=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(g))},d=setTimeout(()=>l(!1),LS);s.stdout?.on("data",g=>{a=(a+g.toString("utf8")).slice(-MS);let y=Dp(a);y!==null&&l(y)}),s.on("error",()=>l(!1)),s.on("close",()=>l(Dp(a)??!1))})}var FS=[".idea",".deveco","cxx","compile_commands.json"];function Gr(n){return O.join(n,...FS)}function Np(n){return new Promise(e=>setTimeout(e,n))}var $S=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function qr(n){let e=O.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&$S.has(e)}function es(n){return O.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function Se(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function jS(n){return Se(n)}function vt(n){let e=jS(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function lr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??O.join(Ko.homedir(),"AppData","Local");return O.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?O.join(Ko.homedir(),"Library","Logs","devecocli-mcp-server"):O.join(Ko.homedir(),".local","share","devecocli-mcp-server","logs")}function Lp(n,e){let t=HS(e),r=US(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=BS(t,n,s);return WS(e,a),i}function HS(n){let e;try{e=X.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function US(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function BS(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function WS(n,e){try{X.mkdirSync(O.dirname(n),{recursive:!0})}catch{}try{X.writeFileSync(n,e.join(`
|
|
2
|
+
var sR=Object.defineProperty;var aR=(r,e)=>{for(var t in e)sR(r,t,{get:e[t],enumerable:!0})};import*as Wu from"path";import{program as me}from"commander";import{red as xV}from"colorette";var ts={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Ja={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Se={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},oe={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},Vn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},rs={TMS_URL:"https://terms-drcn.platform.dbankcloud.cn/agreementservice/user",PRIVACY_ID:"20000257",PRIVACY_URL:"https://legal.cloud.huawei.com/terms/scope/huawei/deveco-cli/privacy-statement.htm?code=CN&language=zh-CN&branchid=0&contenttag=default"},ns={baseUrl:oe.LOGIN_URL,authUrl:oe.AUTH_APPLY_PATH,tempTokenCheckUrl:oe.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:oe.JWT_TOKEN_CHECK_PATH,successRedirectUrl:oe.LOGIN_SUCCESS_PATH,failedRedirectUrl:oe.LOGIN_FAILED_PATH,logoutUrl:oe.LOGOUT_PATH,agcTeamListUrl:oe.AGC_TEAM_LIST_URL,appId:Se.APP_ID,timeout:ts.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as yI}from"commander";import{green as Vc,red as Nw,yellow as Gc}from"colorette";import Aw from"json5";import*as Es from"fs";import*as _w from"path";import X from"fs";import*as H from"path";import rr from"json5";import*as Vu from"fs";import*as _e from"path";function f(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;console.log(`[DEBUG] ${e}`)}}var E=class r{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let n=e.trim();if(!/^\d+$/.test(n))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(n,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
|
+
`)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return r.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,n,i=new Date){if(!t&&!n)return e;let[o,s]=r.resolveTimeBounds(t,n,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let h=r.extractTimestampFromLogLine(d,i);h&&(l=r.isWithinBounds(h,o,s)),l&&c.push(d)}return c.join(`
|
|
4
|
+
`)}static resolveTimeBounds(e,t,n){let i=e?new Date(n.getTime()-e*1e3):null,o=t?new Date(n.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,n]:o?[null,o]:[null,null]}static isWithinBounds(e,t,n){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=n?Math.floor(n.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let n=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!n)return null;let i=t.getFullYear(),o=Number.parseInt(n[1],10)-1,s=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),c=Number.parseInt(n[4],10),l=Number.parseInt(n[5],10),d=n[6]??"0",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),y=new Date(i,o,s,a,c,l,h);return y.getTime()>t.getTime()+1440*60*1e3&&y.setFullYear(i-1),y}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 n=/^[a-zA-Z0-9_]+$/;for(let i=0;i<t.length;i++){let o=t[i];if(!n.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}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(n=>{let i=n.charCodeAt(0);return i<=r.ASCII_CONTROL_MAX||i===r.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let n=`'${e.replace(/'/g,"'\\''")}'`;return f(`quotePosixShellArg: ${e} -> ${n}`),n}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(_e.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=_e.resolve(_e.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=_e.normalize(e),i=_e.relative(n,t);if(i.split(_e.sep)[0]===".."||_e.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||_e.isAbsolute(e)}static isPathContained(e,t){let n=_e.resolve(t,e),i=_e.relative(t,n);return r.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let n=r.isPathContained(e,t);if(!n.contained)return n;let i;try{i=Vu.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=_e.resolve(i,e),s;try{s=Vu.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return r.isPathContained(s,i)}};import ay from"crypto";import se from"fs";import ac from"os";import pt from"path";import lR from"https";var Ag={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Ka=class r{static ENDPOINT=Ag.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),n=t?.code??t?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(e,t,n,i){let o=new URL(e);return new Promise((s,a)=>{let c=lR.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},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(n),c.end()})}};var Tg={identity:r=>r,camelCase:r=>r,snakeCase:r=>r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},Gu=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??Tg.identity,n=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=n[o]??t(o);i[a]=this.transform(s)}return i}},Ng=new Gu({namingStrategy:Tg.snakeCase,fieldNames:{}});import is from"crypto";import Ya from"fs";import dR from"path";var Xa="aes-256-gcm",uR=12,pR="deveco-cli-trace-file",fR="trace-file-secret",Mg=32;function _g(r){try{let e=Ya.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Mg?e:null}catch{return null}}function Og(r){let e=dR.join(r,fR),t=_g(e);if(t)return qu(t);let n=is.randomBytes(Mg).toString("base64");try{Ya.mkdirSync(r,{recursive:!0});try{Ya.writeFileSync(e,n,{flag:"wx"})}catch{let i=_g(e);if(i)return qu(i);Ya.writeFileSync(e,n)}}catch{}return qu(n)}function qu(r){return is.createHash("sha256").update(pR).update(r).digest()}function Lg(r,e){let t=is.randomBytes(uR),n=is.createCipheriv(Xa,e,t),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o={version:1,algorithm:Xa,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(o)}function Fg(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!mR(t))return r;try{let n=is.createDecipheriv(Xa,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function mR(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===Xa&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as Y from"fs";import*as ic from"path";import ne from"fs";import{spawn as hR}from"child_process";import*as Za from"os";import*as B from"path";import gR from"json5";var zu="Huawei";var Bg=3;function Qa(r){if(!ne.existsSync(r)||!ne.statSync(r).isDirectory())return!1;let e=ne.existsSync(B.join(r,"build-profile.json5")),t=ne.existsSync(B.join(r,"hvigorfile.js"))||ne.existsSync(B.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=ne.readFileSync(B.join(r,"build-profile.json5"),"utf-8");return gR.parse(n).app!==void 0}catch{return!1}}function Ju(r,e,t){if(e>=t)return null;let n=yR(r),i=wR(n);if(i)return i;for(let o of n){let s=Ju(o,e+1,t);if(s)return s}return null}function yR(r){try{let e=ne.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(B.join(r,n.name));return t}catch{return[]}}function wR(r){for(let e of r)if(Qa(e))return e;return null}function kr(r){if(!r||r.trim()==="")return null;let e=B.resolve(r),t;try{t=ne.realpathSync(e)}catch{t=e}if(!ne.existsSync(t))return null;if(Qa(t))return t;let n=t;for(let i=1;i<=3;i++){let o=B.dirname(n);if(o===n)break;if(Qa(o))return o;n=o}if(ne.statSync(t).isDirectory()){let i=Ju(t,0,Bg);if(i)return i}return null}function ec(r){if(!r||r.trim()==="")return null;let e=B.resolve(r),t;try{t=ne.realpathSync(e)}catch{t=e}return!ne.existsSync(t)||!ne.statSync(t).isDirectory()?null:Qa(t)?t:Ju(t,0,Bg)}var $g="DevEco Studio";function Wg(){if(process.platform==="win32"){let r=[B.join("C:\\Program Files",zu,$g),B.join("C:\\Program Files (x86)",zu,$g)];return jg(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",B.join(process.env.HOME??"","Applications","DevEco Studio.app")];return jg(r)}return null}function jg(r){for(let e of r)if(ne.existsSync(e))return e;return null}function Mi(r,e){let t=e?B.join("standardIndex","index.js"):"index.js";return ne.existsSync(B.join(r,"ace-server"))?B.join(r,"ace-server","out",t):B.join(r,"out",t)}function tc(r){return ne.existsSync(Mi(r,!0))}var vR=5e3,bR=64*1024,Hg=new Map;function Vg(r,e){let t=SR(r),n=Hg.get(t);if(n)return n;let i=ER(r,e).catch(()=>!1);return Hg.set(t,i),i}function SR(r){let e=B.resolve(r).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function Ug(r){try{let e=JSON.parse(r.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function ER(r,e){let t=Mi(r,!0);if(!ne.existsSync(t))return Promise.resolve(!1);let n=e||process.execPath||"node",i=[t,"--list-protocols"];return g.debug(`Executing: ${n} ${i.join(" ")}`),new Promise(o=>{let s=hR(n,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=h=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(h))},d=setTimeout(()=>l(!1),vR);s.stdout?.on("data",h=>{a=(a+h.toString("utf8")).slice(-bR);let y=Ug(a);y!==null&&l(y)}),s.on("error",()=>l(!1)),s.on("close",()=>l(Ug(a)??!1))})}var PR=[".idea",".deveco","cxx","compile_commands.json"];function Gn(r){return B.join(r,...PR)}function Gg(r){return new Promise(e=>setTimeout(e,r))}var CR=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function qn(r){let e=B.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&CR.has(e)}function rc(r){return B.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function Ie(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function kR(r){return Ie(r)}function Mt(r){let e=kR(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Qr(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??B.join(Za.homedir(),"AppData","Local");return B.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?B.join(Za.homedir(),"Library","Logs","devecocli-mcp-server"):B.join(Za.homedir(),".local","share","devecocli-mcp-server","logs")}function qg(r,e){let t=RR(e),n=DR(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=xR(t,r,s);return IR(e,a),i}function RR(r){let e;try{e=ne.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function DR(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(n+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function xR(r,e,t){let n=!1,i=r.map(o=>{if(n)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):o});return n||i.push(t),i}function IR(r,e){try{ne.mkdirSync(B.dirname(r),{recursive:!0})}catch{}try{ne.writeFileSync(r,e.join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`,"utf8")}catch{}}function
|
|
7
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);
|
|
8
|
-
`,"utf8"),
|
|
9
|
-
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await
|
|
6
|
+
`,"utf8")}catch{}}function Ku(r,e,t="[Cleanup]"){try{let n=B.dirname(r);if(!ne.existsSync(n))return;let i=Date.now();for(let o of ne.readdirSync(n,{withFileTypes:!0}))o.isDirectory()&&AR(B.join(n,o.name),i,e,t)}catch{}}function AR(r,e,t,n){try{let{mtimeMs:i}=ne.statSync(r);if(e-i<=t)return;ne.rmSync(r,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${n} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${r}`)}catch(i){console.error(`${n} Failed to remove expired dir ${r}: ${i}`)}}var zg="mcp-server.log",TR="mcp-server",NR={maxSize:10*1024*1024,maxFiles:4},Yu=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...NR,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Qr(),this.currentLogFile=ic.join(this.logDir,zg),Y.existsSync(this.logDir)||Y.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}getRotatedFileName(e,t){return ic.join(this.logDir,`${TR}-${e}.log.${t}`)}fileExists(e){try{return Y.accessSync(e,Y.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=Y.readdirSync(this.logDir),t=[];for(let i of e)if(i===zg||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=ic.join(this.logDir,i),s=Y.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<t.length;i++)try{Y.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&Y.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&Y.renameSync(o,s)}let n=this.getRotatedFileName(e,1);Y.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=Y.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=Y.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{Y.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${o}
|
|
7
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);Y.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{Y.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},St=null;function zn(r=!1){St&&St.dispose(),St=new Yu(r)}function Jg(){St&&(St.dispose(),St=null)}function Kg(){St&&St.flush()}function Yg(){return St?.getLogFilePath()??null}function Xg(){return St?.getLogDirectory()??null}function nc(){return St||zn(!1),St}var g={debug:(r,...e)=>nc().debug(r,...e),info:(r,...e)=>nc().info(r,...e),warn:(r,...e)=>nc().warn(r,...e),error:(r,...e)=>nc().error(r,...e)};import os from"fs";import Xu from"path";var ss=300*1e3,as=3600*1e3,Zu=10080*60*1e3,Oi=8*1024*1024,Qu=3600*1e3,Zg=".pending",_R=/\.reclaim-\d+-\d+$/;function Ze(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var MR="upload-state.json";function ey(r){return Xu.join(r,MR)}function OR(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function oc(r){try{let e=os.readFileSync(ey(r),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return OR()}}function ep(r,e){try{os.writeFileSync(ey(r),JSON.stringify(e),"utf8")}catch{}}function ty(r){let e=oc(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),ep(r,e))}function ry(r){let e=oc(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,ep(r,e)}function ny(r){let e=oc(r);e.lastRetryAt=Date.now(),ep(r,e)}function tp(r){let e=r.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function rp(r){if(!r.startsWith("telemetry-"))return null;let e=_R.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(Zg))return null;let n=t.slice(0,-Zg.length);return n.endsWith(".txt")?n:null}function np(r){return rp(r)!==null}function LR(r,e=Date.now()){try{return e-os.statSync(r).mtimeMs>=Qu}catch{return!1}}function Qg(r,e=Date.now()){let t;try{t=os.readdirSync(r)}catch{return!1}return t.some(n=>np(n)&&LR(Xu.join(r,n),e))}function FR(r,e=Date.now()){if(Qg(r,e))return!0;let t=Xu.join(r,"failed");if(Qg(t,e))return!0;let n;try{n=os.readdirSync(t)}catch{return!1}for(let i of n){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=tp(i);if(o!==null&&e-o<=Zu)return!0}return!1}function iy(r,e=Date.now()){let t=oc(r);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=ss||FR(r,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=as))}import $R from"crypto";import sc from"fs";import jR from"path";var HR="install-id";function UR(r){return jR.join(r,HR)}function oy(r){try{let e=sc.readFileSync(r,"utf8").trim();return BR(e)?e:null}catch{return null}}function BR(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r)}function sy(r){let e=UR(r),t=oy(e);if(t)return t;let n=$R.randomUUID();try{sc.mkdirSync(r,{recursive:!0});try{sc.writeFileSync(e,n,{flag:"wx"})}catch{let i=oy(e);if(i)return i;sc.writeFileSync(e,n)}}catch{}return n}var cs=class r{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Ka;storageDir="";failedDir="";installId="";disabled=Ze();traceFileKey=Buffer.alloc(0);sessionId=ay.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=pt.join(e,"failed"),this.cliVersion="1.3.10-Test.1",this.nodeVersion=process.version,this.installId=sy(e).replace(/-/g,""),this.traceFileKey=Og(e),se.mkdirSync(e,{recursive:!0}),se.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 o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=Lg(JSON.stringify(o),this.traceFileKey);await se.promises.appendFile(this.currentFile(),s+`
|
|
8
|
+
`,"utf8"),ty(this.storageDir)}catch{}}buildTraceEvent(e,t,n,i){let o=`${r.EVENT_PREFIX}${e.event}`,s=Ng.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:ay.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:n,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=ac.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=ac.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 ac.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(ac.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}currentFile(){return pt.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 ${ss/1e3}s, retry failed every ${as/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},ss)},ss),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},as)},as)}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 n of e)await this.flushFile(n)||(t=!1);return ry(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 se.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>pt.join(this.failedDir,o)),i=!0;for(let o of n){let s=pt.basename(o),a=tp(s);if(a!==null){if(e-a>Zu){try{await se.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||g.warn("[telemetry] retry failed"),ny(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await se.promises.readdir(t)}catch{continue}for(let i of n)np(i)&&await this.reclaimOrphan(pt.join(t,i),e)}}async reclaimOrphan(e,t){let n;try{let l=await se.promises.stat(e);if(t-l.mtimeMs<Qu)return;n=l.size}catch{return}let i=pt.dirname(e),o=rp(pt.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=pt.join(i,o),c=Oi-await this.fileSize(a);if(n>c){try{await se.promises.unlink(s)}catch{}g.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){g.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}g.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let i=pt.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await se.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await se.promises.appendFile(t,await se.promises.readFile(e))}catch(n){return g.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await se.promises.unlink(e)}catch(n){g.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await se.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await se.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await se.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>pt.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>Oi){g.warn(`[telemetry] ${pt.basename(e)} is ${t} bytes (> ${Oi}), dropped without uploading`);try{await se.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await se.promises.rename(e,n)}catch{return!1}await this.touch(n);let i;try{i=await se.promises.readFile(n,"utf8")}catch{return!1}let o=i.split(`
|
|
9
|
+
`).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await se.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,o)}collectDecryptBatch(e,t){let n=[],i=16,o=t;for(;o<e.length&&n.length<r.MAX_BATCH;){let s=Fg(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&i+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),i+=a,o++}return{batch:n,next:o}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let i=n,{batch:o,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let 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(i).join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`;return await this.moveToFailed(e,d),!1}}try{await
|
|
12
|
-
`).filter(Boolean),s=
|
|
11
|
+
`;return await this.moveToFailed(e,d),!1}}try{await se.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let i=JSON.parse(n);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=pt.basename(e,".pending"),i=pt.join(this.failedDir,n),o=t.split(`
|
|
12
|
+
`).filter(Boolean),s=Oi-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&g.warn(`[telemetry] failed file capped at ${Oi} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await se.promises.appendFile(i,a.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`,"utf8")}catch{return}try{await re.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,r.push(e[o])}return r.reverse(),r}};var k=new Mi;import{spawn as nb}from"child_process";import{existsSync as ib}from"fs";import{dirname as ob,join as sb}from"path";import{fileURLToPath as ab}from"url";function cb(){let n=ob(ab(import.meta.url)),e=sb(n,"internal","telemetry-upload-background.js");return ib(e)?e:null}function al(n){if(He()||!Gp(n))return;let e=cb();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{nb(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){h.warn("[telemetry] failed to spawn background upload:",t)}}var S=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function V(n){if(n instanceof S)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var b={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Ne={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5"};var U=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=$.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=$.join(e,"build-profile.json5");if(!ee.existsSync(t))return null;try{let r=ee.readFileSync(t,"utf-8"),i=Nt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new S(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"src","main","module.json5");if(!ee.existsSync(i))return"entry";try{let o=ee.readFileSync(i,"utf-8");return Nt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=$.normalize(e);for(let r of this.profile.modules){let i=$.normalize($.join(this.rootDir,r.srcPath)),o=i+$.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new S(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"build-profile.json5");if(!ee.existsSync(i))throw new S(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");try{let o=ee.readFileSync(i,"utf-8");return Nt.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(e){if(e){let r=this.profile.app.products?.find(i=>i.name===e);if(r?.bundleName)return r.bundleName}let t=$.join(this.rootDir,"AppScope","app.json5");if(ee.existsSync(t))try{let r=ee.readFileSync(t,"utf-8"),i=Nt.parse(r);if(i?.app?.bundleName)return i.app.bundleName}catch(r){console.warn(`Warning: Failed to parse ${t}:`,r)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=$.join(this.rootDir,"AppScope","app.json5");if(!ee.existsSync(e))return!1;try{let t=ee.readFileSync(e,"utf-8");return Nt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,r.srcPath),o=$.join(i,"src","main","module.json5");if(!ee.existsSync(o))return"EntryAbility";try{let s=ee.readFileSync(o,"utf-8"),c=Nt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new S(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new S(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return[];let r=this.readLockFinalLocalModuleDeps(e);return r!==null?r:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=$.join(this.rootDir,Ne.LOCK_JSON5_PATH);if(!ee.existsSync(t))return null;let r;try{r=Nt.parse(ee.readFileSync(t,"utf-8"))}catch(d){return p(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let i=r,o=i?.modules;if(!o||typeof o!="object")return null;let s=Object.values(o).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(i.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,y=>this.resolveLockDepByVersion(y),c,l)}return c}resolveLockDepByVersion(e){if(typeof e!="object"||e===null)return null;let t=e.version;return typeof t=="string"?this.resolveLocalDepToModule(t):null}resolveDepModule(e,t,r){if(t?.has(e)){let i=t.get(e);if(i){let o=this.resolveLocalDepToModule(i);if(o)return o}}return r()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[r,i]of Object.entries(e))typeof i=="string"&&t.set(r,i);return t.size>0?t:null}resolveLocalDepToModule(e){let t=n.stripLocalDep(e);if(!t)return null;let r=$.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let o=this.profile.modules.find(s=>$.resolve(this.rootDir,s.srcPath)===i);return o?o.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=$.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Ne.OH_PACKAGE_JSON5);if(!ee.existsSync(t))return[];let r=this.readRootOverrideMap(),i=[],o=new Set;try{let s=Nt.parse(ee.readFileSync(t,"utf-8"));for(let a of["dependencies","dynamicDependencies"]){let c=s?.[a];!c||typeof c!="object"||this.collectLocalDeps(c,r,l=>this.resolveOhPackageDepByValue(l,e),i,o)}}catch(s){p(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}readRootOverrideMap(){let e=$.join(this.rootDir,Ne.OH_PACKAGE_JSON5);if(!ee.existsSync(e))return null;try{let t=Nt.parse(ee.readFileSync(e,"utf-8"));return this.buildOverrideMap(t?.overrides)}catch{return null}}resolveOhPackageDepByValue(e,t){return typeof e=="string"?this.resolveLocalDepModuleName(e,t):null}collectLocalDeps(e,t,r,i,o){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>r(a));c&&!o.has(c)&&(o.add(c),i.push(c))}}resolveLocalDepModuleName(e,t){let r=n.stripLocalDep(e);if(!r)return null;let i=$.join(t.srcPath,r),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>$.resolve(this.rootDir,a.srcPath)===o);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new S(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!ee.existsSync(a))throw new S(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let I=this.getSignedHapName(c,o.srcPath,i,t);I&&(d=I)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new S(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let y=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!ee.existsSync(y))throw new S(`Generated package file not found in ${y}.`,"Generated package file not found.");return y}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=$.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!ee.existsSync(l))throw new S(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return ee.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=$.resolve(i,"build",t,...r);return E.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=ee.readFileSync(e,"utf-8");r=Nt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(r)?r:[r];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new S(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=$.basename(e);if(t!==e)throw new S(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new S(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import{spawnSync as om}from"child_process";import Ie from"fs";import*as We from"os";import*as D from"path";import as from"fs";import*as cs from"os";import*as Oi from"path";import pb from"regedit";import{execFileSync as db}from"child_process";import Yp from"fs";import*as Kp from"os";import*as cl from"path";import{compare as lb}from"semver";function dr(n,e){return lb(n,e)}function In(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function ss(n,e){let t=cl.join(n,"Contents","Info.plist");if(!Yp.existsSync(t)){p(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=db(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function ub(n){let e=ss(n,"CFBundleShortVersionString");if(!e)return ss(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[ss(n,"CFBundleVersion"),ss(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function ur(n){if(Kp.platform()==="darwin")return ub(n);let e=cl.join(n,"product-info.json");try{let t=JSON.parse(Yp.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var mb="DevEco Studio",fb=["Contents","Resources","product-info.json"],hb="name";function gb(n){return n.filter(e=>{try{return as.statSync(e).isDirectory()}catch{return!1}})}function yb(n){let e=Oi.join(n,...fb);if(as.existsSync(e))try{let r=JSON.parse(as.readFileSync(e,"utf8"))[hb];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function vb(n){return yb(n)===mb}function wb(){let n=[];for(let e of[Oi.join(cs.homedir(),"Applications"),"/Applications"])try{n.push(...as.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>Oi.join(e,t)).filter(vb))}catch{}return n}function Xp(n){return new Promise((e,t)=>pb.list(n,(r,i)=>r?t(r):e(i)))}async function Zp(n,e,t){let i=((await Xp([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Xp(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function Sb(){let n=[Oi.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await Zp(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await Zp(e,()=>!0,""))}catch{}return n}async function Qp(){let n=cs.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?wb():await Sb(),t=gb(e).flatMap(r=>{let i=ur(r);return i?(p(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(p(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation, or set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");return t.reduce((r,i)=>In(i.version,r.version)>0?i:r)}import*as em from"fs";import*as Ue from"path";function ll(n,e){let t=Ue.relative(e,n);return t===""||!Ue.isAbsolute(t)&&!t.startsWith(`..${Ue.sep}`)&&t!==".."}function pr(n){let e=Ue.resolve(n),t=[],r=e;for(;;)try{let i=em.realpathSync(r);return t.length===0?i:Ue.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Ue.dirname(r);if(o===r)return e;t.push(Ue.basename(r)),r=o}}function tm(n,e){let t=pr(e),r=pr(n);return ll(r,t)?r:null}function dl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function ls(n){let e=dl(n);if(!e)throw new Error("Path must not be empty.");return pr(e)}var ul="https://matrix.openharmony.cn",lt={TAGS_API_URL:`${ul}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${ul}/api/registry/skill/skills`,SKILL_API_BASE:`${ul}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},wt={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},pi:{path:".pi/agent/skills",displayName:"pi"},deveco:{path:".config/deveco/skills",displayName:"deveco"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"},dsh:{path:".dsh/skills",projectPath:".dsh/skills",displayName:"deepseek harness"}};import{homedir as Lt}from"os";import Be from"path";var Mt="deveco-mcp";var mr={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Be.join(Lt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:Be.join(Lt(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(Lt(),"AppData","Roaming"),"Trae CN","User"):Be.join(Lt(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Be.join(Lt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Be.join(Lt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"codebuddy"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(Lt(),"AppData","Roaming"),"Qoder","SharedClientCache"):Be.join(Lt(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:Be.join(Lt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Be.join(Lt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function nm(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function rm(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function bb(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."}}}function im(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function ds(n,e){return n.format==="opencode"?nm(e):n.format==="claude-code"||n.format==="codex"?rm(e):n.format==="codebuddy"?bb(e):im(e)}var pl="https://developer.huawei.com/consumer/cn/download/";var Eb=/^#\s*Version:\s*(\S+)/,Pb="26.0.0.810";function Cb(n){try{let e=JSON.parse(Ie.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){p(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function kb(n){let e=D.join(n,"default","openharmony");return[D.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>D.join(e,t,"oh-uni-package.json"))]}var P=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(Ie.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return Ie.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.")}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return In(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):ur(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),n.assertMinimumVersion(ur(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new S(`Failed to determine ${t} version from ${r} at ${o}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new S(`Invalid ${t} version "${e}" from ${r} at ${o}`,`Invalid ${t} version "${e}" from ${r}`);if(In(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
15
|
-
|
|
14
|
+
`,"utf8")}catch{return}try{await se.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let n=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,n.push(e[o])}return n.reverse(),n}};var R=new cs;import{spawn as WR}from"child_process";import{existsSync as VR}from"fs";import{dirname as GR,join as qR}from"path";import{fileURLToPath as zR}from"url";function JR(){let r=GR(zR(import.meta.url)),e=qR(r,"internal","telemetry-upload-background.js");return VR(e)?e:null}function ip(r){if(Ze()||!iy(r))return;let e=JR();if(!e){g.warn("[telemetry] background upload script not found, skipping spawn");return}try{WR(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){g.warn("[telemetry] failed to spawn background upload:",t)}}var w=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function Z(r){if(r instanceof w)return r.traceMessage;if(r instanceof Error){let e=r.code;return typeof e=="string"&&e!==""?e:r.name}return"UnknownError"}var v={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Ce={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5",HVIGOR_CONFIG:"hvigor/hvigor-config.json5"};var W=class r{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let n=r.tryLoadProjectProfile(t);if(n)return new r(t,n);let i=H.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=H.join(e,"build-profile.json5");if(!X.existsSync(t))return null;try{let n=X.readFileSync(t,"utf-8"),i=rr.parse(n);return i.app?i:null}catch(n){return console.error(`Error parsing ${t}:`,n),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let n=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=H.join(n,"src","main","module.json5");if(!X.existsSync(i))return"entry";try{let o=X.readFileSync(i,"utf-8");return rr.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=H.normalize(e);for(let n of this.profile.modules){let i=H.normalize(H.join(this.rootDir,n.srcPath)),o=i+H.sep;if(t.startsWith(o)||t===i)return n.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new w(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let n=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=H.join(n,"build-profile.json5");if(!X.existsSync(i))throw new w(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");try{let o=X.readFileSync(i,"utf-8");return rr.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(e){if(e){let n=this.profile.app.products?.find(i=>i.name===e);if(n?.bundleName)return n.bundleName}let t=H.join(this.rootDir,"AppScope","app.json5");if(X.existsSync(t))try{let n=X.readFileSync(t,"utf-8"),i=rr.parse(n);if(i?.app?.bundleName)return i.app.bundleName}catch(n){console.warn(`Warning: Failed to parse ${t}:`,n)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=H.join(this.rootDir,"AppScope","app.json5");if(!X.existsSync(e))return!1;try{let t=X.readFileSync(e,"utf-8");return rr.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let n=this.profile.modules.find(s=>s.name===e);if(!n)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,n.srcPath),o=H.join(i,"src","main","module.json5");if(!X.existsSync(o))return"EntryAbility";try{let s=X.readFileSync(o,"utf-8"),c=rr.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new w(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(n=>n.name===e)){let n=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new w(`Product '${e}' not found in project configuration. Available products: ${n}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return[];let n=this.readLockFinalLocalModuleDeps(e);return n!==null?n:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=H.join(this.rootDir,Ce.LOCK_JSON5_PATH);if(!X.existsSync(t))return null;let n;try{n=rr.parse(X.readFileSync(t,"utf-8"))}catch(d){return f(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let i=n,o=i?.modules;if(!o||typeof o!="object")return null;let s=Object.values(o).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(i.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let h=s[d];!h||typeof h!="object"||this.collectLocalDeps(h,a,y=>this.resolveLockDepByVersion(y),c,l)}return c}resolveLockDepByVersion(e){if(typeof e!="object"||e===null)return null;let t=e.version;return typeof t=="string"?this.resolveLocalDepToModule(t):null}resolveDepModule(e,t,n){if(t?.has(e)){let i=t.get(e);if(i){let o=this.resolveLocalDepToModule(i);if(o)return o}}return n()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[n,i]of Object.entries(e))typeof i=="string"&&t.set(n,i);return t.size>0?t:null}resolveLocalDepToModule(e){let t=r.stripLocalDep(e);if(!t)return null;let n=H.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,n)}catch{return null}let o=this.profile.modules.find(s=>H.resolve(this.rootDir,s.srcPath)===i);return o?o.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=H.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Ce.OH_PACKAGE_JSON5);if(!X.existsSync(t))return[];let n=this.readRootOverrideMap(),i=[],o=new Set;try{let s=rr.parse(X.readFileSync(t,"utf-8"));for(let a of["dependencies","dynamicDependencies"]){let c=s?.[a];!c||typeof c!="object"||this.collectLocalDeps(c,n,l=>this.resolveOhPackageDepByValue(l,e),i,o)}}catch(s){f(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}readRootOverrideMap(){let e=H.join(this.rootDir,Ce.OH_PACKAGE_JSON5);if(!X.existsSync(e))return null;try{let t=rr.parse(X.readFileSync(e,"utf-8"));return this.buildOverrideMap(t?.overrides)}catch{return null}}resolveOhPackageDepByValue(e,t){return typeof e=="string"?this.resolveLocalDepModuleName(e,t):null}collectLocalDeps(e,t,n,i,o){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>n(a));c&&!o.has(c)&&(o.add(c),i.push(c))}}resolveLocalDepModuleName(e,t){let n=r.stripLocalDep(e);if(!n)return null;let i=H.join(t.srcPath,n),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>H.resolve(this.rootDir,a.srcPath)===o);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],n=[],i=new Set;for(n.push(e),i.add(e);n.length>0;){let o=n.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(n.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,n){this.validateProduct(n);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new w(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,n,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!X.existsSync(a))throw new w(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,n,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let D=this.getSignedHapName(c,o.srcPath,i,t);D&&(d=D)}let h=s?"-signed.hsp":"-signed.hap";if(!n&&!d.endsWith(h))throw new w(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let y=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!X.existsSync(y))throw new w(`Generated package file not found in ${y}.`,"Generated package file not found.");return y}findRemoteHspPaths(e,t,n="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,n),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=H.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,n,["outputs",t,c]);if(!X.existsSync(l))throw new w(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}resolveModuleSpecsForProduct(e){let t=[];for(let n of this.profile.modules){let i=n.targets;if(!i||i.length===0){t.push(`${n.name}@default`);continue}let o=i.filter(s=>!s.applyToProducts||s.applyToProducts.includes(e));if(o.length!==0)for(let s of o)t.push(`${n.name}@${s.name}`)}return t}listBuildArtifacts(e,t){let n=[];for(let i of e){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default",c=this.profile.modules.find(d=>d.name===s);if(!c)continue;let l=this.buildOutputPath(c.srcPath,t,["outputs",a]);if(X.existsSync(l))for(let d of X.readdirSync(l))(d.endsWith(".hap")||d.endsWith(".hsp")||d.endsWith(".har"))&&n.push(H.join(l,d))}return n}listProjectAppArtifacts(e){let t=E.ensurePathWithinRoot(this.rootDir,H.resolve(this.rootDir,"build","outputs",e));if(!X.existsSync(t))return[];let n=[],i=o=>{for(let s of X.readdirSync(o,{withFileTypes:!0})){let a=H.join(o,s.name);s.isDirectory()?i(a):s.name.endsWith(".app")&&n.push(a)}};return i(t),n}collectBuildArtifacts(e,t,n){let i=t;if(!e){let s=new Set(t);i=[...t,...this.profile.modules.map(a=>`${a.name}@default`).filter(a=>!s.has(a))]}let o=this.listBuildArtifacts(i,n);return e&&o.push(...this.listProjectAppArtifacts(n)),o}getSignedHapName(e,t,n,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,n,["outputs",i,o]);return X.existsSync(s)?o:null}buildOutputPath(e,t,n){let i=E.resolvePathWithinRoot(this.rootDir,e),o=H.resolve(i,"build",t,...n);return E.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let n=t.dependRemoteHsps;return Array.isArray(n)?n.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let n;try{let c=X.readFileSync(e,"utf-8");n=rr.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(n)?n:[n];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new w(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=H.basename(e);if(t!==e)throw new w(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new w(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import xp from"fs/promises";import rn from"path";function Et(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}import lp from"fs";import Jn from"path";import{homedir as dy}from"os";import Ue from"fs/promises";import ft from"path";import{randomUUID as cy}from"crypto";async function Me(r){try{return await Ue.lstat(r)}catch(e){if(e.code==="ENOENT")return;throw e}}async function ke(r){let e=ft.resolve(r),t=ft.dirname(e);try{return ft.join(await Ue.realpath(t),ft.basename(e))}catch(n){if(n.code!=="ENOENT"||t===e)throw n;return ft.join(await ke(t),ft.basename(e))}}async function op(r,e){let t=`${e}.backup-${cy()}`,n=await Me(e);n&&await Ue.rename(e,t);try{await Ue.rename(r,e)}catch(i){throw n&&await Ue.rename(t,e),i}n&&await Ue.rm(t,{recursive:!0,force:!0})}function he(r,e){let t=n=>ft.resolve(n).replace(/^\\\\\?\\/,"").replace(/[\\/]+$/,"");return process.platform==="win32"?t(r).toLowerCase()===t(e).toLowerCase():t(r)===t(e)}function Li(r,e){let t=(n,i)=>{let o=ft.relative(n,i);return o===""||!o.startsWith(`..${ft.sep}`)&&o!==".."&&!ft.isAbsolute(o)};return t(r,e)||t(e,r)}async function cc(r,e,t=!1){let n=await Ue.realpath(r);if(!(await Ue.stat(n)).isDirectory())throw new Error(`Skill source is not a directory: ${r}`);let i=await ke(e),o=await Me(i);if(he(n,i))return nr(i,"same-source");let s=o?await Ue.realpath(i).catch(()=>i):i;if(o?.isSymbolicLink()&&he(n,s))return nr(i,"correct-link");let a=await sp(i,t);if(a)return a;if(Li(n,i)||o&&Li(n,s))throw new Error(`Skill source and destination overlap: ${r}, ${e}`);await Ue.mkdir(ft.dirname(i),{recursive:!0});let c=`${i}.install-${cy()}`;try{let l=await KR(n,c);return await op(c,i),{success:!0,path:i,...l}}finally{await Ue.rm(c,{recursive:!0,force:!0})}}function nr(r,e){return{success:!0,skipped:!0,path:r,reason:e}}async function sp(r,e){if(!e&&await Me(r))return nr(r,"already-exists")}async function KR(r,e){try{let t=process.platform==="win32"?r:ft.relative(ft.dirname(e),r);return await Ue.symlink(t,e,process.platform==="win32"?"junction":"dir"),{mode:"symlink"}}catch(t){return await Ue.rm(e,{recursive:!0,force:!0}),await Ue.cp(r,e,{recursive:!0,dereference:!0,errorOnExist:!0,force:!1}),{mode:"copy",fallbackReason:t.code??String(t)}}}async function lc(r){let e=await ke(r),t=await Me(e);return t?(await Ue.rm(e,{recursive:!t.isSymbolicLink(),force:!0}),{success:!0,path:e}):nr(e,"not-installed")}var ly={amp:{displayName:"Amp",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},antigravity:{displayName:"Antigravity",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity/skills"},"antigravity-cli":{displayName:"Antigravity CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity-cli/skills"},astrbot:{displayName:"AstrBot",skillsDir:"data/skills",globalSkillsDir:"~/.astrbot/data/skills"},atomcode:{displayName:"atomcode",skillsDir:".atomcode/skills",globalSkillsDir:"~/.atomcode/skills",detect:["~/.atomcode"]},augment:{displayName:"Augment",skillsDir:".augment/skills",globalSkillsDir:"~/.augment/skills"},bob:{displayName:"IBM Bob",skillsDir:".bob/skills",globalSkillsDir:"~/.bob/skills"},"claude-code":{displayName:"Claude Code",skillsDir:".claude/skills",globalSkillsDir:"~/.claude/skills",detect:["~/.claude"]},cline:{displayName:"Cline",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"codearts-agent":{displayName:"CodeArts Agent",skillsDir:".codeartsdoer/skills",globalSkillsDir:"~/.codeartsdoer/skills"},codebuddy:{displayName:"CodeBuddy",skillsDir:".codebuddy/skills",globalSkillsDir:"~/.codebuddy/skills",detect:["~/.codebuddy"]},codex:{displayName:"Codex",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.codex"],legacySkillsDirs:[".codex/skills"],legacyGlobalSkillsDirs:["~/.codex/skills"]},continue:{displayName:"Continue",skillsDir:".continue/skills",globalSkillsDir:"~/.continue/skills"},crush:{displayName:"Crush",skillsDir:".crush/skills",globalSkillsDir:"~/.config/crush/skills"},cursor:{displayName:"Cursor",skillsDir:".agents/skills",globalSkillsDir:"~/.cursor/skills",detect:["~/.cursor"],legacySkillsDirs:[".cursor/skills"]},deepagents:{displayName:"Deep Agents",skillsDir:".agents/skills",globalSkillsDir:"~/.deepagents/agent/skills"},deveco:{displayName:"deveco",skillsDir:".deveco/skills",globalSkillsDir:"~/.config/deveco/skills",detect:["~/.config/deveco"]},devin:{displayName:"Devin for Terminal",skillsDir:".devin/skills",globalSkillsDir:"~/.config/devin/skills"},droid:{displayName:"Droid",skillsDir:".agents/skills",globalSkillsDir:"~/.factory/skills"},dsh:{displayName:"deepseek harness",skillsDir:".dsh/skills",globalSkillsDir:"~/.dsh/skills",detect:["~/.dsh"]},"gemini-cli":{displayName:"Gemini CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/skills"},"github-copilot":{displayName:"GitHub Copilot",skillsDir:".agents/skills",globalSkillsDir:"~/.copilot/skills"},goose:{displayName:"Goose",skillsDir:".goose/skills",globalSkillsDir:"~/.config/goose/skills"},grok:{displayName:"Grok Build",skillsDir:".grok/skills",globalSkillsDir:"~/.grok/skills"},"hermes-agent":{displayName:"Hermes Agent",skillsDir:".hermes/skills",globalSkillsDir:"~/.hermes/skills"},"iflow-cli":{displayName:"iFlow CLI",skillsDir:".iflow/skills",globalSkillsDir:"~/.iflow/skills"},junie:{displayName:"Junie",skillsDir:".junie/skills",globalSkillsDir:"~/.junie/skills"},kilo:{displayName:"Kilo Code",skillsDir:".agents/skills",globalSkillsDir:"~/.kilo/skills"},"kimi-code-cli":{displayName:"Kimi Code CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"kiro-cli":{displayName:"Kiro CLI",skillsDir:".kiro/skills",globalSkillsDir:"~/.kiro/skills"},kode:{displayName:"Kode",skillsDir:".kode/skills",globalSkillsDir:"~/.kode/skills"},lingma:{displayName:"Lingma",skillsDir:".lingma/skills",globalSkillsDir:"~/.lingma/skills"},"minimax-code":{displayName:"MiniMax Code",skillsDir:".minimax/skills",globalSkillsDir:"~/.minimax/skills"},"mistral-vibe":{displayName:"Mistral Vibe",skillsDir:".vibe/skills",globalSkillsDir:"~/.vibe/skills"},neovate:{displayName:"Neovate",skillsDir:".neovate/skills",globalSkillsDir:"~/.neovate/skills"},ona:{displayName:"Ona",skillsDir:".ona/skills",globalSkillsDir:"~/.ona/skills"},openclaw:{displayName:"OpenClaw",skillsDir:"skills",globalSkillsDir:"~/.openclaw/skills"},opencode:{displayName:"OpenCode",skillsDir:".agents/skills",globalSkillsDir:"~/.config/opencode/skills",detect:["~/.config/opencode"],legacySkillsDirs:[".opencode/skills"]},openhands:{displayName:"OpenHands",skillsDir:".openhands/skills",globalSkillsDir:"~/.openhands/skills"},pi:{displayName:"Pi",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.pi/agent"],legacySkillsDirs:[".pi/skills"],legacyGlobalSkillsDirs:["~/.pi/agent/skills"]},qoder:{displayName:"Qoder",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder/skills",detect:["~/.qoder"]},"qoder-cn":{displayName:"Qoder CN",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder-cn/skills"},"qwen-code":{displayName:"Qwen Code",skillsDir:".qwen/skills",globalSkillsDir:"~/.qwen/skills"},reasonix:{displayName:"Reasonix",skillsDir:".reasonix/skills",globalSkillsDir:"~/.reasonix/skills"},replit:{displayName:"Replit",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},trae:{displayName:"Trae",skillsDir:".trae/skills",globalSkillsDir:"~/.trae/skills"},"trae-cn":{displayName:"Trae CN",skillsDir:".trae/skills",globalSkillsDir:"~/.trae-cn/skills",detect:["~/.trae-cn"],legacySkillsDirs:[".trae-cn/skills"]},universal:{displayName:"Universal",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},warp:{displayName:"Warp",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},windsurf:{displayName:"Windsurf",skillsDir:".windsurf/skills",globalSkillsDir:"~/.codeium/windsurf/skills"},zcode:{displayName:"ZCode",skillsDir:".zcode/skills",globalSkillsDir:"~/.zcode/skills"},zed:{displayName:"Zed",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"}};var ap="https://matrix.openharmony.cn",Pt={TAGS_API_URL:`${ap}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${ap}/api/registry/skill/skills`,SKILL_API_BASE:`${ap}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},cp=".agents/skills",ls=ly;function up(r){return Jn.resolve(r==="~"||r.startsWith("~/")?Jn.join(dy(),r.slice(1)):r)}function Qe(){return Object.keys(ls)}function dc(r){return[...new Set((r??"").split(",").map(e=>e.trim()).filter(Boolean))]}function Ot(r){let e=Object.prototype.hasOwnProperty.call(ls,r)?ls[r]:void 0;if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Qe().join(", ")}`);return e}function dp(r){return up(Ot(r).globalSkillsDir)}function pp(r,e){return Jn.join(r,Ot(e).skillsDir)}function ir(r){return Jn.join(r??dy(),cp)}function en(r,e){return e?pp(e,r):dp(r)}function uc(r,e){let t=en(r,e);return he(t,ir(e))}function uy(r,e){let t=Ot(r),n=e?(t.legacySkillsDirs??[]).map(o=>Jn.join(e,o)):(t.legacyGlobalSkillsDirs??[]).map(up),i=[en(r,e)];return n.filter(o=>i.some(s=>he(s,o))?!1:(i.push(o),!0))}function fp(r,e){let t=Ot(e).skillsDir.split("/")[0];return t.startsWith(".")&&lp.existsSync(Jn.join(r,t))}function Kn(r,e){let t=Ot(r);if(t.detect)return t.detect.some(o=>lp.existsSync(up(o)));let n=dp(r);return![ir(),dp("universal")].some(o=>he(o,n))&&lp.existsSync(Jn.dirname(n))?!0:!!(e&&t.skillsDir!==cp&&fp(e,r))}import pc from"path";function py(r){let e=[];r.agents.length&&e.push({agents:[...new Set(r.agents)]});let t=new Map;for(let{project:n,agent:i}of r.projectAgents){let o=t.get(n)??[];o.push(i),t.set(n,o)}for(let[n,i]of t)e.push({project:n,agents:[...new Set(i)]});return e}async function XR(r,e,t,n){let i=[];for(let o of uy(r,e.project)){let s=await ke(pc.join(o,t));!n.some(a=>he(a,s))&&await Me(s)&&i.push(s)}return i}async function fc(r,e,t=!0){let n=await ke(pc.join(ir(r.project),e)),i=[];for(let o of r.agents){let s=en(o,r.project),a=await ke(pc.join(s,e)),c=await XR(o,r,e,[n,a]),l=!!(r.project&&!t&&!uc(o,r.project)&&c.length===0&&!fp(r.project,o)),d=i.find(h=>he(h.path,a));d?(d.legacy.push(...c.filter(h=>!d.legacy.some(y=>he(y,h)))),d.skipped&&=l):i.push({path:a,legacy:c,skipped:l})}return i}async function fy(r,e,t=!0){let n=await fc(r,e,t);if(n.every(o=>o.skipped))return n;let i=await ke(pc.join(ir(r.project),e));return n.some(o=>he(o.path,i))||n.unshift({path:i,legacy:[],skipped:!1}),n}import Fi from"fs/promises";import Ft from"path";import{randomUUID as CD}from"crypto";import{lock as kD}from"proper-lockfile";import*as ds from"fs";import*as yy from"path";import{homedir as ZR}from"os";import*as my from"fs";import*as et from"path";function mp(r,e){let t=et.relative(e,r);return t===""||!et.isAbsolute(t)&&!t.startsWith(`..${et.sep}`)&&t!==".."}function tn(r){let e=et.resolve(r),t=[],n=e;for(;;)try{let i=my.realpathSync(n);return t.length===0?i:et.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=et.dirname(n);if(o===n)return e;t.push(et.basename(n)),n=o}}function hy(r,e){let t=tn(e),n=tn(r);return mp(n,t)?n:null}function hp(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function mc(r){let e=hp(r);if(!e)throw new Error("Path must not be empty.");return tn(e)}var QR="deveco-cli",gy,gp=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function eD(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":hp(r))||yy.join(ZR(),".local","share",QR);try{return mc(t)}catch(n){throw new gp(n instanceof Error?n.message:String(n))}}function j(){if(gy!==void 0)return gy;let r=eD();try{if(ds.existsSync(r))return ds.realpathSync(r)}catch{}return r}import wD from"adm-zip";import vD from"crypto";import{timingSafeEqual as bD}from"crypto";import Sp from"fs";import Lt from"path";import{fileURLToPath as SD}from"url";import{homedir as or}from"os";import tt from"path";var sr="deveco-mcp",hc={"trae-cn":".trae-cn",opencode:".config/opencode",pi:".pi/agent",deveco:".config/deveco",cursor:".cursor",codebuddy:".codebuddy",qoder:".qoder","claude-code":".claude",codex:".codex",atomcode:".atomcode",dsh:".dsh"};var Rr={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:tt.join(or(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:tt.join(or(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:tt.join(process.platform==="win32"?tt.join(process.env.APPDATA??tt.join(or(),"AppData","Roaming"),"Trae CN","User"):tt.join(or(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:tt.join(or(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:tt.join(or(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"codebuddy"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:tt.join(process.platform==="win32"?tt.join(process.env.APPDATA??tt.join(or(),"AppData","Roaming"),"Qoder","SharedClientCache"):tt.join(or(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:tt.join(or(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:tt.join(or(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function vy(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function wy(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function tD(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."}}}function by(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function gc(r,e){return r.format==="opencode"?vy(e):r.format==="claude-code"||r.format==="codex"?wy(e):r.format==="codebuddy"?tD(e):by(e)}var yp="https://developer.huawei.com/consumer/cn/download/";import pD from"axios";var rD={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function nD(r){try{return new URL(r)}catch{return null}}function Sy(r){var e=(typeof r=="string"?nD(r):r)||{},t=e.protocol,n=e.host,i=e.port;if(typeof n!="string"||!n||typeof t!="string"||(t=t.split(":",1)[0],n=n.replace(/:\d*$/,""),i=parseInt(i)||rD[t]||0,!iD(n,i)))return"";var o=wp(t+"_proxy")||wp("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function iD(r,e){var t=wp("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(n){if(!n)return!0;var i=n.match(/^(.+):(\d+)$/),o=i?i[1]:n,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!r.endsWith(o)):r!==o}):!0}function wp(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}import{spawn as Cy}from"child_process";import*as Yn from"fs";import*as ky from"os";import*as yc from"path";var Ry=6e4;async function oD(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Ey(r,"ProxyServer");if(!e)return null;let t=await Ey(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Ey(r,e){return new Promise(t=>{let n=Cy("reg.exe",["query",r,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";n.stdout.on("data",o=>{i+=o.toString()}),n.on("error",()=>t(null)),n.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function sD(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function aD(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Py(r){let e={},t=0,n="";for(let i of r.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),n=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:n,headers:e}}function cD(r,e,t,n){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((r.timeoutMs??Ry)/1e3)))];return r.method&&r.method!=="GET"&&i.push("-X",r.method),r.data!==void 0&&i.push("--data-binary",r.data),i.push(...lD(r.headers,r.data!==void 0)),n?(i.push("--dump-header",t),i.push("--output",n)):i.push("--include"),i.push(r.url),i}function lD(r,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),n=[],i=!1;for(let[o,s]of Object.entries(r??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||n.push("-H",`${o}: ${s}`)}return e&&!i&&n.push("-H","Content-Type: application/json"),n}function dD(r,e,t){if(t){let l=Yn.readFileSync(e,"utf8"),d=Yn.readFileSync(t),h=Py(l);return{statusCode:h.statusCode,statusText:h.statusText,body:d.toString("base64"),headers:h.headers,bodyBuffer:d}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let i=r.slice(n),o=i.indexOf(`\r
|
|
15
|
+
\r
|
|
16
|
+
`);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=Py(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function Dy(r){if(process.platform!=="win32")return null;let e=sD()??await oD();if(!e)return null;let t;r.binary&&(t=Yn.mkdtempSync(yc.join(ky.tmpdir(),"curl-")));let n=t?yc.join(t,"header.tmp"):void 0,i=t?yc.join(t,"body.tmp"):void 0;try{let o=cD(r,e,n,i),s=await uD(o,r.timeoutMs);return!s||s.code!==0?null:dD(s.stdout,n,i)}catch{return null}finally{t&&Yn.rmSync(t,{recursive:!0,force:!0})}}function uD(r,e){let t=aD();return new Promise(n=>{let i=Cy(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??Ry);i.stdout.on("data",c=>{o+=c.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),i.on("close",c=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:c??-1,stdout:o})})})}function fD(r){let e=new URL(r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var vp=class{client;constructor(){let e={timeout:ts.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ja.USER_AGENT,"accept-language":Ja.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=pD.create(e),this.client.interceptors.request.use(t=>{let n=Sy(t.url??"");return t.proxy=n?fD(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`,i=new Error(`${t.message}
|
|
17
|
+
${n}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"GET",t)}}async post(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw n}}async postAllowFailure(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}async deleteAllowFailure(e,t){try{let n=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(n.data),o=i.toString("utf8");return{statusCode:n.status,statusText:n.statusText??"",buffer:i,body:o}}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw n}}async withCurlFallback(e,t,n,i){let o=await this.tryCurlFallback(e,t,n,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,n,i,o=!1){if(process.platform!=="win32"||!(e instanceof Error)||!mD(e))return null;let s,a=t;return n==="GET"?i?.params&&(a=hD(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Dy({url:a,method:n,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},$=new vp;function mD(r){if(r.response?.status===407)return!0;let e=r.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:r.code==="SELF_SIGNED_CERT_IN_CHAIN"||r.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||r.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||r.code==="CERT_HAS_EXPIRED"||r.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function hD(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let n=t.toString();if(!n)return r;let i=r.includes("?")?"&":"?";return`${r}${i}${n}`}import*as xy from"fs";import*as Iy from"path";var Ay=["DevEco"];async function us(){let r=await $.get(Pt.TAGS_API_URL),t=bc(r,"Tags API").data.skill.filter(n=>n.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(n=>n.id)}async function gD(r){let e=[],t=Pt.DEFAULT_PAGE_SIZE,n=Pt.DEFAULT_MAX_PAGES,i=1;for(;i<=n;){let o=await $.post(Pt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[r]}}),s=bc(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function wc(r){let e=new Map,t=r.map(i=>gD(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Ay.includes(o.name)))}async function yD(r,e){let t=await $.post(Pt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Pt.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return bc(t,"Skills API").data.list}async function vc(r,e){let t=new Map,n=e.map(o=>yD(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Ay.includes(s.name)))}function bp(r){Et(r);let e=[];for(let t of Qe()){let n=en(t);if(!Kn(t))continue;let i=Iy.join(n,r);xy.existsSync(i)&&e.push(Ot(t).displayName)}return e.sort()}function bc(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=$.parseJson(r);if(t.code!==Pt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Ty(r){Et(r);let e=`${Pt.SKILL_API_BASE}/${r}/checksum`,t=await $.get(e);return bc(t,"Checksum API").data}var Ny=Sp.promises;function _y(r,e){let t=Lt.resolve(e),n=Lt.resolve(r),i=Lt.relative(n,t);if(i.startsWith("..")||Lt.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Ep(r){return Lt.isAbsolute(r)?r:Lt.resolve(process.cwd(),r)}function ED(r){return vD.createHash("sha256").update(r).digest("hex")}async function PD(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=ED(r),i=e.sha256.toLowerCase(),o=Buffer.from(n,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!bD(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Pp(r){Et(r);let e=`${Pt.SKILL_API_BASE}/${r}/install?format=zip`,t=await $.getBinary(e),n=await Ty(r);return await PD(t,n),t}async function My(r,e,t){Et(t);let n=new wD(r),i=n.getEntries();try{await Ny.stat(e)}catch{await Ny.mkdir(e,{recursive:!0})}let o=Lt.join(e,t);_y(e,o);for(let s of i){let a=Lt.join(o,s.entryName);_y(o,a)}n.extractAllTo(o,!0)}function Xn(){let e=Lt.dirname(SD(import.meta.url));for(;;){let t=Lt.join(e,"skills","deveco-cli");if(Sp.existsSync(t)&&Sp.statSync(t).isDirectory())return t;let n=Lt.dirname(e);if(n===e)break;e=n}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}function Oy(r){return r?Ft.join(r,".deveco-cli","skills"):Ft.join(j(),"skills")}function RD(r,e){return Et(r),Ft.join(Oy(e),"store",r)}async function Ly(r,e){let t=e??j(),n=await Fi.realpath(t).catch(s=>{if(s.code==="ENOENT")return ke(t);throw s}),i=Ft.join(n,Ft.relative(t,r)),o=await ke(i);if(!he(i,o))throw new Error(`Skill storage parent redirects outside its managed location: ${i}`);return o}async function Cp(r,e){return Ly(RD(r,e),e)}async function ps(r,e,t){Et(r);let n=e.customPath??Oy(e.project),i=e.customPath?await ke(Ft.join(n,`.${r}.lock`)):await Ly(Ft.join(n,"locks",`${r}.lock`),e.project);await Fi.mkdir(Ft.dirname(i),{recursive:!0});let o=await kD(n,{realpath:!1,lockfilePath:i,stale:3e4,update:1e4,retries:{retries:100,minTimeout:50,maxTimeout:200}});try{return await t()}finally{await o()}}async function Fy(r){let e=await Fi.lstat(r);if(!e.isDirectory()||e.isSymbolicLink()||!(await Fi.stat(Ft.join(r,"SKILL.md"))).isFile())throw new Error(`Invalid Skill store: ${r}`)}async function $y(r,e,t,n,i){let o=await Cp(r,t),s=await Me(o);if(!i&&!s&&(await Promise.all(n.map(c=>Me(c.path)))).every(Boolean))return{results:n.map(c=>nr(c.path,"already-exists"))};for(let a of n)for(let c of[a.path,...a.legacy])if(Li(o,c))throw new Error(`Skill store and destination overlap: ${o}, ${c}`);if(!i&&s){try{await Fy(o)}catch(a){throw new Error(`Cannot reuse Skill store ${o}; use --force to replace: ${a.message}`,{cause:a})}return{source:o,results:[]}}return{source:o,results:[await Hy(r,e,o)]}}async function jy(r,e,t,n){let i=await ke(t);return await sp(i,n)??Hy(r,e,i)}async function Hy(r,e,t){await Fi.mkdir(Ft.dirname(t),{recursive:!0});let n=`${t}.extract-${CD()}`;try{await My(e,n,r);let i=Ft.join(n,r);return await Fy(i),await op(i,t),{success:!0,path:t,reason:"shared-entity-updated"}}finally{await Fi.rm(n,{recursive:!0,force:!0})}}function fs(r,e){return{success:!1,path:r,error:e instanceof Error?e.message:String(e)}}async function kp(r,e,t){let n=[];for(let i of py(e))try{n.push(...await ps(r,i,()=>t(i)))}catch(o){n.push(fs(rn.join(ir(i.project),r),o))}return n}async function Dp(r){return xp.realpath(r).catch(e=>{if(e.code==="ENOENT"||e.code==="ELOOP")return r;throw e})}async function DD(r,e){let t=await xp.realpath(e);for(let n of r.legacy){let i=await Me(n);if(i&&!i.isSymbolicLink()&&Li(t,n))throw new Error(`Skill source and legacy destination overlap: ${e}, ${n}`);await lc(n)}}async function xD(r,e,t,n){let i=[];for(let o of Qe()){let s=en(o,e.project);if(e.agents.includes(o)||uc(o,e.project)&&!Kn(o,e.project))continue;let a=await ke(rn.join(s,r)),c=await Me(a);c&&(he(a,t)&&Kn(o,e.project)||n&&c.isSymbolicLink()&&he(await Dp(a),n))&&i.push(Ot(o).displayName)}return[...new Set(i)]}function ID(r,e){let t=`still used by ${e.join(", ")}`;return console.log(`Skill ${rn.basename(r)} in ${rn.dirname(r)} is kept: ${t}.`),nr(r,t)}async function Rp(r,e,t,n){try{if(!await Me(r))return;let i=await xD(e,t,r,n);return i.length?ID(r,i):await lc(r)}catch(i){return fs(r,i)}}var ar=class{async installBundledSkill(e,t,n=!1){return await xp.access(rn.join(e,"SKILL.md")),t.customPath?this.installCustom("deveco-cli",e,t.customPath,n):kp("deveco-cli",t,i=>this.installScope("deveco-cli",e,i,t.explicitAgents,n))}async installArchiveSkill(e,t,n,i=!1){return Et(e),n.customPath?this.installCustom(e,t,n.customPath,i):kp(e,n,o=>this.installScope(e,t,o,n.explicitAgents,i))}async installCustom(e,t,n,i){let o=rn.join(n,e);try{return await ps(e,{customPath:n},async()=>[typeof t=="string"?await cc(t,o,i):await jy(e,t,o,i)])}catch(s){return[fs(o,s)]}}async installScope(e,t,n,i=!0,o=!1){let s=await fy(n,e,i),a=s.filter(l=>!l.skipped),c=s.filter(l=>l.skipped).map(l=>nr(l.path,"agent-project-root-missing"));if(!a.length)return c;try{let l=typeof t=="string"?{source:t,results:[]}:await $y(e,t,n.project,a,o);return[...c,...l.results,...l.source?await this.installSkillEntries(l.source,a,o):[]]}catch(l){return[...c,...a.map(d=>fs(d.path,l))]}}async installSkillEntries(e,t,n){let i=[];for(let o of t)try{i.push(await cc(e,o.path,n)),n&&await DD(o,e)}catch(s){i.push(fs(o.path,s))}return i}async migrateBundledSkill(e,t){await ps("deveco-cli",t,()=>this.migrateBundledScope(e,t))}async migrateBundledScope(e,t){let n,i=[];for(let o of t.agents)try{for(let s of await fc({...t,agents:[o]},"deveco-cli"))await this.migrateBundledDestination(e,s,i)}catch(s){n=s,console.error(`Skill migration failed for ${o}: ${s.message}`)}if(n)throw n}async migrateBundledDestination(e,t,n){let i=await Me(t.path);(!i||!i.isDirectory()&&!i.isSymbolicLink())&&!t.legacy.length||n.some(o=>he(o,t.path))||((await cc(e,t.path)).reason==="already-exists"&&console.warn(`Skill migration skipped: ${t.path} (already exists; run devecocli init --force to replace).`),n.push(t.path))}async removeSkill(e,t){if(Et(e),t.customPath){let n=rn.join(t.customPath,e);return ps(e,t,async()=>[await lc(n)])}return kp(e,t,n=>this.removeScope(e,n,t.explicitAgents))}async removeScope(e,t,n=!0){let i=await ke(rn.join(ir(t.project),e)),o=await this.removeAgentEntries(e,t,i,n);if(o.every(s=>s.success)){let s=await Rp(i,e,t,await Dp(i));s&&o.push(s)}if(o.every(s=>s.success)){let s=await Cp(e,t.project),a=await Rp(s,e,{...t,agents:[]},await Dp(s));a&&o.push(a)}return o.length||(console.log(`Skill ${e} not found for the selected agents.`),o.push(nr(i,"not-installed"))),o}async removeAgentEntries(e,t,n,i){let o=new Set;for(let a of await fc(t,e,i))if(!a.skipped)for(let c of[a.path,...a.legacy])he(c,n)||o.add(c);let s=[];for(let a of o){let c=await Rp(a,e,t);c&&s.push(c)}return s}};import Sc from"fs/promises";import Uy from"path";function AD(r){return`'${process.platform==="win32"?r.replace(/'/g,"''"):r.replace(/'/g,"'\\''")}'`}async function TD(r,e){try{if(!(await Me(r))?.isSymbolicLink())return;let n=await Sc.realpath(r);return he(n,e)?void 0:{path:r,reason:`points to ${n}`,repair:!0}}catch(t){let n=t.code,i=n==="ENOENT"||n==="ELOOP"||n==="ENOTDIR";return{path:r,reason:i?"broken link":`cannot check: ${t.message}`,repair:i}}}var Ip=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await Sc.realpath(e),n=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(n))return;this.checked.add(n);let i=await Sc.realpath(Xn());if(!(await Sc.stat(Uy.join(i,"SKILL.md"))).isFile())throw new Error(`Skill source has no SKILL.md: ${i}`);let o=await this.checkKnownEntries(t,i);this.reportIssues(t,o)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let n=new Set([ir(e),...Qe().map(s=>pp(e,s))]),i=[],o=[];for(let s of n){let a=Uy.join(s,"deveco-cli");try{let c=await ke(a);if(i.some(d=>he(d,c)))continue;i.push(c);let l=await TD(c,t);l&&o.push(l)}catch(c){o.push({path:a,reason:`cannot check: ${c.message}`,repair:!1})}}return o}reportIssues(e,t){for(let n of t)console.warn(`Project Skill link: ${n.path} (${n.reason}).`);t.some(n=>n.repair)&&(console.warn(`Run: devecocli init --project ${AD(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},rt=new Ip;import _p from"fs";import qy from"path";import{cyan as GD}from"colorette";import{spawn as HD}from"child_process";import*as Gy from"fs";import*as Pc from"path";import{yellow as UD,cyan as BD}from"colorette";import WD from"proper-lockfile";import{compare as ND}from"semver";function nn(r,e){return ND(r,e)}function $i(r,e){let t=Math.max(r.split(".").length,e.split(".").length);for(let n=0;n<t;n++){let i=Number(r.split(".")[n]??0)-Number(e.split(".")[n]??0);if(i)return i}return 0}function ji(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-common"}function cr(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.10-Test.1"}function on(){return"daily"}function $t(){return Number.isFinite(1),1}var jt="@deveco-test/deveco-cli-knowledgebase";function Hi(){let r=process.env.DEVECO_CLI_DISABLE_UPDATE;return r==="check"||r==="all"?r:"off"}import*as ms from"fs";import*as hs from"path";var _D={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Ap=new Map,sn=class r{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=hs.join(e,"cache.json"),this.lockFilePath=hs.join(e,"check.lock")}async writeSuccess(e,t=[],n,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:n,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(r.CHECK_WINDOW_HOUR,0,0,0),n=t>Date.now()?t-r.ONE_DAY_MS:t;return e<n}getLockPath(){return this.lockFilePath}read(){let e=Ap.get(this.cacheFilePath);if(e)return e;try{let t=ms.readFileSync(this.cacheFilePath,"utf-8"),n=JSON.parse(t);return Ap.set(this.cacheFilePath,n),n}catch{return{..._D}}}async write(e){f(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ms.promises.mkdir(hs.dirname(this.cacheFilePath),{recursive:!0}),await ms.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Ap.set(this.cacheFilePath,e)}};import{createRequire as MD}from"module";import{dirname as OD,join as Ui}from"path";import{pathToFileURL as LD}from"url";import{readFile as By,access as Tp}from"fs/promises";import*as Wy from"semver";var FD=MD(import.meta.url);async function $D(){try{let r=FD.resolve(`${jt}/package.json`),e=JSON.parse(await By(r,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:OD(r)}}catch{return null}}async function Vy(){let r=j(),e=Ui(r,"doc-data","current.json"),t;try{t=JSON.parse(await By(e,"utf8"))}catch{return null}let n=Ui(r,"doc-data",t.version);try{return await Tp(Ui(n,"dist","engine","index.js")),await Tp(Ui(n,"docs.zip")),await Tp(Ui(n,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:n}}catch{return null}}async function jD(){return[await Vy(),await $D()].filter(e=>e!==null).sort((e,t)=>Wy.rcompare(e.version,t.version))}async function Bi(){let r=$t(),e=await Vy();return e&&e.apiVersion<=r?e.version:null}async function Ec(){let r=$t(),e=await jD(),t=!1;for(let n of e){if(n.apiVersion>r){f(`docs: skip candidate v${n.version} (apiVersion ${n.apiVersion} > ${r})`);continue}t=!0;try{let i=Ui(n.dir,"dist","engine","index.js");return await import(LD(i).href)}catch(i){f(`docs: candidate v${n.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw e.length>0&&!t?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please run `devecocli docs update` or reinstall CLI")}var gs=class{constructor(e){this.actionCommand=e}cache=new sn(Pc.join(j(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=cr(),t=on(),n=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=n!=null&&n!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&nn(c,e)>0&&a.push(UD(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.log();for(let d of a)console.log(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){f(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=$t(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let n=this.cache.getLatestCompatibleDocsVersion();if(!n)return{message:null,stale:!1};let i=await Bi();return i&&nn(n,i)<=0?{message:null,stale:!1}:{message:BD(`New docs version ${n} available, run \`devecocli docs update\` to upgrade`),stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await VD(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];f(`Executing: ${process.execPath} ${e.join(" ")}`),HD(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{f("Update check lock held by another process, skipping")}}};async function VD(r,e){await Gy.promises.mkdir(Pc.dirname(r),{recursive:!0});let t=await WD.lock(r,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var Np=_p.promises;async function qD(r){let e=dc(r);for(let t of e)Ot(t);return e}async function zD(r){return Qe().filter(e=>Kn(e,r))}async function JD(){let r=Xn();await new ar().migrateBundledSkill(r,{agents:Qe()})}async function zy(){try{let r=qy.join(j(),"skills","migration-version"),e=await Np.readFile(r,"utf8").catch(n=>{if(n.code==="ENOENT")return"";throw n}),t=cr();if(e.trim()===t)return;await JD(),await Np.mkdir(qy.dirname(r),{recursive:!0}),await Np.writeFile(r,t,"utf8")}catch{}}function Wi(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(GD("Finished:"));for(let i of r){if(!i.path)continue;let o=i.reason==="already-exists"?"already exists; use --force to replace":i.reason,s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Dr(r,e,t){if(!_p.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!_p.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function Vi(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?Ep(r):void 0,resolvedProject:e?Ep(e):void 0}}async function Gi(r,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let n=r.agent?await qD(r.agent):await zD(t);if(!n.length)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return t?{agents:[],explicitAgents:!!r.agent,projectAgents:n.map(i=>({project:t,agent:i}))}:{agents:n,projectAgents:[],explicitAgents:!!r.agent}}import KD from"fs";import Cc from"path";import{cyan as YD}from"colorette";import*as kc from"smol-toml";var qi=KD.promises;async function XD(r){try{let e=await qi.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${r}: ${e.message}`,{cause:e})}}async function ZD(r){try{let e=await qi.readFile(r,"utf8");return e.trim()===""?{}:kc.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function QD(r,e){let t=Cc.dirname(r);await qi.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await qi.writeFile(r,n,"utf8")}async function ex(r,e){let t=Cc.dirname(r);await qi.mkdir(t,{recursive:!0});let n=kc.stringify(e);await qi.writeFile(r,n,"utf8")}function Jy(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function Ky(r,e,t,n,i){(!r[e]||typeof r[e]!="object")&&(r[e]={});let o=r[e];return t in o&&!i?!1:(o[t]=n,!0)}async function Yy(r,e){return r.format==="codex"?ZD(e):XD(e)}async function Xy(r,e,t){return r.format==="codex"?ex(e,t):QD(e,t)}async function Mp(r,e,t=!1){let n=Rr[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Rr).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await Yy(n,n.globalConfigPath);if(Jy(i,n.mcpServersKey,sr)&&!t)return console.log(`MCP server ${sr} already configured in ${n.globalConfigPath}.`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=gc(n,void 0);return Ky(i,n.mcpServersKey,sr,o,t),await Xy(n,n.globalConfigPath,i),console.log(`MCP server ${sr} configured in ${n.globalConfigPath}.`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}async function Rc(r,e,t=!1){let n=Rr[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Rr).join(", ")}`};let i=Cc.isAbsolute(n.projectConfigPath)?n.projectConfigPath:Cc.join(e,n.projectConfigPath);try{let o=await Yy(n,i);if(Jy(o,n.mcpServersKey,sr)&&!t)return console.log(`MCP server ${sr} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=gc(n,e);return Ky(o,n.mcpServersKey,sr,s,t),await Xy(n,i,o),console.log(`MCP server ${sr} configured in ${i}.`),{success:!0,configPath:i,agentName:r,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}function Op(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(YD("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}import tx from"fs";import rx from"path";import{homedir as nx}from"os";async function Lp(r,e){let t=[],n=r.agent?dc(r.agent):Object.keys(hc);for(let i of n){if(!Object.prototype.hasOwnProperty.call(hc,i))throw new Error(`Invalid MCP agent: ${i}`);(r.agent||tx.existsSync(rx.join(nx(),hc[i])))&&t.push(i)}if(!t.length)throw new Error("No agents supporting MCP configuration found; use --skill");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}import{spawnSync as nw}from"child_process";import Oe from"fs";import*as nt from"os";import*as I from"path";import xc from"fs";import*as Ic from"os";import*as ys from"path";import sx from"regedit";import{execFileSync as ix}from"child_process";import Zy from"fs";import*as Qy from"os";import*as Fp from"path";function Dc(r,e){let t=Fp.join(r,"Contents","Info.plist");if(!Zy.existsSync(t)){f(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[n,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=ix(n,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function ox(r){let e=Dc(r,"CFBundleShortVersionString");if(!e)return Dc(r,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),n=[Dc(r,"CFBundleVersion"),Dc(r,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of n){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function an(r){if(Qy.platform()==="darwin")return ox(r);let e=Fp.join(r,"product-info.json");try{let t=JSON.parse(Zy.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var ax="DevEco Studio",cx=["Contents","Resources","product-info.json"],lx="name";function dx(r){return r.filter(e=>{try{return xc.statSync(e).isDirectory()}catch{return!1}})}function ux(r){let e=ys.join(r,...cx);if(xc.existsSync(e))try{let n=JSON.parse(xc.readFileSync(e,"utf8"))[lx];return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function px(r){return ux(r)===ax}function fx(){let r=[];for(let e of[ys.join(Ic.homedir(),"Applications"),"/Applications"])try{r.push(...xc.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>ys.join(e,t)).filter(px))}catch{}return r}function ew(r){return new Promise((e,t)=>sx.list(r,(n,i)=>n?t(n):e(i)))}async function tw(r,e,t){let i=((await ew([r]))[r]?.keys??[]).filter(e).map(s=>`${r}\\${s}`);if(i.length===0)return[];let o=await ew(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function mx(){let r=[ys.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{r.push(...await tw(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{r.push(...await tw(e,()=>!0,""))}catch{}return r}async function rw(){let r=Ic.platform();if(r==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=r==="darwin"?fx():await mx(),t=dx(e).flatMap(n=>{let i=an(n);return i?(f(`[ToolProvider] ${n} => version ${i}`),[{root:n,version:i}]):(f(`[ToolProvider] Skipping ${n}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation, or set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");return t.reduce((n,i)=>$i(i.version,n.version)>0?i:n)}var hx=/^#\s*Version:\s*(\S+)/,gx="26.0.0.810";function yx(r){try{let e=JSON.parse(Oe.readFileSync(r,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){f(`[ToolProvider] Failed to parse API level from ${r}: ${e instanceof Error?e.message:String(e)}`);return}}function wx(r){let e=I.join(r,"default","openharmony");return[I.join(r,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>I.join(e,t,"oh-uni-package.json"))]}var P=class r{constructor(e,t,n,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=n;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return r.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=r.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(Oe.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=r.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return Oe.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=r.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.")}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return $i(e,t)}static async checkVersion(){let e=await r.resolveInstallSource();(e.sourceType==="clt"?r.fromCLT(e.toolchainRoot):r.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await r.resolveInstallSource();return e.sourceType==="clt"?r.fromCLT(e.toolchainRoot):r.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=r.buildToolPaths(e,"clt");return r.assertBuiltPathsInsideRoot(e,t,!1),new r("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,r.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let n=r.buildToolPaths(e,"studio");return r.assertBuiltPathsInsideRoot(e,n,!0),new r(t,e,e,n.nodePath,n.ohpmJsPath,n.hvigorJsPath,n.javaPath,n.sdkPath,n.hdcPath,n.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?r.readCltVersion(this._toolchainRoot):an(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");r.assertMinimumVersion(r.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),r.assertMinimumVersion(an(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,n,i,o){if(!e)throw new w(`Failed to determine ${t} version from ${n} at ${o}`,`Failed to determine ${t} version from ${n}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new w(`Invalid ${t} version "${e}" from ${n} at ${o}`,`Invalid ${t} version "${e}" from ${n}`);if($i(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
18
|
+
${yp}`)}static resolveCodelinterPath(e,t){let n=r.buildToolPaths(e,t).codelinterCandidates,i=n.find(r.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new w(`${a}
|
|
16
19
|
Searched paths:
|
|
17
|
-
${
|
|
18
|
-
`)}`,a)}let o=
|
|
19
|
-
`)){let
|
|
20
|
-
`)){let r=t.trim();if(!r)continue;let i=r.split(",");if(i.length<3)continue;let o=Number(i[0]),s=Number(i[1]),a=Number(i[2]);isNaN(o)||isNaN(s)||isNaN(a)||e.push({pid:o,ppid:s,rssBytes:a})}return e}function um(n,e){let t=new Map,r=new Map;for(let a of n){t.set(a.pid,a.rssBytes);let c=r.get(a.ppid);c?c.push(a.pid):r.set(a.ppid,[a.pid])}let i=0,o=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(o.has(a))continue;o.add(a),i+=t.get(a)??0;let c=r.get(a);c&&s.push(...c)}return i}async function Nb(n){let e=await Rb();return um(e,n)}function Lb(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${fl}'; sleep ${e}; done`;return p(`Executing: sh -c ${t}`),sm("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&cm()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${fl}'; Start-Sleep -Milliseconds ${n} }`;return p(`Executing: ${ps} -NoProfile -Command ${e}`),sm(ps,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function ne(n){return`${(n/1024/1024).toFixed(2)}MB`}async function am(n,e){if(!n)return process.memoryUsage().rss;if(e)return Nb(n);let t=await et(n);return t?Number(t)*1024:0}function An(n,e=500,t=!1){let r=0,i=!1,o=a=>{if(i||!n)return;let c=t?um(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return Ob(e);if(process.platform==="linux")return _b(e,o,()=>r);let s=Lb(e);return s?(Mb(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await am(n,t);return Math.max(r,a)}}):{stop:async()=>{i=!0;let a=await am(n,t);return Math.max(r,a)}}}function Mb(n,e){let t=process.platform==="darwin"?lm:dm,r="";n.stdout?.on("data",i=>{r+=i.toString();let o=r.split(fl);r=o.pop()??"";for(let s of o)e(t(s))}),n.on("error",()=>{})}function Ob(n){let e=process.memoryUsage().rss,t=setInterval(()=>{let r=process.memoryUsage().rss;r>e&&(e=r)},n);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function _b(n,e,t){e(us());let r=setInterval(()=>e(us()),n);return{stop:async()=>(clearInterval(r),e(us()),t())}}function Fb(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function $b(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var tt=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=fr.dirname(e.javaPath),o=`${i}${fr.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath},a=fs.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!a&&(s.JAVA_HOME=fr.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){p("[HvigorAdapter] Daemon already running.");return}p("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}async isDaemonAlive(e){let t=this.findProjectDaemon(e);return t?this.isPortListening(t.port):!1}isPortListening(e){return new Promise(t=>{let r=new pm.Socket;r.setTimeout(2e3),r.once("connect",()=>{r.destroy(),t(!0)}),r.once("error",()=>t(!1)),r.once("timeout",()=>{r.destroy(),t(!1)}),r.connect(e,"127.0.0.1")})}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!ms.existsSync(t))return null;try{let r=ms.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||fr.join(fs.homedir(),".hvigor");return fr.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];return t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];p(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=jb(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=He()?void 0:An(o.pid,500,!0),a="";try{await o}finally{if(s){let c=await s.stop();c>0&&(a=ne(c),p(`Hvigor peak memory: ${a}`))}}return a}};import{execa as Hb}from"execa";var Dn=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];p(`Executing: ${e} ${t.join(" ")}`);let r=Hb(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=He()?void 0:An(r.pid,500,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=ne(o))}}}};import{mkdir as Ub}from"fs/promises";import{dirname as Bb,resolve as Wb}from"path";import{execa as Vb}from"execa";import{lock as gl,check as e$}from"proper-lockfile";function yl(n){return Wb(n,".hvigor",".build-lock")}function Gb(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function mm(n){let e=Bb(yl(n));if(await Ub(e,{recursive:!0}),process.platform==="win32")try{await Vb("attrib",["+h",e])}catch{}}async function qb(n,e){let t=new AbortController,r=Gb(e);await mm(n);let i={lockfilePath:yl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await gl(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await gl(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Jr(n,e,t){let{release:r,signal:i}=await qb(n,t);try{return await e(i)}finally{await r()}}async function hs(n,e){let t=new AbortController;await mm(n);let r={lockfilePath:yl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await gl(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as hr from"fs";import*as Yr from"path";import zb from"json5";var Jb=1e3;function ys(n){p(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Yr.join(n,Ne.SYNC_OUTPUT_PATH);if(!hr.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return p(`[ProjectCheck] ${l.reason}`),l}let t=hr.statSync(e).mtimeMs;p(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Yb(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return p(`[ProjectCheck] ${l.reason}`),l}let i=Yr.join(n,Ne.OH_PACKAGE_JSON5),o=gs(i,t,"root");if(o.required)return p(`[ProjectCheck] Root check: ${o.reason}`),o;let s=Yr.join(n,Ne.BUILD_PROFILE_JSON5),a=gs(s,t,"build-profile");if(a.required)return p(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Yr.join(n,l.srcPath,Ne.OH_PACKAGE_JSON5),g=gs(d,t,l.name);if(g.required)return p(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let y=Yr.join(n,l.srcPath,Ne.BUILD_PROFILE_JSON5),I=gs(y,t,l.name);if(I.required)return p(`[ProjectCheck] Module '${l.name}' build-profile check: ${I.reason}`),I}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return p(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function gs(n,e,t){if(!hr.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=hr.statSync(n).mtimeMs;return r-e>Jb?{required:!0,reason:`${t}: source mtime (${new Date(r).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Yb(n){let e=Yr.join(n,Ne.BUILD_PROFILE_JSON5);try{let t=hr.readFileSync(e,"utf-8");if(!t.trim())return null;let r=zb.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as G from"fs";import*as J from"path";import*as fm from"util";var vl="";function ws(n){if(!n||n==="auto"||n==="stdout"||n==="none"){vl="";return}vl=n}function hm(){return vl||($p()??"")}function vs(n,...e){if(e.length===0)return n;try{return fm.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var u={info(n,...e){h.info(`[lsp] ${vs(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${vs(n,...e)}`)},error(n,...e){h.error(`[lsp] ${vs(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${vs(n,...e)}`)}};import*as _i from"fs";import*as Fi from"os";import*as Tn from"path";import Kb from"json5";var v={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},x="2.0",Rn={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate"};var gm=8192,wl=100,ym=.03,vm=.7,Ve=900*1e3;function rt(n){if(!_i.existsSync(n))return null;try{let e=_i.readFileSync(n,"utf-8");return e.trim()?Kb.parse(e):null}catch{return null}}function Ss(n,e){let t=Math.floor(Fi.totalmem()/1048576),r=Math.floor(t*vm),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=gm,n>wl&&(i+=(n-wl)*ym*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return u.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function St(n){if(n.startsWith("file:"))return n;try{let e=Tn.resolve(n),t=new URL(`file://${e}`).toString();if(Fi.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function xn(n){return n&&n.replace(/\\/g,"/")}function de(n){let e=Tn.normalize(n).replace(/\\/g,"/");if(Fi.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Kr(n){return n||process.execPath||"node"}function $i(n){let e=de(n.lspLogPath),t=["--expose-gc",`--max-old-space-size=${n.serverMaxSize}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${e}`,n.serverPath,n.transportFlag??"--stdio",`--logger-path=${e}`,"--logger-level=TRACE"];return n.projectPath&&t.push(`--projectPath=${de(n.projectPath)}`),n.sdkPath&&t.push(`--sdkPath=${de(n.sdkPath)}`),t}function wm(n){return Tn.join(n,"build-profile.json5")}var Vt=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=wm(this.projectRoot);try{let t=rt(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Xb}from"child_process";import*as Es from"fs";var Zb=600*1e3;function Qb(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function eE(n,e){let t=[],r=[],i="",o="";return n.stdout?.on("data",s=>{let a=s.toString();t.push(a),i=Sm(i+a,e)}),n.stderr?.on("data",s=>{let a=s.toString();r.push(a),o=Sm(o+a,c=>{u.info("[hvigor:err] %s",c),e?.(c)})}),{stdout:t,stderr:r,flush:()=>{i&&e?.(i),o&&(u.info("[hvigor:err] %s",o),e?.(o))}}}function Sm(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&e?.(i);return r}function bs(n){return n.join("")}function tE(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
20
|
+
${n.join(`
|
|
21
|
+
`)}`,a)}let o=tn(e),s=tn(i);return r.assertInsideRoot(s,o,"codelinter"),s}static isValidRoot(e,t){if(!r.isDirectory(e))return!1;if(t==="clt")return Oe.existsSync(I.join(e,"version.txt"));let n=nt.platform()==="darwin"?I.join(e,"Contents"):e,i=nt.platform()==="darwin"?I.join(n,"Info.plist"):I.join(n,"product-info.json");if(!Oe.existsSync(i))return!1;let o=r.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(Oe.existsSync)}static buildToolPaths(e,t){return t==="clt"?r.buildCltToolPaths(e):r.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=nt.platform()==="win32",n=t?".exe":"",i=I.join(e,"sdk");return{nodePath:t?I.join(e,"tool","node","node.exe"):I.join(e,"tool","node","bin","node"),ohpmJsPath:I.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:I.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:i,hdcPath:I.join(i,"default","openharmony","toolchains",`hdc${n}`),emulatorPath:I.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:r.clangdPathFor(i),arktsLangServerCandidates:[{root:I.join(e,"arkts-lsp","lib"),marker:I.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:r.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=nt.platform()==="darwin",n=nt.platform()==="win32",i=t?I.join(e,"Contents"):e,o=I.join(i,"tools"),s=I.join(i,"sdk"),a=n?".exe":"";return{nodePath:n?I.join(o,"node","node.exe"):I.join(o,"node","bin","node"),ohpmJsPath:I.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:I.join(o,"hvigor","bin","hvigorw.js"),javaPath:n?I.join(e,"jbr","bin","java.exe"):t?I.join(i,"jbr","Contents","Home","bin","java"):I.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:I.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:I.join(o,"emulator",n?"Emulator.exe":"Emulator"),clangdPath:r.clangdPathFor(s),arktsLangServerCandidates:r.studioArktsLangServerCandidates(e),codelinterCandidates:r.codelinterCandidatesFor(e,"studio")}}static codelinterCandidatesFor(e,t){if(t==="clt")return[I.join(e,"codelinter","index.js"),I.join(e,"codelinter","run","index.js"),I.join(e,"tool","codelinter","bin","codelinter.js"),I.join(e,"tool","codelinter","codelinter.js")];let n=nt.platform()==="darwin"?["Contents"]:[];return[I.join(e,...n,"plugins","codelinter","run","index.js"),I.join(e,...n,"plugins","codelinter","index.js"),I.join(e,...n,"tools","codelinter","bin","codelinter.js"),I.join(e,...n,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(nt.platform()==="linux")return[];let t=nt.platform()==="darwin"?["Contents"]:[],n=I.join(e,...t,"plugins","openharmony");return[{root:n,marker:I.join(n,"ace-server","out","index.js")}]}static clangdPathFor(e){return I.join(e,"default","openharmony","native","llvm","bin",nt.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return Oe.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return Oe.existsSync(e)&&Oe.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return r.installSourcePromise||(r.installSourcePromise=r.resolveInstallSourceUncached()),r.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[n,i,o]of e){let s=process.env[n]?.trim();if(s){let a=r.resolveExplicitRoot(s,i,n);return f(`[ToolProvider] Using ${n} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await rw();return f(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,n){let i;try{i=mc(e)}catch(o){throw new Error(`Invalid ${n}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&nt.platform()==="darwin"&&(i=r.normalizeMacStudioRoot(i)),r.isValidRoot(i,t)?i:r.throwInvalidSource(i,t,n,e)}static assertBuiltPathsInsideRoot(e,t,n){let i=tn(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];n&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)r.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,n){if(hy(e,t)===null)throw new Error(`Unsafe toolchain path: ${n} resolves outside the toolchain root`)}static throwInvalidSource(e,t,n,i){throw t==="clt"&&r.isValidRoot(e,"studio")?new Error(`${n} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&r.isValidRoot(e,"clt")?new Error(`${n} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${n}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${I.sep}Contents`,n=I.normalize(e);return n.endsWith(t)?n.slice(0,-t.length):n}static readCltVersion(e){try{return Oe.readFileSync(I.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(hx)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),i=[t&&(r.javaIn(I.join(t,"bin"))??r.javaIn(t)),...r.locateJavaFromPath()].filter(o=>!!o);if(!e)return i[0]?Oe.realpathSync(i[0]):"";for(let o of i)if(r.isUsableJava(o))return Oe.realpathSync(o);throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.")}static locateJavaFromPath(){let e=nt.platform()==="win32",t=e?"where.exe":"which",n=e?["java"]:["-a","java"];f(`Executing: ${t} ${n.join(" ")}`);let i=nw(t,n,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return i.error||i.status!==0?[]:i.stdout.split(/\r?\n/).map(o=>o.trim()).filter(Boolean)}static javaIn(e){return(nt.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(n=>I.join(e,n)).find(Oe.existsSync)}static isUsableJava(e){let t=["-version"];f(`Executing: ${e} ${t.join(" ")}`);let n=nw(e,t,{encoding:"utf8",stdio:"pipe",timeout:2e3,windowsHide:!0});return!n.error&&n.status===0}getMaxApiLevel(){for(let e of wx(this.sdkPath)){let t=yx(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=I.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(Oe.readFileSync(e,"utf8"))}catch(o){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:o})}let n=t.data?.platformVersion,i=typeof n=="string"?n.trim():"";if(!i)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return i}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=nt.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",n=I.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=I.join(n,"resources","apiChange"),o=I.join(n,"api-change-scan.js");if(!Oe.existsSync(i)||!Oe.existsSync(o)){let s=an(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${gx}. Upgrade before using 'check compat' at ${yp}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as Nx}from"execa";import*as dw from"net";import*as cn from"path";import*as Nc from"fs";import*as _c from"os";import{execFile as Hp,spawn as iw}from"child_process";import{existsSync as vx,readdirSync as bx,readFileSync as Sx}from"fs";var Tc="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",$p,jp="---MEMORY-SAMPLE-DELIMITER---";function sw(){return $p===void 0&&($p=vx(Tc)),$p}function mt(r){return new Promise(e=>{let t=process.platform==="win32",n=t?"tasklist":"ps",i=t?["/fi",`PID eq ${r}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(r)];f(`Executing: ${n} ${i.join(" ")}`),Hp(n,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?Tx(s):Ax(s))})})}async function Ex(){return process.platform==="linux"?Ac():process.platform==="darwin"?Px():process.platform==="win32"?Cx():[]}function Ac(){let r=[],e;try{e=bx("/proc")}catch{return r}for(let t of e){if(!/^\d+$/.test(t))continue;let n=Number(t);try{let i=Sx(`/proc/${n}/status`,"utf8"),o=i.match(/VmRSS:\s+(\d+)\s+kB/),s=i.match(/^PPid:\s+(\d+)/m);if(!o||!s)continue;r.push({pid:n,ppid:Number(s[1]),rssBytes:Number(o[1])*1024})}catch{}}return r}function Px(){return new Promise(r=>{Hp("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){r([]);return}r(aw(t))})})}function aw(r){let e=[];for(let t of r.trim().split(`
|
|
22
|
+
`)){let n=t.trim().split(/\s+/);if(n.length<3)continue;let i=Number(n[0]),o=Number(n[1]),s=Number(n[2]);isNaN(i)||isNaN(o)||isNaN(s)||e.push({pid:i,ppid:o,rssBytes:s*1024})}return e}function Cx(){return new Promise(r=>{if(!sw()){r([]);return}Hp(Tc,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,n)=>{if(t){r([]);return}r(cw(n))})})}function cw(r){let e=[];for(let t of r.trim().split(`
|
|
23
|
+
`)){let n=t.trim();if(!n)continue;let i=n.split(",");if(i.length<3)continue;let o=Number(i[0]),s=Number(i[1]),a=Number(i[2]);isNaN(o)||isNaN(s)||isNaN(a)||e.push({pid:o,ppid:s,rssBytes:a})}return e}function lw(r,e){let t=new Map,n=new Map;for(let a of r){t.set(a.pid,a.rssBytes);let c=n.get(a.ppid);c?c.push(a.pid):n.set(a.ppid,[a.pid])}let i=0,o=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(o.has(a))continue;o.add(a),i+=t.get(a)??0;let c=n.get(a);c&&s.push(...c)}return i}async function kx(r){let e=await Ex();return lw(e,r)}function Rx(r){if(process.platform==="darwin"){let e=(r/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${jp}'; sleep ${e}; done`;return f(`Executing: sh -c ${t}`),iw("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&sw()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${jp}'; Start-Sleep -Milliseconds ${r} }`;return f(`Executing: ${Tc} -NoProfile -Command ${e}`),iw(Tc,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function ae(r){return`${(r/1024/1024).toFixed(2)}MB`}async function ow(r,e){if(!r)return process.memoryUsage().rss;if(e)return kx(r);let t=await mt(r);return t?Number(t)*1024:0}function zi(r,e=2e3,t=!1){let n=0,i=!1,o=a=>{if(i||!r)return;let c=t?lw(a,r):a.find(l=>l.pid===r)?.rssBytes??0;c>n&&(n=c)};if(!r)return xx(e);if(process.platform==="linux")return Ix(e,o,()=>n);let s=Rx(e);return s?(Dx(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await ow(r,t);return Math.max(n,a)}}):{stop:async()=>{i=!0;let a=await ow(r,t);return Math.max(n,a)}}}function Dx(r,e){let t=process.platform==="darwin"?aw:cw,n="";r.stdout?.on("data",i=>{n+=i.toString();let o=n.split(jp);n=o.pop()??"";for(let s of o)e(t(s))}),r.on("error",()=>{})}function xx(r){let e=process.memoryUsage().rss,t=setInterval(()=>{let n=process.memoryUsage().rss;n>e&&(e=n)},r);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function Ix(r,e,t){e(Ac());let n=setInterval(()=>e(Ac()),r);return{stop:async()=>(clearInterval(n),e(Ac()),t())}}function Ax(r){let e=r.trim().match(/^(\d+)$/);return e?e[1]:null}function Tx(r){let e=r.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Mc="module",ht=class{toolProvider;projectRoot;env;silent;constructor(e,t,n=!1){this.toolProvider=e,this.projectRoot=t,this.silent=n;let i=cn.dirname(e.javaPath),o=`${i}${cn.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath},a=_c.platform()==="darwin"&&e.javaPath==="/usr/bin/java";e.sourceType==="clt"&&e.javaPath&&!a&&(s.JAVA_HOME=cn.dirname(i)),this.env=s}async sync(e,t){let n=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(n)}async buildProduct(e,t){let n=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(n)}async buildModules(e,t,n,i){let o=[...Array.from(i),"--mode","module","-p",`module=${n.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`];return this.runHvigor(o)}async clean(e,t){let n=["clean","--mode",e??Mc];return t&&t.length>0&&n.push("-p",`module=${t.join(",")}`),this.runHvigor(n)}async stopDaemon(){return this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){f("[HvigorAdapter] Daemon already running.");return}f("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}async isDaemonAlive(e){let t=this.findProjectDaemon(e);return t?this.isPortListening(t.port):!1}isPortListening(e){return new Promise(t=>{let n=new dw.Socket;n.setTimeout(2e3),n.once("connect",()=>{n.destroy(),t(!0)}),n.once("error",()=>t(!1)),n.once("timeout",()=>{n.destroy(),t(!1)}),n.connect(e,"127.0.0.1")})}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!Nc.existsSync(t))return null;try{let n=Nc.readFileSync(t,"utf-8"),i=JSON.parse(n),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||cn.join(_c.homedir(),".hvigor");return cn.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let n=["--mode","module"];return t&&n.push("-p",`module=${t}`),n.push("-p",`product=${e}`,"compileNative"),this.runHvigor(n)}async runHvigor(e){let t=this.toolProvider.nodePath,n=[this.toolProvider.hvigorJsPath,...e];f(`Executing: ${t} ${n.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=Nx(t,n,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=Ze()?void 0:zi(o.pid,2e3,!0),a="";try{await o}finally{if(s){let c=await s.stop();c>0&&(a=ae(c),f(`Hvigor peak memory: ${a}`))}}return a}};import{execa as _x}from"execa";var Ji=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async install(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install"];f(`Executing: ${e} ${t.join(" ")}`);let n=_x(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Ze()?void 0:zi(n.pid,2e3,!1);try{await n}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=ae(o))}}}};import{mkdir as Mx}from"fs/promises";import{dirname as Ox,resolve as Lx}from"path";import{execa as Fx}from"execa";import{lock as Up,check as pK}from"proper-lockfile";function Bp(r){return Lx(r,".hvigor",".build-lock")}function $x(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function uw(r){let e=Ox(Bp(r));if(await Mx(e,{recursive:!0}),process.platform==="win32")try{await Fx("attrib",["+h",e])}catch{}}async function jx(r,e){let t=new AbortController,n=$x(e);await uw(r);let i={lockfilePath:Bp(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Up(r,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return n(),{release:await Up(r,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function xr(r,e,t){let{release:n,signal:i}=await jx(r,t);try{return await e(i)}finally{await n()}}async function Oc(r,e){let t=new AbortController;await uw(r);let n={lockfilePath:Bp(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Up(r,{...n,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import ws from"fs";import*as q from"path";import pw from"fs";import*as fw from"path";import Hx from"json5";function Ux(r,e){try{let n=Hx.parse(pw.readFileSync(r,"utf-8")).modules?.find(i=>i.name===e);return n?.srcPath?n.srcPath.replace(/^\.\//,""):null}catch(t){return f(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function Ht(r,e){let t=fw.join(r,"build-profile.json5");return pw.existsSync(t)?Ux(t,e)??e:e}var lr=class r{static generate(e,t,n,i){let o=Ht(e,t),s=q.join(e,o),a=q.join(s,"build","config"),c=r.buildConfig(e,s,n,i);ws.mkdirSync(a,{recursive:!0}),ws.writeFileSync(q.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=q.join(s,"build",n,"intermediates","loader_out",n,"ets");ws.mkdirSync(l,{recursive:!0})}static remove(e,t){let n=Ht(e,t),i=q.join(e,n,"build","config","buildConfig.json");ws.existsSync(i)&&(ws.unlinkSync(i),f(`[BuildConfigManager] buildConfig.json removed: ${i}`))}static removeAll(e){for(let t of e.profile.modules)r.remove(e.rootDir,t.name)}static async withBuildConfig(e,t,n,i,o){for(let s of t)r.generate(e,s,n,i);try{return await o()}finally{for(let s of t)r.remove(e,s)}}static buildConfig(e,t,n,i){let o=q.dirname(i.nodePath)+q.sep,s=q.join(t,"build",n),a=q.join(s,"intermediates"),c=q.join(a,"loader_out",n),l=q.join(a,"res",n);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:q.join(e,"build-profile.json5"),localPropertiesPath:q.join(e,"local.properties"),appResource:q.join(l,"ResourceTable.txt"),cachePath:q.join(s,"cache",n,`${n}@CompileArkTS`,"esmodule","debug"),aceBuildJson:q.join(a,"loader",n,"loader.json"),aceModuleJsonPath:q.join(l,"module.json"),aceSoPath:q.join(c,"nativeDependencies.txt"),aceModuleRoot:q.join(t,"src","main","ets"),aceModuleBuild:q.join(c,"ets"),aceProfilePath:q.join(l,"resources","base","profile"),aceSuperVisualPath:q.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:q.join(c,"ets"),changedFileList:q.join(a,"patch",n,"changedFileList.json"),patchAbcPath:q.join(a,"patch",n,"ets"),removeChangedFileListInSdk:"true"}}}};import*as Ir from"fs";import*as dr from"path";import Bx from"json5";var Wx=1e3;function Ki(r,e,t){let n=Vx(r,e,t);return n.required?(f(`[ProjectCheck] ${t} check: ${n.reason}`),n):null}function Lc(r){f(`[ProjectCheck] Checking sync required at project root: ${r}`);let e=dr.join(r,Ce.SYNC_OUTPUT_PATH);if(!Ir.existsSync(e)){let a={required:!0,reason:`sync baseline file not found: ${e}`};return f(`[ProjectCheck] ${a.reason}`),a}let t=Ir.statSync(e).mtimeMs,n=dr.join(r,Ce.LOCK_JSON5_PATH);if(!Ir.existsSync(n)){let a={required:!0,reason:`oh_modules lock not found: ${n}`};return f(`[ProjectCheck] ${a.reason}`),a}let i=Gx(r);if(i===null)return{required:!0,reason:"failed to parse build-profile.json5"};let o=Ki(dr.join(r,Ce.OH_PACKAGE_JSON5),t,"root");if(o||(o=Ki(dr.join(r,Ce.BUILD_PROFILE_JSON5),t,"build-profile"),o)||(o=Ki(dr.join(r,Ce.HVIGOR_CONFIG),t,"hvigor-config"),o)||(o=Ki(dr.join(r,Ce.HVIGOR_CONFIG),t,"hvigor-config"),o))return o;for(let a of i)if(o=Ki(dr.join(r,a.srcPath,Ce.OH_PACKAGE_JSON5),t,a.name),o||(o=Ki(dr.join(r,a.srcPath,Ce.BUILD_PROFILE_JSON5),t,a.name),o))return o;let s=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return f(`[ProjectCheck] ${s}`),{required:!1,reason:s}}function Vx(r,e,t){if(!Ir.existsSync(r))return{required:!1,reason:`${t}: source not found, skip`};let n=Ir.statSync(r).mtimeMs;return n-e>Wx?{required:!0,reason:`${t}: source mtime (${new Date(n).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Gx(r){let e=dr.join(r,Ce.BUILD_PROFILE_JSON5);try{let t=Ir.readFileSync(e,"utf-8");if(!t.trim())return null;let n=Bx.parse(t);if(typeof n!="object"||n===null)return null;let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Q from"fs";import*as z from"path";import*as mw from"util";var Wp="";function $c(r){if(!r||r==="auto"||r==="stdout"||r==="none"){Wp="";return}Wp=r}function hw(){return Wp||(Xg()??"")}function Fc(r,...e){if(e.length===0)return r;try{return mw.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var m={info(r,...e){g.info(`[lsp] ${Fc(r,...e)}`)},warn(r,...e){g.warn(`[lsp] ${Fc(r,...e)}`)},error(r,...e){g.error(`[lsp] ${Fc(r,...e)}`)},debug(r,...e){g.debug(`[lsp] ${Fc(r,...e)}`)}};import*as vs from"fs";import*as bs from"os";import*as Xi from"path";import qx from"json5";var b={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},L="2.0",Yi={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate"};var gw=8192,Vp=100,yw=.03,ww=.7,it=900*1e3;function gt(r){if(!vs.existsSync(r))return null;try{let e=vs.readFileSync(r,"utf-8");return e.trim()?qx.parse(e):null}catch{return null}}function jc(r,e){let t=Math.floor(bs.totalmem()/1048576),n=Math.floor(t*ww),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=gw,r>Vp&&(i+=(r-Vp)*yw*1024),o=`formula(moduleCount=${r})`);let s=n>0&&i>n;s&&(i=n);let a=Math.round(i);return m.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${n}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Ut(r){if(r.startsWith("file:"))return r;try{let e=Xi.resolve(r),t=new URL(`file://${e}`).toString();if(bs.platform()==="win32"){let n=t.match(/^file:\/\/\/([A-Za-z]):/);if(n){let i=n[1].toUpperCase(),o=t.substring(`file:///${n[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return r}}function Zi(r){return r&&r.replace(/\\/g,"/")}function ge(r){let e=Xi.normalize(r).replace(/\\/g,"/");if(bs.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Zn(r){return r||process.execPath||"node"}function Ss(r){let e=ge(r.lspLogPath),t=["--expose-gc",`--max-old-space-size=${r.serverMaxSize}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${e}`,r.serverPath,r.transportFlag??"--stdio",`--logger-path=${e}`,"--logger-level=TRACE"];return r.projectPath&&t.push(`--projectPath=${ge(r.projectPath)}`),r.sdkPath&&t.push(`--sdkPath=${ge(r.sdkPath)}`),t}function vw(r){return Xi.join(r,"build-profile.json5")}var Ar=class{constructor(e){this.projectRoot=e}getAllModuleInfo(){let e=vw(this.projectRoot);try{let t=gt(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return m.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as zx}from"child_process";import*as Uc from"fs";var Jx=600*1e3;function Kx(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function Yx(r,e){let t=[],n=[],i="",o="";return r.stdout?.on("data",s=>{let a=s.toString();t.push(a),i=bw(i+a,e)}),r.stderr?.on("data",s=>{let a=s.toString();n.push(a),o=bw(o+a,c=>{m.info("[hvigor:err] %s",c),e?.(c)})}),{stdout:t,stderr:n,flush:()=>{i&&e?.(i),o&&(m.info("[hvigor:err] %s",o),e?.(o))}}}function bw(r,e){let t=r.split(/\r?\n/),n=t.pop()??"";for(let i of t)i&&e?.(i);return n}function Hc(r){return r.join("")}function Xx(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
21
24
|
Output so far:
|
|
22
|
-
`+t,exitCode:-1};let r
|
|
25
|
+
`+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function Zx(r,e,t,n){return new Promise(i=>{let o=zx(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:s,stderr:a,flush:c}=Yx(o,n),l=setTimeout(()=>{o.kill(),c();let d=[Hc(s),Hc(a)].filter(Boolean).join(`
|
|
23
26
|
`).trim();i({success:!1,output:`Build process timeout after 10 minutes.
|
|
24
27
|
Output so far:
|
|
25
|
-
`+d,exitCode:-1})},
|
|
26
|
-
`).trim()||"";i(
|
|
27
|
-
[ohpm install]
|
|
28
|
-
[hvigor sync]
|
|
29
|
-
[
|
|
30
|
-
[hvigor
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
[
|
|
35
|
-
|
|
36
|
-
`+
|
|
28
|
+
`+d,exitCode:-1})},Jx);o.on("close",(d,h)=>{clearTimeout(l),c();let y=[Hc(s),Hc(a)].filter(Boolean).join(`
|
|
29
|
+
`).trim()||"";i(Xx(d,h,y))}),o.on("error",d=>{clearTimeout(l),i({success:!1,output:`Build execution exception: ${d.message}`,exitCode:-1})})})}async function Gp(r,e,t,n,i,o){let s={...process.env,DEVECO_SDK_HOME:n},a=Kx(e,t,i);return await Zx(a,r,s,o)}function Qx(r,e,t){return{node_path:e,hvigor_path:t,sdk_path:r}}function eI(r){return!r.node_path||!Uc.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!Uc.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!Uc.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var tI="--sync -p product=default";async function Sw(r,e,t,n,i){try{let o=Qx(e,t,n),s=eI(o);if(s!=null)return m.info(`Config validation failed: ${s}`),!1;let a=await Gp(r,o.node_path,o.hvigor_path,e,tI,i);return m.info(`[hvigor] sync finished: success=${a.success}, exitCode=${a.exitCode}`),a.success}catch(o){return m.info(`syncProject failed: ${JSON.stringify(o)}`),!1}}function rI(r){let e=z.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function nI(r,e){let t=z.join(r,e.name);return e.isDirectory()?e.name===".cxx"||Pw(t):rI(t)}function Pw(r){if(!Q.existsSync(r))return!1;try{return Q.readdirSync(r,{withFileTypes:!0}).some(t=>nI(r,t))}catch{}return!1}function ln(r){try{let t=new Ar(r).getAllModuleInfo(),n=[];for(let i of t){let o=z.resolve(r,i.srcPath);Pw(o)&&n.push(i)}return n}catch(e){throw g.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function iI(r){let e=[],n=new Ar(r).getAllModuleInfo();for(let i of n){let o=z.resolve(r,i.srcPath),s=z.join(o,".cxx");Q.existsSync(s)&&Cw(s,e)}return e}function Cw(r,e){try{let t=Q.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=z.join(r,n.name);n.isDirectory()?Cw(i,e):n.name==="compile_commands.json"&&e.push(i)}}catch{}}function oI(r){let e=[];for(let t of r)try{let n=Q.readFileSync(t,"utf8"),i=JSON.parse(n);e.push(...i)}catch{}return e}function sI(r,e){let t=z.join(r,...aI.slice(0,-1));Q.mkdirSync(t,{recursive:!0});let n=z.join(t,"compile_commands.json");Q.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function qp(r){let e=iI(r);if(e.length>0){let t=oI(e);sI(r,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}var aI=[".idea",".deveco","cxx","compile_commands.json"];async function cI(r,e,t,n,i){if(!n){g.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}g.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${n}`);for(let o of i){let s=o.name;try{E.assertModuleName(s)}catch{g.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${o.name}`,"-p","product=default","compileNative"].join(" ");g.info(`[CppCompile] Running compileNative for module: ${o.name}`);let c=await Gp(r,t,n,e,a);c.success?g.info(`[CppCompile] compileNative ${o.name} succeeded`):g.warn(`[CppCompile] compileNative ${o.name} failed: ${c.output}`)}}async function kw(r,e,t,n){let i=ln(r);if(i.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${i.length} C++ module(s): ${i.map(o=>o.name).join(", ")}`),await cI(r,e,t,n,i),qp(r),hI(r,i)}function Bc(r,e){let t=r?.trim()??"";if(!t)return null;let n=t;if(/\{workspace\}/i.test(n)){if(!e)return g.warn("[CppCompile] {workspace} placeholder in compile_commands path but no project root resolved, falling back to default sync"),null;n=n.replace(/\{workspace\}/gi,e)}else if(!z.isAbsolute(n)){if(!e)return g.warn(`[CppCompile] Relative compile_commands path '${n}' requires a project root, falling back to default sync`),null;n=z.join(e,n)}let i=z.resolve(n);try{if(!Q.existsSync(i)||!Q.statSync(i).isFile())return g.warn(`[CppCompile] Custom compile_commands.json not found: ${i}, falling back to default sync`),null;let o=JSON.parse(Q.readFileSync(i,"utf8"));if(!Array.isArray(o))return g.warn(`[CppCompile] Custom compile_commands.json is not a JSON array: ${i}, falling back to default sync`),null}catch(o){return g.warn(`[CppCompile] Failed to read custom compile_commands.json (${i}): ${o}, falling back to default sync`),null}return z.dirname(i)}var lI=1e3,dI=["src","main","cpp","CMakeLists.txt"],uI=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),pI=new Set(["c","cpp","cxx","cc"]),fI="cpp-source-manifest.json";function mI(r){let e=z.extname(r).replace(/^\./,"").toLowerCase();return pI.has(e)}function Ew(r,e){return Q.existsSync(r)?Q.statSync(r).mtimeMs-e>lI:!1}function Rw(r){return z.join(z.dirname(Gn(r)),fI)}function Dw(r,e,t){let n;try{n=Q.readdirSync(r,{withFileTypes:!0})}catch{return}for(let i of n){let o=z.join(r,i.name);if(i.isDirectory()){if(uI.has(i.name))continue;Dw(o,e,t)}else mI(i.name)&&t.push(z.relative(e,o).replace(/\\/g,"/"))}}function xw(r,e){let t=[];for(let n of e){let i=z.resolve(r,n.srcPath);Dw(i,r,t)}return t.sort()}function hI(r,e){let t=xw(r,e),n={files:t,updatedAt:Date.now()},i=Rw(r);try{Q.mkdirSync(z.dirname(i),{recursive:!0}),Q.writeFileSync(i,JSON.stringify(n,null,2),"utf8"),g.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(o){g.warn(`[CppCompile] Failed to write C++ source manifest: ${o}`)}}function gI(r,e){let t=Rw(r);if(!Q.existsSync(t))return{required:!0,reason:"C++ source manifest not found, needs initialization"};let n;try{let o=JSON.parse(Q.readFileSync(t,"utf8"));n=Array.isArray(o.files)?o.files:[]}catch{return{required:!0,reason:"C++ source manifest corrupted, needs initialization"}}let i=xw(r,e);return i.length!==n.length||i.some((o,s)=>o!==n[s])?{required:!0,reason:`C++ source file set changed (recorded=${n.length}, actual=${i.length})`}:null}function Iw(r){let e=Gn(r);if(!Q.existsSync(e))return{required:!0,reason:"C++ baseline (compile_commands.json) not found, needs initialization"};let t=Q.statSync(e).mtimeMs,n=ln(r);if(n.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let o of n){let s=z.resolve(r,o.srcPath);if(Ew(z.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${o.name}': build-profile.json5 newer than baseline`};let a=z.join(s,...dI);if(Ew(a,t))return{required:!0,reason:`module '${o.name}': CMakeLists.txt newer than baseline`}}let i=gI(r,n);return i||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}var Tw=["assembleHap","assembleApp","assembleHsp","assembleHar"];function wI(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode){let t=["debug","release"],n=(r.profile.app.buildModeSet?.map(o=>o.name)??[]).filter(o=>!t.includes(o)),i=[...t,...n];if(!i.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${i.join(", ")}`)}if(e.assembleType&&!Tw.includes(e.assembleType))throw new Error(`Invalid assemble type '${e.assembleType}'. Valid types: ${Tw.join(", ")}`);if(e.signingConfig){if(!/^[\da-zA-Z_-]+$/.test(e.signingConfig))throw new Error(`Invalid signing config name '${e.signingConfig}'. Only letters, digits, hyphens and underscores are allowed.`);let t=r.profile.app.signingConfigs?.map(n=>n.name)??[];if(!t.includes(e.signingConfig)){let n=t.length>0?`Available configs: ${t.join(", ")}.`:"No signing configs found in build-profile.json5.",i=e.signingConfig.endsWith("_release")?"Run `devecocli signature generate --type release` to generate release signing materials.":"Run `devecocli signature generate` to generate signing materials.";throw new Error(`Signing config '${e.signingConfig}' not found in build-profile.json5. ${n} ${i}`)}}}function Mw(r,e){let t=r.profile.modules.map(i=>i.name),n=new Set(t);for(let i of e){let o=i.split("@",1)[0];if(!n.has(o))throw new Error(`Module '${o}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function vI(r,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,Mw(r,t);else{let i=r.profile.modules,o=i.filter(s=>r.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new w(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new w(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let n=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";n.add(`${s}@${a}`)}return Array.from(n)}function zp(r,e,t){let n=new Set;for(let i of e){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i;if(t){let a=r.getModuleType(s),c=a==="shared"?"assembleHsp":a==="har"?"assembleHar":"assembleHap";t!==c&&t!=="assembleApp"&&console.warn(Gc(`Warning: --assemble-type ${t} may not be compatible with module '${s}' (type: ${a}, expected: ${c}).`)),n.add(t)}else{let a=r.getModuleType(s);a==="shared"?n.add("assembleHsp"):a==="har"?n.add("assembleHar"):n.add("assembleHap")}}return n}function Wc(r,e){let t=e,n=`${r} failed`;console.error(Nw(n));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(n,{cause:e})}async function bI(r,e,t,n,i){if(!Lc(i).required)return console.log(`
|
|
30
|
+
[ohpm install] Skipped (configurations unchanged)`),console.log(`
|
|
31
|
+
[hvigor sync] Skipped (configurations unchanged)`),"";console.log(`
|
|
32
|
+
[ohpm install] Running...`);try{await r.install()}catch(s){Wc("ohpm install",s)}console.log(`
|
|
33
|
+
[hvigor sync] Running...`);try{return await e.sync(t,n)}catch(s){Wc("hvigor sync",s)}return""}async function Jp(r,e,t,n,i,o){let s=await bI(r,e,t,n,o);console.log(`
|
|
34
|
+
[hvigor build] Running...`);let a="";try{i.type==="product"?a=await e.buildProduct(t,n):a=await e.buildModules(t,n,i.modulesToBuild,i.moduleTasks)}catch(c){Wc("hvigor build",c)}return SI(o),{ohpmMemoryMb:r.peakMemoryMb,syncMemoryMb:s,buildMemoryMb:a}}function SI(r){try{if(ln(r).length===0)return;qp(r),console.log(Vc(`
|
|
35
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(Gc(`
|
|
36
|
+
Failed to merge compile_commands.json: ${e.message}`))}}async function Ow(r,e){let t=Date.now(),n=!0,i=null;try{await e()}catch(o){n=!1,i=Z(o),console.error(Nw(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(r,o)}}function EI(r){let e={event:v.CommandExecuted,args:["build",...r.product?["--product"]:[],...r.modules?["--modules"]:[],...r.buildMode?["--build-mode"]:[],...r.assembleType?["--assemble-type"]:[],...r.signingConfig?["--signing-config"]:[]]};return r.buildMode&&(e.build_mode=r.buildMode),r.modules&&(e.module_count=r.modules.length),r.assembleType&&(e.assemble_type=r.assembleType),r.signingConfig&&(e.signing_config=r.signingConfig),e}function PI(r){let e={event:v.CommandExecuted,args:["build","clean",...r.mode?["--mode"]:[],...r.modules?["--modules"]:[]]};return r.modules&&(e.module_count=r.modules.length),r.mode&&(e.clean_mode=r.mode),e}async function CI(r){let e=W.discover(process.cwd());await rt.warnInvalidBundledLinks(e.rootDir),console.warn(Gc("Ensure the project source is trustworthy before proceeding."));let t=await P.new();t.assertJava(),wI(e,r);let n=r.product||"default",i=r.buildMode||"debug",o=kI(e,r),s=new Ji(t,e.rootDir),a=new ht(t,e.rootDir),c=r.signingConfig?RI(e.rootDir,n,r.signingConfig):void 0;try{let l=await xr(e.rootDir,async()=>(lr.removeAll(e),Jp(s,a,n,i,o,e.rootDir)),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
|
|
37
|
+
`+Vc("Build completed successfully")),DI(e,o,n),{bundleName:e.getBundleName(),...l}}finally{c?.()}}function kI(r,e){if(e.assembleType==="assembleApp"||e.product&&!e.modules&&!e.assembleType)return{type:"product"};let t=vI(r,e),n=zp(r,t,e.assembleType);return{type:"modules",modulesToBuild:t,moduleTasks:n}}function RI(r,e,t){let n=_w.join(r,"build-profile.json5"),i=Es.readFileSync(n,"utf-8"),o=Aw.parse(i),s=o?.app?.products??[],a=s.findIndex(c=>c.name===e);return a>=0?s[a].signingConfig=t:s.push({name:e,signingConfig:t}),f(`[build] temporarily setting product '${e}' signingConfig to '${t}'`),Es.writeFileSync(n,Aw.stringify(o,null,2),"utf-8"),()=>{Es.writeFileSync(n,i,"utf-8"),f("[build] restored original build-profile.json5")}}function DI(r,e,t){let n=e.type==="product"?r.resolveModuleSpecsForProduct(t):e.modulesToBuild,i=r.collectBuildArtifacts(e.type==="product",n,t);if(i.length!==0){console.log(Vc("Build artifacts:"));for(let o of i)console.log(` ${o}`)}}async function xI(r){let e=process.cwd(),t=W.discover(e);await rt.warnInvalidBundledLinks(t.rootDir),console.warn(Gc("Ensure the project source is trusted before proceeding."));let n=await P.new();n.assertJava();let i;r.modules&&r.modules.length>0&&(Mw(t,r.modules),i=r.modules.map(s=>s.split("@",1)[0]));let o=new ht(n,t.rootDir);return await xr(t.rootDir,async()=>{let s=i&&i.length>0?`mode=${r.mode??Mc}, modules=${i.join(",")}`:`mode=${r.mode??Mc}`;console.log(`
|
|
38
|
+
Running hvigor clean (${s})...`);try{await o.clean(r.mode,i)}catch(a){Wc("hvigor clean",a)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
39
|
+
`+Vc("Clean completed successfully.")),t.getBundleName()}var Lw=new yI("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").option("--assemble-type <type>","Assemble task type: assembleHap, assembleApp, assembleHsp, assembleHar (default: auto-detect by module type)").option("--signing-config <name>","Signing config name defined in build-profile.json5 (overrides product default)").action(async r=>{let e=EI(r);await Ow(e,async()=>{let t=await CI(r);e.bundle_name=t.bundleName,t.ohpmMemoryMb&&(e.ohpm_install_memory=t.ohpmMemoryMb),t.syncMemoryMb&&(e.hvigor_sync_memory=t.syncMemoryMb),t.buildMemoryMb&&(e.hvigor_build_memory=t.buildMemoryMb)})});Lw.command("clean").description("Clean HarmonyOS project build outputs").option("--mode <mode>","hvigor --mode value (default: module)").option("--modules <modules...>","Scope clean to specific modules").action(async(r,e)=>{let t=e.parent?.opts()??{},n={mode:r.mode,modules:r.modules??t.modules},i=PI(n);await Ow(i,async()=>{i.bundle_name=await xI(n)})});var Fw=Lw;import{Command as XT}from"commander";import{green as Ls,red as ZT,yellow as Sl}from"colorette";import*as Fs from"path";import{randomUUID as BI}from"crypto";import{execa as Gw}from"execa";import{execa as UI}from"execa";import{execFile as II,spawn as AI}from"child_process";import{promisify as TI}from"util";var NI=TI(II);function $w(r,e,t){let i=r.replace(/\r\n/g,`
|
|
37
40
|
`).split(`
|
|
38
|
-
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function
|
|
39
|
-
`)){let i=
|
|
41
|
+
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function jw(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function _I(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??-1}}function MI(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function OI(r,e,t,n,i){r.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=$w(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=$w(e.stderrLineBuffer+s,"stderr",t)}),r.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),r.on("close",o=>{if(e.settled)return;e.settled=!0,jw(e.stdoutLineBuffer,"stdout",t),jw(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=_I(e,o);n(s)})}async function Ps(r,e=[],t={}){try{let{stdout:n,stderr:i}=await NI(r,e,t);return{stdout:typeof n=="string"?n.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(n){let i=n;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()??i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function Hw(r,e,t){return await new Promise((n,i)=>{let o=AI(r,e,{stdio:["inherit","pipe","pipe"]}),s=MI();OI(o,s,t,n,i)})}function Uw(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var LI=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],FI=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Bt(r){return r?LI.some(e=>e.test(r))?"transient":FI.some(e=>e.test(r))?"fatal":"ok":"ok"}var $I=/(?:^|\s)(\d{2,})(?:\s|$)/;function Bw(r){let e=r.stdout.trim(),t=r.stderr.trim();return Bt(e)!=="ok"||Bt(t)!=="ok"?"query-failed":r.exitCode===0?e&&$I.test(e)?"alive":"dead":r.exitCode===1&&!e&&!t?"dead":"query-failed"}var Kp=[800,1500,2500];function jI(r){return new Promise(e=>setTimeout(e,r))}async function C(r,e){let t=1+Kp.length,n={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(n=await Ps(r,e),n.exitCode===0||Bt(n.stderr)!=="transient"||i>=t-1)return n;f(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Kp[i]}ms`),await jI(Kp[i])}return n}var Ww=/^[\w.-]+$/;async function qc(r,e,t){if(!Ww.test(t)){f(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let n=["-t",e,"shell","param","get",t];f(`Executing: ${r} ${n.join(" ")}`);let i=await C(r,n);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Bt(o)!=="ok"))return Uw(o)}var Yp="__DEVECO_PARAM_DELIM__";function HI(r,e){let t=new Map,n=r.split(Yp);for(let i=0;i<e.length;i++){let o=(n[i]??"").trim();if(!o||Bt(o)!=="ok")continue;let s=Uw(o);s&&t.set(e[i],s)}return t}async function Qi(r,e,t){let n=t.filter(a=>Ww.test(a)?!0:(f(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(n.length===0)return new Map;if(n.length===1){let a=new Map,c=await qc(r,e,n[0]);return c&&a.set(n[0],c),a}let i=n.map(a=>`param get ${a}`).join(`; echo ${Yp}; `)+`; echo ${Yp}`,o=await C(r,["-t",e,"shell",i]);if(o.exitCode===0){let a=HI(o.stdout,n);if(a.size>0)return a}f(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of n){let c=await qc(r,e,a);c&&s.set(a,c)}return s}function ur(r){return r.startsWith("127.0.0.1:")}var Vw=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ce=class r{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new r(e.hdcPath)}static withHdcPath(e){return new r(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let n=e.trim(),i=t?.trim();if(!n||!i)return n;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return n.replace(o,"").trim()||n}async executeHdc(e){return f(`Executing: ${this.hdcPath} ${e.join(" ")}`),UI(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
|
|
42
|
+
`)){let i=n.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){f(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Qi(this.hdcPath,e,[...Vw]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let n=e.find(s=>s.serial===t);if(n)return n;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new w(`Multiple devices match "${t}". Use a serial instead:
|
|
40
43
|
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
41
|
-
`),"Multiple devices match."):new S(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Nn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Ot(e),r,i;try{let o=await Nn(this.hdcPath,e,[...Hm]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Le=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=oe.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;p(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Um(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){E.assertBundleNameStrict(t);let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${WE()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){E.assertBundleNameStrict(t),E.assertAbilityName(r);let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async pidofBundle(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","pidof",t],i=this.toolProvider.hdcPath;p(`Executing: ${i} ${r.join(" ")}`);let o=await ie(i,r),s=$m(o);if(s==="query-failed"){let a=[o.stdout,o.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${o.exitCode}`}`)}return s==="alive"}async forceStopApp(e,t){E.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}async transferFile(e,t,r,i){let o=["-t",e,"file",t,r,i],s=await this.runHdc(o,!1);if(!s.includes("FileTransfer finish"))throw new Error(`File ${t} failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async runSqlite3(e,t,r=[]){let i=["-t",e,"shell","sqlite3",t,...r];await Um(this.toolProvider.hdcPath,i,{stdio:"inherit",env:{...process.env}})}};import Dl from"fs";import*as Xr from"path";function Ui(n,e){if(!Dl.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Dl.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Xr.resolve(e),o=new Set,s=[];for(let a of r){let c=Xr.resolve(i,a),l=Xr.isAbsolute(a)?Xr.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,i);if(!d.contained){if(!Dl.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Rl from"fs";import Bi from"path";import{execa as qE}from"execa";import Bm from"fs";import*as Wm from"path";import VE from"json5";function GE(n,e){try{let r=VE.parse(Bm.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return p(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function _t(n,e){let t=Wm.join(n,"build-profile.json5");return Bm.existsSync(t)?GE(t,e)??e:e}async function Vm(n,e,t,r){let i=Bi.dirname(n.javaPath),o={...process.env,PATH:`${i}${Bi.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];p(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await qE(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>JE(e,l,r))}function Gm(n,e,t){let r=_t(n,e);return Bi.join(n,r,"build",t,"outputs")}function zE(n,e,t){return Bi.join(Gm(n,e,t),`${e}-${t}-signed.hqf`)}function JE(n,e,t){let r=Gm(n,e,t),i=zE(n,e,t);if(Rl.existsSync(i))return i;let o=Tl(r,"-signed.hqf")??Tl(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return p(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function Tl(n,e){if(!Rl.existsSync(n))return null;for(let t of Rl.readdirSync(n,{withFileTypes:!0})){let r=Bi.join(n,t.name);if(t.isDirectory()){let i=Tl(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import se from"fs";import*as M from"path";import xl from"json5";var qm="default",Ln=class n{static writeChangedFileLists(e,t,r,i){let o=t||qm,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||qm,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=M.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=M.join(e,r,"build",t,"intermediates","patch","default"),s=M.join(o,"changedFileList.json");if(se.existsSync(s)||(se.mkdirSync(o,{recursive:!0}),se.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=M.join(e,r,"build",t,"intermediates","hotReload"),c=M.join(a,"changedFileList.json");se.existsSync(c)||(se.mkdirSync(a,{recursive:!0}),se.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=M.join(e,"build-profile.json5");if(!se.existsSync(t))return null;try{let r=se.readFileSync(t,"utf-8");return xl.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=M.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=M.normalize(e);for(let o of r){let s=M.normalize(M.join(t,o.srcPath)),a=s+M.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=M.join(e,t,"src","main","module.json5");if(!se.existsSync(r))return"entry";try{let i=se.readFileSync(r,"utf-8");return xl.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=M.join(e,t,"oh-package.json5");if(!se.existsSync(r))return[];try{let i=se.readFileSync(r,"utf-8"),o=xl.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=M.resolve(e,t,o);return i.find(l=>M.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=M.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=M.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=M.dirname(s);se.existsSync(l)||se.mkdirSync(l,{recursive:!0}),se.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),p(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!se.existsSync(e))return[];try{let t=se.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=M.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=M.join(e,a,"src","main","ets"),g=i.map(xe=>n.resolveRelativePathForPatch(xe,d)),y=n.mergeStrings(l.modifiedFiles,g),I=n.mergePatchResources(l.rawFile,o),le=n.mergePatchResources(l.resFile,s),z=M.dirname(c);se.existsSync(z)||se.mkdirSync(z,{recursive:!0}),se.writeFileSync(c,JSON.stringify({resources:{resFile:le,rawFile:I},modifiedFiles:y}),"utf-8"),p(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!se.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=se.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return M.relative(M.normalize(t),M.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import YE from"fs";import{randomUUID as KE}from"crypto";import{execa as XE}from"execa";var Mn=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!YE.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}E.assertBundleName(r);let o=`/data/local/tmp/${KE()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let o=await this.runHdc(r,!1);if(p(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;p(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await XE(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var ZE="6.1.1",ks=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await Jr(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(ZE);let t=Ui(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t);await this.stopApp(e);let i=await this.buildHqf(e,r);await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Ln.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return p(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Vm(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Mn(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Le(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new Le(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){throw new Error(`[Apply] launch app failed: ${r.message}`,{cause:r})}}};import Nl from"fs";import*as B from"path";var Is=class n{static generate(e,t,r,i){let o=_t(e,t),s=B.join(e,o),a=B.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Nl.mkdirSync(a,{recursive:!0}),Nl.writeFileSync(B.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=B.join(s,"build",r,"intermediates","loader_out",r,"ets");Nl.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,r,i){let o=B.dirname(i.nodePath)+B.sep,s=B.join(t,"build",r),a=B.join(s,"intermediates"),c=B.join(a,"loader_out",r),l=B.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:B.join(e,"build-profile.json5"),localPropertiesPath:B.join(e,"local.properties"),appResource:B.join(l,"ResourceTable.txt"),cachePath:B.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:B.join(a,"loader",r,"loader.json"),aceModuleJsonPath:B.join(l,"module.json"),aceSoPath:B.join(c,"nativeDependencies.txt"),aceModuleRoot:B.join(t,"src","main","ets"),aceModuleBuild:B.join(c,"ets"),aceProfilePath:B.join(l,"resources","base","profile"),aceSuperVisualPath:B.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:B.join(c,"ets"),changedFileList:B.join(a,"patch",r,"changedFileList.json"),patchAbcPath:B.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import zm from"fs";import*as q from"path";var As=class n{static generate(e,t,r,i){let o=_t(e,t),s=q.join(e,o),a=q.join(s,"build","config"),c=n.buildConfig(e,s,r,i);zm.mkdirSync(a,{recursive:!0}),zm.writeFileSync(q.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),p(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=q.dirname(i.nodePath)+q.sep,s=q.join(t,"build",r),a=q.join(s,"intermediates"),c=q.join(a,"loader_out",r),l=q.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:q.join(e,"build-profile.json5"),localPropertiesPath:q.join(e,"local.properties"),appResource:q.join(l,"ResourceTable.txt"),cachePath:q.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:q.join(a,"loader",r,"loader.json"),aceModuleJsonPath:q.join(l,"module.json"),aceSoPath:q.join(c,"nativeDependencies.txt"),aceModuleRoot:q.join(t,"src","main","ets"),aceModuleBuild:q.join(c,"ets"),aceProfilePath:q.join(l,"resources","base","profile"),aceSuperVisualPath:q.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:q.join(c,"ets"),changedFileList:q.join(a,"hotReload","changedFileList.json"),patchAbcPath:q.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Jm from"crypto";import dt from"fs";import ut from"path";import Ym from"os";import{io as QE}from"socket.io-client";var eP=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),On=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;dt.mkdirSync(ut.dirname(i),{recursive:!0}),dt.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
44
|
+
`),"Multiple devices match."):new w(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`,"Device not found.")}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let n=await Qi(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=n.get("const.product.devicetype");let i=n.get("const.ohos.apiversion"),o=n.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=ur(e),n,i;try{let o=await Qi(this.hdcPath,e,[...Vw]);n=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:i}}};function WI(r,e,t,n){let i=["-t",r,"shell","bm","install"];return n?.replace&&i.push("-r"),e&&i.push("-p",e),t&&i.push("-s",t),n?.wait!==void 0&&i.push("-w",String(n.wait)),n?.user&&i.push("-u",n.user),i}var le=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ce.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;f(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await Gw(n,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){E.assertBundleNameStrict(t);let n=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(n.includes("uninstall bundle successfully"))return!0;if(n.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${n}`)}async installApp(e,t,n){let i=!!n?.shared?.length;if(t.length===0&&!i)return;let o=BI(),s=t.length?`/data/local/tmp/${o}`:null,a=i?`/data/local/tmp/${o}-shared`:null;try{s&&await this.runHdc(["-t",e,"shell","mkdir",s]),a&&await this.runHdc(["-t",e,"shell","mkdir",a]),s&&await this.pushFiles(e,t,s),a&&n?.shared&&await this.pushFiles(e,n.shared,a);let c=WI(e,s,a,n),l=await this.runHdc(c);if(!l.includes("install bundle successfully."))throw new Error(l)}finally{s&&await this.runHdc(["-t",e,"shell","rm","-rf",s],!1),a&&await this.runHdc(["-t",e,"shell","rm","-rf",a],!1)}}async pushFiles(e,t,n){for(let i of t){let o=await this.runHdc(["-t",e,"file","send",i,n+"/"]);if(!o.startsWith("FileTransfer finish"))throw new Error(o)}}async launchApp(e,t,n){E.assertBundleNameStrict(t),E.assertAbilityName(n);let i=["-t",e,"shell","aa","start","-a",n,"-b",t];return await this.runHdc(i)}async pidofBundle(e,t){E.assertBundleNameStrict(t);let n=["-t",e,"shell","pidof",t],i=this.toolProvider.hdcPath;f(`Executing: ${i} ${n.join(" ")}`);let o=await C(i,n),s=Bw(o);if(s==="query-failed"){let a=[o.stdout,o.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${o.exitCode}`}`)}return s==="alive"}async forceStopApp(e,t){E.assertBundleNameStrict(t);let n=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(n,!1)}async transferFile(e,t,n,i){let o=["-t",e,"file",t,n,i],s=await this.runHdc(o,!1);if(!s.includes("FileTransfer finish"))throw new Error(`File ${t} failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async runSqlite3(e,t,n=[]){let i=["-t",e,"shell","sqlite3",t,...n];await Gw(this.toolProvider.hdcPath,i,{stdio:"inherit",env:{...process.env}})}};import Xp from"fs";import*as Qn from"path";function Cs(r,e){if(!Xp.existsSync(r))throw new Error(`Apply file list not found: ${r}`);let n=Xp.readFileSync(r,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(n.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Qn.resolve(e),o=new Set,s=[];for(let a of n){let c=Qn.resolve(i,a),l=Qn.isAbsolute(a)?Qn.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,i);if(!d.contained){if(!Xp.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Zp from"fs";import ks from"path";import{execa as VI}from"execa";async function qw(r,e,t,n){let i=ks.dirname(r.javaPath),o={...process.env,PATH:`${i}${ks.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:r.sdkPath},s=[r.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${n}`,"-p",`product=${n}`,"-p","debuggable=true","assembleDevHqf"];f(`[buildSignedHqf] ${r.nodePath} ${s.join(" ")}`);let a=await VI(r.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>qI(e,l,n))}function zw(r,e,t){let n=Ht(r,e);return ks.join(r,n,"build",t,"outputs")}function GI(r,e,t){return ks.join(zw(r,e,t),`${e}-${t}-signed.hqf`)}function qI(r,e,t){let n=zw(r,e,t),i=GI(r,e,t);if(Zp.existsSync(i))return i;let o=Qp(n,"-signed.hqf")??Qp(n,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${n})`);return f(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function Qp(r,e){if(!Zp.existsSync(r))return null;for(let t of Zp.readdirSync(r,{withFileTypes:!0})){let n=ks.join(r,t.name);if(t.isDirectory()){let i=Qp(n,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return n}return null}import de from"fs";import*as U from"path";import ef from"json5";var Jw="default",eo=class r{static writeChangedFileLists(e,t,n,i){let o=t||Jw,s=r.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:n};let a=s.modules,c=r.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:n};let l=r.buildReverseDependencyMap(e,a),d=r.createCollectors(c),h=r.collectChanges(n,e,a,l,d);return{writtenModules:r.flushCollectors(e,o,c,d,i),skippedFiles:h}}static initEmptyChangedFileLists(e,t,n){let i=t||Jw,o=r.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=r.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!n||c.name===n;r.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(n=>{let i=r.getModuleType(e,n.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let n of e)t.set(n.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,n,i,o){let s=[];for(let a of e){let c=U.normalize(a),l=r.classifyFile(c,t,n);if(l.fileClass==="unknown"){s.push(c);continue}let d=r.findModuleByFilePath(c,t,n);if(!d){s.push(c);continue}let h=r.resolveTargetModules(d,t,n,i);if(h.length===0){s.push(c);continue}r.dispatchToCollectors(h,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,n,i){let o=r.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(r.findTopLevelConsumers(e.name,i,t,n))}static dispatchToCollectors(e,t,n,i,o,s){for(let a of e){let c=t.get(a);c&&r.addFileToCollector(c,n,i.fileClass,o,s)}}static flushCollectors(e,t,n,i,o){let s=[];for(let a of n){let c=i.get(a.name);if(!c||!r.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&r.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),r.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,n,i){let o=U.join(e,n,"build",t,"intermediates","patch","default"),s=U.join(o,"changedFileList.json");if(de.existsSync(s)||(de.mkdirSync(o,{recursive:!0}),de.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=U.join(e,n,"build",t,"intermediates","hotReload"),c=U.join(a,"changedFileList.json");de.existsSync(c)||(de.mkdirSync(a,{recursive:!0}),de.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=U.join(e,"build-profile.json5");if(!de.existsSync(t))return null;try{let n=de.readFileSync(t,"utf-8");return ef.parse(n)}catch{return null}}static classifyFile(e,t,n){let i=U.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,n){let i=U.normalize(e);for(let o of n){let s=U.normalize(U.join(t,o.srcPath)),a=s+U.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let n=U.join(e,t,"src","main","module.json5");if(!de.existsSync(n))return"entry";try{let i=de.readFileSync(n,"utf-8");return ef.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let n=new Map;for(let i of t){let o=r.readLocalDependencies(e,i.srcPath);for(let s of o){let a=n.get(s)||[];a.includes(i.name)||a.push(i.name),n.set(s,a)}}return n}static readLocalDependencies(e,t){let n=U.join(e,t,"oh-package.json5");if(!de.existsSync(n))return[];try{let i=de.readFileSync(n,"utf-8"),o=ef.parse(i);return r.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,n){let i=r.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(n)){if(typeof a!="string")continue;let c=r.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,n,i){let o=n;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=U.resolve(e,t,o);return i.find(l=>U.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,n,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),r.processDependents(c,t,n,i,o,a))}return o}static processDependents(e,t,n,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(h=>h.name===c);if(!l)continue;let d=r.getModuleType(n,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,n,i,o){let s=U.join(o,i,"src","main","resources");n==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):n==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):n==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):n==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,n,i){let o=t.replace(/^\.\//,""),s=U.join(e,o,"build",n,"intermediates","hotReload","changedFileList.json"),a=r.readExistingApply(s),c=r.mergeApplyEntries(a,i),l=U.dirname(s);de.existsSync(l)||de.mkdirSync(l,{recursive:!0}),de.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),f(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!de.existsSync(e))return[];try{let t=de.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,n,i,o,s){let a=t.replace(/^\.\//,""),c=U.join(e,a,"build",n,"intermediates","patch","default","changedFileList.json"),l=r.readExistingPatch(c),d=U.join(e,a,"src","main","ets"),h=i.map(ut=>r.resolveRelativePathForPatch(ut,d)),y=r.mergeStrings(l.modifiedFiles,h),D=r.mergePatchResources(l.rawFile,o),K=r.mergePatchResources(l.resFile,s),we=U.dirname(c);de.existsSync(we)||de.mkdirSync(we,{recursive:!0}),de.writeFileSync(c,JSON.stringify({resources:{resFile:K,rawFile:D},modifiedFiles:y}),"utf-8"),f(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!de.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=de.readFileSync(e,"utf-8"),n=JSON.parse(t);return{modifiedFiles:n?.modifiedFiles||[],rawFile:n?.resources?.rawFile||[],resFile:n?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return U.relative(U.normalize(t),U.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let n=new Set,i=[];for(let o of[...e,...t])n.has(o.filePath)||(n.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let n=new Set,i=[];for(let o of[...e,...t])n.has(o)||(n.add(o),i.push(o));return i}static mergePatchResources(e,t){let n=new Set,i=[];for(let o of[...e,...t])n.has(o.filePath)||(n.add(o.filePath),i.push(o));return i}};import zI from"fs";import{randomUUID as JI}from"crypto";import{execa as KI}from"execa";var to=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,n){for(let a of t)if(!zI.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}E.assertBundleName(n);let o=`/data/local/tmp/${JI()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${n}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,n,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",n]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let n=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&n.push("-o");let o=await this.runHdc(n,!1);if(f(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),n=parseInt(t.trim(),10);if(!isNaN(n))return console.log(`[InstallHqf] device API version: ${n}`),n}catch{}return 0}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;f(`[InstallHqf] Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await KI(n,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var YI="6.1.1",zc=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}async execute(e){await xr(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(YI);let t=Cs(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let n=this.writeChangeFileList(e,t);await this.stopApp(e);let i=await this.buildHqf(e,n);await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let n=eo.writeChangedFileLists(this.projectRoot,e.productName,t);if(n.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${n.writtenModules.join(", ")}`),n.writtenModules}async buildHqf(e,t){return f(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await lr.withBuildConfig(this.projectRoot,t,e.productName,this.toolProvider,()=>qw(this.toolProvider,this.projectRoot,t,e.productName))}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new to(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new le(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(n){console.warn(`[Apply] stop app failed: ${n.message}`)}}async launchApp(e){let t=new le(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(n){throw new Error(`[Apply] launch app failed: ${n.message}`,{cause:n})}}};import Kw from"fs";import*as ee from"path";var Jc=class r{static generate(e,t,n,i){let o=Ht(e,t),s=ee.join(e,o),a=ee.join(s,"build","config"),c=r.buildConfig(e,s,n,i);Kw.mkdirSync(a,{recursive:!0}),Kw.writeFileSync(ee.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,n,i){let o=ee.dirname(i.nodePath)+ee.sep,s=ee.join(t,"build",n),a=ee.join(s,"intermediates"),c=ee.join(a,"loader_out",n),l=ee.join(a,"res",n);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:ee.join(e,"build-profile.json5"),localPropertiesPath:ee.join(e,"local.properties"),appResource:ee.join(l,"ResourceTable.txt"),cachePath:ee.join(s,"cache",n,`${n}@CompileArkTS`,"esmodule","debug"),aceBuildJson:ee.join(a,"loader",n,"loader.json"),aceModuleJsonPath:ee.join(l,"module.json"),aceSoPath:ee.join(c,"nativeDependencies.txt"),aceModuleRoot:ee.join(t,"src","main","ets"),aceModuleBuild:ee.join(c,"ets"),aceProfilePath:ee.join(l,"resources","base","profile"),aceSuperVisualPath:ee.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:ee.join(c,"ets"),changedFileList:ee.join(a,"hotReload","changedFileList.json"),patchAbcPath:ee.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Yw from"crypto";import Ct from"fs";import kt from"path";import Xw from"os";import{io as XI}from"socket.io-client";var ZI=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),ro=class r{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let n=await this.getOrCreateSocket(t),i=this.watchLogPath;Ct.mkdirSync(kt.dirname(i),{recursive:!0}),Ct.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);n.on("WatchLog",o.onWatchLog),n.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(n,e)}createWatchLogBuffer(e){let n=[];return{onWatchLog:s=>{let a=r.extractText(s);a.trim()&&(n.push(a.endsWith(`
|
|
42
45
|
`)?a:a+`
|
|
43
|
-
`),
|
|
44
|
-
`].join("")),
|
|
46
|
+
`),n.length>100&&n.shift())},onWatchResult:s=>{let a=r.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),Ct.writeFileSync(e,[...n,c+`
|
|
47
|
+
`].join("")),n.length=0}}}awaitInitialBuild(e,t){return new Promise((n,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),n()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return kt.join(this.projectRoot,".hvigor","hotreload-watch.log")}buildStartOptions(e){let t={_:["assembleHap"],daemon:!0,watch:!0,hotReloadBuild:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildStartOptions:",JSON.stringify(t,null,2)),t}disconnect(){this.invalidateSocket()}onSocketDisconnect(e){this.cachedSocket&&this.cachedSocket.on("disconnect",e)}async getOrCreateSocket(e){if(this.cachedSocket&&this.cachedDaemonPort===e.port){if(this.cachedSocket.connected)return this.cachedSocket;this.invalidateSocket()}let t=this.decryptSessionId(e.sessionId);console.log(`[DaemonClient] Socket.IO connect: ws://127.0.0.1:${e.port} (${e.state})`);let n=XI(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((i,o)=>{let s=setTimeout(()=>{o(new Error("Socket connect timeout (10s)"))},1e4);n.once("connect",()=>{clearTimeout(s),i()}),n.once("connect_error",a=>{clearTimeout(s),o(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=n,this.cachedDaemonPort=e.port,n}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let n=await this.getOrCreateSocket(e);return new Promise((i,o)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(n,()=>s,d=>s=d,o),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),n.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),i(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),n.off("BuildStatus",l),this.invalidateSocket(),o(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};n.on("disconnect",c.onDisconnect),n.on("Output",c.onOutput),n.on("BuildStatus",l),n.on("WatchLog",c.onWatchLog),n.on("WatchResult",c.onWatchResult),n.on("WatchCompileResult",c.onWatchCompileResult),n.on("WatchCompileData",c.onWatchCompileData),n.emit("CommonBuild",this.buildCompileOptions(t)),console.log("[DaemonClient] Compiling, waiting for hot compile to finish...")})}static extractText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e;if(typeof t.text=="string")return t.text;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message}return JSON.stringify(e)}createHotCompileHandlers(e,t,n,i){let o=y=>{t()||(n(!0),h(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${y}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),h=()=>{e.off("disconnect",o),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:o,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:h}}getDataHandler(){let e=r.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
|
|
45
48
|
`)?"":`
|
|
46
|
-
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!dt.existsSync(e))return null;try{let t=dt.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=ut.join(t,"fd"),i=ut.join(t,"ac"),o=ut.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(eP)]),c=this.readSingleFile(i),l=Jm.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),y=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,y).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Jm.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=dt.readdirSync(e).map(r=>ut.join(e,r)).filter(r=>dt.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let i=dt.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return dt.readFileSync(ut.join(r,i[0]))})}readSingleFile(e){let t=dt.readdirSync(e).map(r=>ut.join(e,r)).filter(r=>dt.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return dt.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||ut.join(Ym.homedir(),".hvigor");return ut.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||ut.join(Ym.homedir(),".hvigor");return ut.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Zm from"fs";import*as Gt from"path";import{green as xs,yellow as Ll}from"colorette";import Zr from"fs";import*as Qr from"path";import tP from"json5";var rP=2e6,nP=1e6,iP="hotreload",Ds=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Qr.resolve(e,t),s=Qr.join(o,"patch.json"),a;return Zr.existsSync(s)?(p(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(p(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:rP,versionCode:i.versionCode},module:{name:r,type:iP}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Qr.join(e,"AppScope","app.json5");if(!Zr.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Zr.readFileSync(t,"utf-8"),i=tP.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??nP;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Zr.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Qr.dirname(e);Zr.existsSync(r)||Zr.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Zr.writeFileSync(e,i,"utf-8"),p(`[PatchManager] patch.json written to ${e}`),p(`[PatchManager] Content: ${i}`)}};import be from"fs";import*as Y from"path";import Km from"crypto";import oP from"json5";import{execa as Xm}from"execa";var Rs=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);p(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=Y.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return p(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=Y.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(Y.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(Y.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=Km.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=Km.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=be.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=Y.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(be.statSync(e).isDirectory()){let i=be.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(be.readFileSync(Y.join(e,i[0])))}return new Int8Array(be.readFileSync(e))}},Ts=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Y.dirname(e.javaPath)}${Y.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=Y.join(e,"ets","modules.abc");if(be.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!be.existsSync(e))return null;let t=be.readdirSync(e,{withFileTypes:!0});for(let r of t){let i=Y.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=_t(this.projectRoot,e),i=Y.join(this.projectRoot,r,"build",t,"outputs","default");return be.existsSync(i)||be.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:Y.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:Y.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=Y.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];p(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Xm(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):be.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath,s=i.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(i[c-1])?"******":a);p(`[GenSignHqf] Signing: ${o} ${s.join(" ")}`);try{let a=Date.now(),c=await Xm(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):be.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=Rs.decryptPwd(r,t.storePassword,"storePassword"),o=Rs.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=Y.resolve(e.storeFile,".."),r=Y.join(t,"material");return be.existsSync(r)?t:null}readSigningConfig(e){let t=Y.join(this.projectRoot,"build-profile.json5");if(!be.existsSync(t))return null;try{let r=be.readFileSync(t,"utf-8"),i=oP.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[Y.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),Y.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(be.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[Y.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),Y.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(be.existsSync(r))return r;return null}};async function Qm(n){let e=Date.now(),t=_t(n.projectPath,n.moduleName),r=sP(n);console.log(Ll("[HotReload] Ensure the project source is trusted before proceeding."));let i=aP(n),o=Ui(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),cP(n,o),lP(n,t),await dP(n,i);let s=Gt.join(n.projectPath,t,"patch.json"),a=await pP(n,t,s);return await mP(n,a),console.log(xs("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function sP(n){if(Gt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Gt.join(n.projectPath,".hvigor",n.applyFileName)}function aP(n){let{projectPath:e,toolProvider:t}=n,r=new On(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function cP(n,e){let t=Ln.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(xs(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(Ll(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function lP(n,e){let t=Ds.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(xs(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function dP(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=uP(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
|
|
49
|
+
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let n=Date.now();for(;Date.now()-n<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!Ct.existsSync(e))return null;try{let t=Ct.readFileSync(e,"utf-8"),n=JSON.parse(t),i=Object.values(n).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),n=kt.join(t,"fd"),i=kt.join(t,"ac"),o=kt.join(t,"ce"),s=this.readComponents(n),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(ZI)]),c=this.readSingleFile(i),l=Yw.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),h=this.aesGcmDecrypt(l,d),y=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,y).toString("utf-8")}aesGcmDecrypt(e,t){let n=0,i=t.readUInt32BE(n);n+=4;let o=t.subarray(n,n+12);n+=12;let s=i-16,a=t.subarray(n,n+s);n+=s;let c=t.subarray(n,n+16),l=Yw.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=Ct.readdirSync(e).map(n=>kt.join(e,n)).filter(n=>Ct.statSync(n).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(n=>{let i=Ct.readdirSync(n);if(i.length===0)throw new Error(`No file in ${n}`);return Ct.readFileSync(kt.join(n,i[0]))})}readSingleFile(e){let t=Ct.readdirSync(e).map(n=>kt.join(e,n)).filter(n=>Ct.statSync(n).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return Ct.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let n=1;n<e.length;n++){let i=Buffer.isBuffer(e[n])?e[n]:Buffer.from(e[n]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||kt.join(Xw.homedir(),".hvigor");return kt.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||kt.join(Xw.homedir(),".hvigor");return kt.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import ev from"fs";import*as Tr from"path";import{green as Zc,yellow as tf}from"colorette";import ei from"fs";import*as ti from"path";import QI from"json5";var eA=2e6,tA=1e6,rA="hotreload",Kc=class r{static generateOrUpdate(e,t,n){let i=r.readAppConfig(e),o=ti.resolve(e,t),s=ti.join(o,"patch.json"),a;return ei.existsSync(s)?(f(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=r.readExistingPatch(s),a.app.patchVersionCode+=1):(f(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:eA,versionCode:i.versionCode},module:{name:n,type:rA}}),r.writePatchJson(s,a),a}static readAppConfig(e){let t=ti.join(e,"AppScope","app.json5");if(!ei.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let n=ei.readFileSync(t,"utf-8"),i=QI.parse(n),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??tA;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=ei.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return n}static writePatchJson(e,t){let n=ti.dirname(e);ei.existsSync(n)||ei.mkdirSync(n,{recursive:!0});let i=JSON.stringify(t,null,2);ei.writeFileSync(e,i,"utf-8"),f(`[PatchManager] patch.json written to ${e}`),f(`[PatchManager] Content: ${i}`)}};import Ae from"fs";import*as te from"path";import Zw from"crypto";import nA from"json5";import{execa as Qw}from"execa";var Yc=class r{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,n){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${n}`);f(`[DecipherUtil] Decrypting ${n}, encrypted length: ${t.length}`);let i=te.resolve(e,"material"),o=r.getKey(i,n),s=new Int8Array(Buffer.from(t,"hex"));return f(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),r.decrypt(o,s).toString("utf-8")}static getKey(e,t){let n=te.resolve(e,r.DIRS[0]),i=r.readFd(n,t),o=r.readDirBytes(te.resolve(e,r.DIRS[1]),t),s=r.getRootKey(i,o,t),a=r.readDirBytes(te.resolve(e,r.DIRS[2]),t);return new Int8Array(r.decrypt(s,a))}static getRootKey(e,t,n){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${n}`);let i=[...e,r.COMPONENT],o=r.xor(i[0],i[1],n);for(let a=2;a<i.length;a++)o=r.xor(o,i[a],n);let s=Zw.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,n){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${n}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let n=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-n,o=t.slice(4,4+i),s=t.slice(t.length-16),a=Zw.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let n=Ae.readdirSync(e).filter(o=>o!==".DS_Store");if(n.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of n){let s=te.join(e,o);i.push(r.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(Ae.statSync(e).isDirectory()){let i=Ae.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(Ae.readFileSync(te.join(e,i[0])))}return new Int8Array(Ae.readFileSync(e))}},Xc=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${te.dirname(e.javaPath)}${te.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,n,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(n,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=te.join(e,"ets","modules.abc");if(Ae.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let n=this.findFirstAbc(e);return n?{exists:!0,abcPath:n,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!Ae.existsSync(e))return null;let t=Ae.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=te.join(e,n.name);if(n.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(n.isFile()&&n.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let n=Ht(this.projectRoot,e),i=te.join(this.projectRoot,n,"build",t,"outputs","default");return Ae.existsSync(i)||Ae.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:te.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:te.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,n){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=te.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",n,"--force","true"];f(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await Qw(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):Ae.existsSync(n)?(console.log(`[HotReload] Unsigned hqf generated: ${n}`),!0):(console.error(`[HotReload] hqf not generated at ${n}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let n=this.resolveSignConfig();if(!n)return this.signFailResult(e,"Signing prerequisites not met.");let i=this.buildSignArgs(n,e,t),o=this.toolProvider.javaPath,s=i.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(i[c-1])?"******":a);f(`[GenSignHqf] Signing: ${o} ${s.join(" ")}`);try{let a=Date.now(),c=await Qw(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-a}ms`),c.stdout&&console.log(c.stdout),c.stderr&&console.error(c.stderr),c.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${c.exitCode}`):Ae.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(a){return this.signFailResult(e,`hqf signing failed: ${a.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let n=this.resolveMaterialDir();if(!n)return null;try{let i=Yc.decryptPwd(n,t.storePassword,"storePassword"),o=Yc.decryptPwd(n,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,n){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",n,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=te.resolve(e.storeFile,".."),n=te.join(t,"material");return Ae.existsSync(n)?t:null}readSigningConfig(e){let t=te.join(this.projectRoot,"build-profile.json5");if(!Ae.existsSync(t))return null;try{let n=Ae.readFileSync(t,"utf-8"),i=nA.parse(n),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[te.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),te.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let n of t)if(Ae.existsSync(n))return n;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[te.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),te.join(e,"toolchains","lib","app_packing_tool.jar")];for(let n of t)if(Ae.existsSync(n))return n;return null}};async function tv(r){let e=Date.now(),t=Ht(r.projectPath,r.moduleName),n=iA(r);console.log(tf("[HotReload] Ensure the project source is trusted before proceeding."));let i=oA(r),o=Cs(n,r.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${r.applyFileName}`),sA(r,o),aA(r,t),await cA(r,i);let s=Tr.join(r.projectPath,t,"patch.json"),a=await dA(r,t,s);return await uA(r,a),console.log(Zc("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function iA(r){if(Tr.basename(r.applyFileName)!==r.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r.applyFileName}`);return Tr.join(r.projectPath,".hvigor",r.applyFileName)}function oA(r){let{projectPath:e,toolProvider:t}=r,n=new ro(e,t);if(!n.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return n}function sA(r,e){let t=eo.writeChangedFileLists(r.projectPath,r.productName,e,r.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(Zc(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(tf(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function aA(r,e){let t=Kc.generateOrUpdate(r.projectPath,e,r.moduleName);console.log(Zc(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function cA(r,e){let t=Date.now(),n=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:r.moduleSpecs,productName:r.productName});if(i!==0){let o=lA(n);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
|
|
47
50
|
--- compile output (from watch session) ---
|
|
48
|
-
${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function
|
|
49
|
-
`):""}catch{return""}}async function
|
|
50
|
-
`)}toTraceError(e,t){return new
|
|
51
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return
|
|
51
|
+
${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function lA(r){try{return ev.existsSync(r)?ev.readFileSync(r,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
|
|
52
|
+
`):""}catch{return""}}async function dA(r,e,t){let n=Tr.join(r.projectPath,e,"build",r.productName,"intermediates"),i=[Tr.join(n,"hotReload","patchAbcPath"),Tr.join(n,"patch","default")],o=Date.now(),s=new Xc(r.toolProvider,r.projectPath),a=r.targetDeviceId.includes("127.0.0.1")||r.targetDeviceId.includes("localhost"),c=null;for(let l of i){let d=await s.generateAndSign(r.moduleName,l,t,r.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-o}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function uA(r,e){let t=Date.now(),i=await new to(r.toolProvider).install(r.targetDeviceId,e,r.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!i.success)throw new Error(`hqf install failed: ${i.message}`)}function rf(r,e){if(!r||r.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function rv(r,e,t){let n=Tr.join(r.rootDir,".hvigor",t),i;try{i=Cs(n,r.rootDir)}catch{return}let o=new Set;for(let s of i){let a=r.findOwningModule(s);if(!a||a===e)continue;let c=r.getModuleType(a);(c==="feature"||c==="shared")&&o.add(`${a} (${c})`)}o.size>0&&console.warn(tf(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...o].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function nv(r,e,t,n,i){let o=new Set,s=r.collectNonHarDependentModuleList(e);for(let a of s)o.add(r.findArtifactPath(a,t,n,i));return o.add(r.findArtifactPath(e,t,n,i)),[...o]}async function iv(r,e){let t=new ht(r,e.rootDir);try{await t.stopDaemon()}finally{await xr(e.rootDir,async()=>{lr.removeAll(e)},()=>console.log("Another build is already running for this project. Waiting for completion..."))}console.log(Zc("Hvigor daemon stopped."))}var Qc=class{formatPass(e){return e.evidence.processCheckSkipped?"Smoke: PASS (process check unavailable, smoke skipped)":e.evidence.phashBlank===null?"Smoke: PASS (screenshot unavailable, blank check skipped)":"Smoke: PASS"}formatFailure(e,t){let{status:n,reason:i,evidence:o}=e,s=[`Smoke: ${n}`,`${i} (bundle=${t.bundleName}, device=${t.targetDeviceId}).`];return n==="FAIL_CRASH"&&o.crashLogPath&&s.push(`crash_log: ${o.crashLogPath}`),n==="FAIL_BLANK"&&o.screenshotPath&&s.push(`screenshot: ${o.screenshotPath}`),s.join(`
|
|
53
|
+
`)}toTraceError(e,t){return new w(this.formatFailure(e,t),e.status)}};import yl from"fs";import KT from"path";import{yellow as Os}from"colorette";import{cyan as el}from"colorette";function ri(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=Bt(t);return n==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var nf=[800,1500,2500];function fA(r){return new Promise(e=>setTimeout(e,r))}var dn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ce.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let n of e)console.error(n);return}for(let n of e)console.log(n)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
54
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return f(el(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return f(el(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(n,e);if(i)return f(el(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(n);throw new w(`Device '${e}' not found.
|
|
52
55
|
Available devices:
|
|
53
|
-
${o}`,"Device not found.")}if(
|
|
54
|
-
${o.stdout}`),this.parseCrashLogFilenames(o.stdout,
|
|
55
|
-
`).map(
|
|
56
|
-
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),y=Number(c[3]),I=Number(c[4]);Number.isFinite(y)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:y,name:l,pid:g,displayId:d,type:I})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function nf(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Wi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function of(n){if(typeof n!="string")return;let e=n.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function sf(n){return n.originalText||void 0}function _n(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function af(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let y={...i,children:[]};if(a?t.push(y):o.children.push(y),d=y,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let y=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";p(`collapse ${y} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let y=i.children.length-1;y>=0;y--)r.push({current:i.children[y],parent:d,depth:g})}return t}function bP(n){let e=yP(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function EP(n){return n.attributes??{}}function Ms(n,e,t){let r=EP(n),i={id:r.id||void 0,type:r.type||void 0,text:sf(r),bounds:of(r.bounds),clickable:Wi(r.clickable)||void 0,longClickable:Wi(r.longClickable)||void 0,scrollable:Wi(r.scrollable)||void 0,checkable:Wi(r.checkable)||void 0,hitTestBehavior:nf(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Ms(o,e,t+1))),i}function PP(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new S(`Window '${e}' not found. Available windows: ${i||"none"}`,"Window not found.")}return r}let t=n.find(r=>r.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var tn=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),p(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await ie(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=SP(wP(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),bP(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];p(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await ie(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{p(`Removing local dump file: ${t}`),vP(t)}catch(o){p(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];p(`Executing: ${this.hdcPath} ${i.join(" ")}`),await ie(this.hdcPath,i).catch(o=>{p(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new qt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=PP(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>Ms(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:Ms(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>af(Ms(s,0,0),t))}};import Ge from"fs";import Ae from"path";import{randomUUID as CP}from"crypto";function cf(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display!==void 0&&t.push("-i",n.display),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function lf(n,e){return[n,e].filter(Boolean).join(`
|
|
57
|
-
`).trim()}function
|
|
56
|
+
${o}`,"Device not found.")}if(n.length===1){let i=n[0];return f(el(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new w("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(n),"Multiple devices found.")}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,n){f(`Retrieving PID for bundle ${n}`),E.assertBundleNameStrict(n);let i=await C(e,["-t",t,"shell","pidof",n]),o=ri(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return f(`Found PID for ${n}: ${a}`),a}return f(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){if(f(`Setting hilog buffer size to: ${n}`),!/^\d+[KMG]?$/.test(n))throw new Error(`Invalid hilog buffer size: ${JSON.stringify(n)}. Expected format: <number>[K|M|G], e.g. "4M", "16M"`);let i=await C(e,["-t",t,"shell","hilog","-G",n]),o=ri(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,n,i){let o=this.buildHilogShellCommand(n,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let n=["hilog"];return e.isFollow||n.push("-x"),e.tag&&(E.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(E.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(E.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(E.assertHilogKeyword(e.keyword),n.push("-e",E.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,i,o){let a=await Hw(e,t,{onData:n,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,n,i,o){let s=1+nf.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,n,i,o),a.exitCode===0||Bt(a.stderr)!=="transient"||c>=s-1)return a;f(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${nf[c]}ms`),await fA(nf[c])}return a}async runHilogStreamingCollect(e,t,n){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{f(`Callback triggered when an error occurs during ${n}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,n,i){if(!n.tail&&!n.fromSeconds&&!n.toSeconds)return;let o={...n,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);f(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=ri(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=E.filterLogsByRelativeWindow(c.stdout||c.stderr,n.fromSeconds,n.toSeconds);d=E.getLastLines(d,n.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,n,i){let[o,s]=this.buildHilogCommand(e,t,n,i);f(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=ri(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=E.filterLogsByRelativeWindow(l,n.fromSeconds,n.toSeconds);return d=E.getLastLines(d,n.tail),d}async runHilogFollow(e,t,n,i){try{await this.printTailSnapshotIfNeeded(e,t,n,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,n,i);f(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{f(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=ri(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let n=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(n,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new w(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`,"No running process found for bundle.");return t.logSize&&await this.resizeHilogBuffer(n,e,t.logSize),t.isFollow?await this.runHilogFollow(n,e,t,i||""):await this.getHilogOnce(n,e,t,i||"")}async getLatestCrashLog(e,t){f(`Fetching crash logs from device: ${e}`);let n=this.toolProvider.hdcPath,i=await this.listCrashLogs(n,e,t);if(i.length===0)return;let s=[...i].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(n,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async getCrashLog(e,t){let n=await this.getLatestCrashLog(e,t);return n!==void 0?n:t?`No crash logs found for bundle '${t}'.`:"No crash logs found."}async listCrashLogs(e,t,n){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];f(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=ri(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return f(`Crash logs list output:
|
|
57
|
+
${o.stdout}`),this.parseCrashLogFilenames(o.stdout,n)}parseCrashLogFilenames(e,t){return e.split(`
|
|
58
|
+
`).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>{try{return E.assertCrashFilename(n),!0}catch{return!1}}).filter(n=>t?n.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){f(`Fetching latest crash log file: ${n}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];f(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=ri(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{readFileSync as hA,unlinkSync as gA}from"fs";import{tmpdir as yA}from"os";import{join as wA}from"path";var Nr=class{constructor(e,t){this.hdcPath=e;this.serial=t}async listWindows(e){let t=await this.fetchDump(),n=mA(t);return e?.all||(n=n.filter(i=>i.type===1)),n}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];f(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await C(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function mA(r){let e=r.split(`
|
|
59
|
+
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let n=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),y=Number(c[3]),D=Number(c[4]);Number.isFinite(y)&&Number.isFinite(d)&&Number.isFinite(h)&&n.push({id:y,name:l,pid:h,displayId:d,type:D})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return n.map(s=>({...s,focused:s.id===o}))}function ov(r){if(!(!r||r==="HitTestMode.Default"))return r.startsWith("HitTestMode.")?r.slice(12):r}function Rs(r){if(!(r==null||r==="")){if(typeof r=="boolean")return r;if(r==="true")return!0;if(r==="false")return!1}}function tl(r){if(typeof r!="string")return;let e=r.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function sv(r){return r.originalText||void 0}function no(r,e){let t=[],n=[...r].reverse();for(;n.length>0;){let i=n.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)n.push(i.children[o])}return t}function av(r,e){let t=[],n=[{current:r,parent:null,depth:0}];for(;n.length>0;){let{current:i,parent:o,depth:s}=n.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let y={...i,children:[]};if(a?t.push(y):o.children.push(y),d=y,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let y=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";f(`collapse ${y} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let y=i.children.length-1;y>=0;y--)n.push({current:i.children[y],parent:d,depth:h})}return t}function vA(r){let e=hA(r,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function bA(r){return r.attributes??{}}function rl(r,e,t){let n=bA(r),i={id:n.id||void 0,type:n.type||void 0,text:sv(n),bounds:tl(n.bounds),clickable:Rs(n.clickable)||void 0,longClickable:Rs(n.longClickable)||void 0,scrollable:Rs(n.scrollable)||void 0,checkable:Rs(n.checkable)||void 0,hitTestBehavior:ov(n.hitTestBehavior),children:[]};return e>0&&t+1>=e||r.children&&(i.children=r.children.map(o=>rl(o,e,t+1))),i}function SA(r,e){if(e){let n=r.find(i=>String(i.id)===e);if(!n){let i=r.map(o=>`${o.id} (${o.name})`).join(", ");throw new w(`Window '${e}' not found. Available windows: ${i||"none"}`,"Window not found.")}return n}let t=r.find(n=>n.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var _r=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,n){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];n!==void 0&&o.push("-d",String(n)),t&&o.push("-w",t),f(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await C(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let n=wA(yA(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,n),vA(n)}finally{await this.cleanupDumpArtifacts(e,n,t)}}async recvDumpFile(e,t,n){let i=["-t",e,"file","recv",t,n];f(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await C(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,n){try{f(`Removing local dump file: ${t}`),gA(t)}catch(o){f(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",n];f(`Executing: ${this.hdcPath} ${i.join(" ")}`),await C(this.hdcPath,i).catch(o=>{f(`Failed to clean remote dump file ${n}: ${o.message}`)})}async dumpRawNodes(e,t,n){let o=await new Nr(this.hdcPath,e).listWindows({all:!0});if(n){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=SA(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,n,i){return(await this.dumpRawNodes(e,n,i)).map(s=>rl(s,t,0))}async dumpFullTreeByDisplays(e,t,n){let i=[];for(let o of n){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:rl(s,t,0)})}return i}async dumpCollapsedTree(e,t,n,i){return(await this.dumpRawNodes(e,n,i)).flatMap(s=>av(rl(s,0,0),t))}async dumpRawTree(e,t){return(await this.dumpRawNodes(e,t,!1))[0]}};var Be=class extends Error{position;input;constructor(e,t,n){super(`Selector parse error at ${t}: ${e}`),this.name="SelectorParseError",this.position=t,this.input=n}},EA=["*=","^=","$=","/="],PA=/[A-Za-z_]/,CA=/[A-Za-z0-9_]/,sf=/\s/,kA=/^(.*)\/([gimsuy]+)$/,af=class{input;pos=0;constructor(e){this.input=e}eof(){return this.pos>=this.input.length}peek(e=0){let t=this.pos+e;return t>=0&&t<this.input.length?this.input[t]:""}next(){return this.pos<this.input.length?this.input[this.pos++]:""}startsWith(e){return this.input.slice(this.pos,this.pos+e.length)===e}};function Mr(r){for(;!r.eof()&&sf.test(r.peek());)r.next()}function RA(r){let e=r.pos;if(!PA.test(r.peek()))throw new Be("expected attribute key",r.pos,r.input);for(;!r.eof()&&CA.test(r.peek());)r.next();return r.input.slice(e,r.pos)}function DA(r,e){for(let t of EA)if(r.startsWith(t))return r.pos+=t.length,t;if(r.peek()==="=")return r.next(),"=";throw new Be(`expected operator (=, *=, ^=, $=, /=) after key "${e}"`,r.pos,r.input)}function cv(r){let e=r.match(kA);return e?{value:e[1],flags:e[2]}:{value:r}}function xA(r,e){r.next();let t="";for(;!r.eof();){let n=r.next();if(n==="\\"){if(r.eof())throw new Be("dangling escape in quoted value",r.pos,r.input);t+=r.next();continue}if(n===e)return t;t+=n}throw new Be("unterminated quoted value",r.pos,r.input)}function of(r){return r==='"'||r==="'"}function IA(r,e){let t=r.peek();if(of(t)){let i=xA(r,t);return e==="/="?cv(i):{value:i}}let n="";for(;!r.eof();){let i=r.peek();if(i===","||i==="["||of(i))break;if(sf.test(i)){let o=r.pos+1;for(;o<r.input.length&&sf.test(r.input[o]);)o++;let s=o<r.input.length?r.input[o]:"";if(s===""||s===","||s==="["||of(s))break;n+=r.next();continue}if(i==="\\"){if(r.next(),r.eof())throw new Be("dangling escape in value",r.pos,r.input);n+=r.next();continue}n+=r.next()}return e==="/="?cv(n):{value:n}}function lv(r){Mr(r);let e=RA(r);Mr(r);let t=DA(r,e);if(Mr(r),r.eof()||r.peek()===","||r.peek()==="[")throw new Be(`missing value for key "${e}"`,r.pos,r.input);let{value:n,flags:i}=IA(r,t);if(t==="/=")try{new RegExp(n,i)}catch(s){throw new Be(`invalid regex "${n}"${i?` with flags "${i}"`:""}: ${s.message}`,r.pos,r.input)}let o={key:e,op:t,value:n};return i!==void 0&&(o.flags=i),o}function AA(r){let e="";for(;!r.eof()&&r.peek()!=="]";)e+=r.next();if(e=e.trim(),e==="last")return-1;if(/^-?\d+$/.test(e))return parseInt(e,10);throw new Be(`invalid index "${e}" (expected N, -N, or "last")`,r.pos,r.input)}function Ds(r){if(typeof r!="string")throw new Be("input must be a string",0,String(r));let e=new af(r),t=[];if(Mr(e),e.eof())throw new Be("empty selector",e.pos,r);for(t.push(lv(e));Mr(e),e.peek()===",";){if(e.next(),Mr(e),e.eof()||e.peek()===",")throw new Be("expected clause after comma",e.pos,r);t.push(lv(e))}let n;if(Mr(e),e.peek()==="["){if(e.next(),n=AA(e),Mr(e),e.peek()!=="]")throw new Be("expected ']' after index",e.pos,r);e.next(),Mr(e)}if(!e.eof())throw new Be(`unexpected trailing input "${e.input.slice(e.pos)}"`,e.pos,r);return{clauses:t,index:n,raw:r}}function TA(r,e){if(r==null)return;if(e==="text"){let n=r.originalText??r.text;return n==null?void 0:String(n)}if(e==="desc"||e==="description"){let n=r.description;return n==null?void 0:String(n)}let t=r[e];return t==null?void 0:String(t)}function NA(r,e){let t=TA(r,e.key);if(t===void 0)return!1;switch(e.op){case"=":return t===e.value;case"*=":return t.includes(e.value);case"^=":return t.startsWith(e.value);case"$=":return t.endsWith(e.value);case"/=":try{return(e.flags?new RegExp(e.value,e.flags):new RegExp(e.value)).test(t)}catch{return!1}default:return!1}}function nl(r,e){let t=[],n=[r];for(;n.length>0;){let i=n.pop(),o=i.attributes??null;e.clauses.every(a=>NA(o,a))&&t.push(i);let s=i.children;if(s)for(let a=s.length-1;a>=0;a--)n.push(s[a])}return t}function io(r,e){return e===void 0?r[0]:e>=0?r[e]:r[r.length+e]}import{DOMParser as _A}from"@xmldom/xmldom";import{select as MA}from"xpath";var OA=["id","key","originalText","description","enabled","focused","checked","selected","visible","clickable","longClickable","scrollable","checkable","accessibilityLevel","hitTestBehavior","bounds"];function LA(r){if(!r)return"node";let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return/^[0-9]/.test(e)&&(e="_"+e),e||"node"}var FA=/&/g,$A=/</g,jA=/>/g,HA=/"/g,UA=/'/g;function il(r){return r.replace(FA,"&").replace($A,"<").replace(jA,">").replace(HA,""").replace(UA,"'")}function BA(r){let e=[],t=typeof r.type=="string"?r.type:"";t&&e.push(` type="${il(t)}"`);let n=r.originalText??r.text;n!=null&&n!==""&&e.push(` text="${il(String(n))}"`);for(let o of OA){let s=r[o];s==null||s===""||e.push(` ${o}="${il(String(s))}"`)}let i=r.description;return i!=null&&i!==""&&e.push(` desc="${il(String(i))}"`),e.join("")}function dv(r){let e=r.attributes??{},t=LA(typeof e.type=="string"?e.type:void 0),n=BA(e),i=r.children??[];return i.length===0?`<${t}${n}/>`:`<${t}${n}>${i.map(dv).join("")}</${t}>`}function WA(r){return`<?xml version="1.0" encoding="UTF-8"?>${dv(r)}`}function VA(r){if(!r)return;let e=r.match(/-?\d+/g);if(!e||e.length<4)return;let[t,n,i,o]=e.map(Number);return[t,n,i,o]}function GA(r){return typeof r!="object"||r===null?!1:r.nodeType===1}function qA(r){let e=i=>{let o=r.getAttribute(i);return o===""||o===null?void 0:o},t={},n=r.attributes;if(n)for(let i=0;i<n.length;i++){let o=n[i];o&&(t[o.name]=o.value)}return{type:e("type")??r.tagName,id:e("id"),key:e("key"),text:e("text"),originalText:e("originalText"),description:e("description")??e("desc"),enabled:e("enabled"),focused:e("focused"),checked:e("checked"),selected:e("selected"),visible:e("visible"),clickable:e("clickable"),longClickable:e("longClickable"),scrollable:e("scrollable"),checkable:e("checkable"),accessibilityLevel:e("accessibilityLevel"),hitTestBehavior:e("hitTestBehavior"),bounds:VA(e("bounds")),attributes:t}}function cf(r,e){if(typeof e!="string"||e.trim()==="")throw new Error("xpath expression must be a non-empty string");let t=WA(r),n=new _A().parseFromString(t,"text/xml"),i=MA(e,n);if(!Array.isArray(i))throw new Error(`xpath "${e}" did not return a node-set; use a path expression like //Button[@text='\u767B\u5F55']`);let o=[];for(let s of i)GA(s)&&o.push(qA(s));return o}function ol(r){return typeof r=="string"&&r.trimStart().startsWith("xpath=")}function sl(r){return r.trimStart().slice(6)}function al(r){return new Promise(e=>setTimeout(e,r))}function lf(r,e){let t=r.attributes??{};return{index:e,id:t.id||void 0,key:t.key||void 0,type:t.type||void 0,text:t.originalText||t.text||void 0,description:t.description||void 0,enabled:t.enabled||void 0,focused:t.focused||void 0,checked:t.checked||void 0,selected:t.selected||void 0,visible:t.visible||void 0,clickable:t.clickable||void 0,longClickable:t.longClickable||void 0,scrollable:t.scrollable||void 0,checkable:t.checkable||void 0,bounds:tl(t.bounds),attributes:t}}function uv(r,e){return{index:e,id:r.id,key:r.key,type:r.type,text:r.text,description:r.description,enabled:r.enabled,focused:r.focused,checked:r.checked,selected:r.selected,visible:r.visible,clickable:r.clickable,longClickable:r.longClickable,scrollable:r.scrollable,checkable:r.checkable,bounds:r.bounds,attributes:r.attributes}}function cl(r){return r.startsWith("base64=")?Buffer.from(r.slice(7).trim(),"base64").toString("utf8"):r}var zA=new Set(["text","desc","description"]),xs=[];function fv(r,e){if(r.attributes)for(let t of Object.keys(r.attributes))e.add(t);if(r.children)for(let t of r.children)fv(t,e)}function mv(r,e){let t=new Set;fv(r,t);let n=[];for(let i of e)zA.has(i.key)||t.has(i.key)||n.push(i.key);return n}function pv(r,e){let t=mv(r,e);for(let n of t)xs.push(`WARNING: attribute "${n}" not found in any node of the layout tree. No matches will be returned for this key.`)}function df(){return xs.splice(0)}var oo=class{dumper;constructor(e){this.dumper=new _r(e)}async find(e,t,n){xs.splice(0);let i=cl(t);if(ol(i))return this.runXpathFind(e,sl(i),n);let o=Ds(i);return this.runFind(e,o,n)}async runFind(e,t,n){let i=n?.timeoutMs??3e3,o=300,s=Date.now(),a=[],c=!1,l=!1;for(;!c;){let h=await this.dumper.dumpRawTree(e,n?.window);if(l||(pv(h,t.clauses),l=!0),a=nl(h,t),c=n?.all?a.length>0:io(a,t.index)!==void 0,c)break;if(Date.now()-s>=i)throw new Error(`Timed out (${i}ms) waiting for selector: ${t.raw}`);await al(o)}if(n?.all)return a.map((h,y)=>lf(h,y));let d=io(a,t.index);if(!d){let h=a.length,y=t.index===void 0?0:t.index;throw new Error(`Index ${y} out of range (matched ${h} element(s)) for selector: ${t.raw}`)}return[lf(d,t.index??0)]}async runXpathFind(e,t,n){let i=n?.timeoutMs??3e3,o=300,s=Date.now(),a=[],c=!1;for(;!c;){let l=await this.dumper.dumpRawTree(e,n?.window);if(a=cf(l,t),c=a.length>0,c)break;if(Date.now()-s>=i)throw new Error(`Timed out (${i}ms) waiting for xpath: ${t}`);await al(o)}return n?.all?a.map((l,d)=>uv(l,d)):[uv(a[0],0)]}async waitForAppearance(e,t,n,i){xs.splice(0);let o=cl(t);if(ol(o))return(await this.runXpathFind(e,sl(o),{timeoutMs:n,window:i}))[0];let s=Ds(o);return await this.runWaitFor(e,s,n,i,!0)}async waitForDisappear(e,t,n,i){xs.splice(0);let o=cl(t);if(ol(o))return this.runXpathWaitFor(e,sl(o),n,i,!1);let s=Ds(o);await this.runWaitFor(e,s,n,i,!1)}async runWaitFor(e,t,n,i,o){let a=Date.now(),c=!1;for(;;){let l=await this.dumper.dumpRawTree(e,i);c||(pv(l,t.clauses),c=!0);let d=nl(l,t),h=io(d,t.index)!==void 0;if(o&&h){let y=io(d,t.index);return lf(y,t.index??0)}if(!o&&!h)return;if(Date.now()-a>=n)throw new Error(`Timed out (${n}ms) waiting for selector to ${o?"appear":"disappear"}: ${t.raw}`);await al(300)}}async runXpathWaitFor(e,t,n,i,o){let a=Date.now();for(;;){let c=await this.dumper.dumpRawTree(e,i),d=cf(c,t).length>0;if(o&&d||!o&&!d)return;if(Date.now()-a>=n)throw new Error(`Timed out (${n}ms) waiting for xpath to ${o?"appear":"disappear"}: ${t}`);await al(300)}}};import ot from"fs";import Le from"path";import{randomUUID as JA}from"crypto";function hv(r,e){let t=["-t",r.serial,"shell","snapshot_display"];return r.display!==void 0&&t.push("-i",r.display),t.push("-f",r.remotePath),e&&t.push("-t",e),t}function gv(r,e){return[r,e].filter(Boolean).join(`
|
|
60
|
+
`).trim()}function yv(r){return r.replace(/(Tips:\s*supported\s+displayIds)\s*:?[ \t]*(?:\r?\n[ \t]*)?(\d+(?:(?:[ \t]*,[ \t]*|[ \t]+|\r?\n[ \t]*)\d+)*)/gi,(e,t,n)=>`${t}: ${n.match(/\d+/g)?.join(", ")??n}`)}function wv(r){let e=String.raw`invalid|not found|not exist|does not exist|out of range|unsupported`;return new RegExp(String.raw`display(?:\s*id)?.*(?:${e})`,"is").test(r)||new RegExp(String.raw`(?:${e}).*display(?:\s*id)?`,"is").test(r)}function vv(r){let e=r.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),n=Number(t[4]);return Number.isFinite(n)?n:void 0}function KA(){return String(Date.now())}function uf(r){let e;try{e=ot.statSync(r)}catch(t){let n=t.code;throw n==="ENOENT"?new Error(`Screenshot directory does not exist: ${r}`,{cause:t}):n==="EACCES"||n==="EPERM"?new Error(`Screenshot directory is not writable: ${r}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${n?` (${n})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${r}`);try{ot.accessSync(r,ot.constants.W_OK|ot.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${r}`,{cause:t})}}function pf(r,e){try{throw ot.lstatSync(r),new Error(`Screenshot file already exists: ${r}`)}catch(t){let n=t.code;if(n==="ENOENT")return;throw n==="EACCES"||n==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!n?t:new Error(`Invalid screenshot path: ${t.message}${n?` (${n})`:""}`,{cause:t})}}function bv(r){if(!ot.existsSync(r))throw new Error(`Screenshot file was not created: ${r}`);let e=ot.statSync(r);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${r}`);let t=ot.readFileSync(r).subarray(0,8),n=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(n))throw new Error(`Screenshot file is not a valid PNG: ${r}`)}function Sv(r){try{return bv(r),!0}catch{return!1}}function Ev(r){let e=[];for(let t of ot.readdirSync(r,{withFileTypes:!0})){let n=Le.join(r,t.name);if(t.isDirectory()){e.push(...Ev(n));continue}t.isFile()&&Sv(n)&&e.push(n)}return e}function YA(r,e){let t=Le.join(r,Le.basename(e));if(Sv(t))return t;let n=Ev(r);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple screenshot files were received in ${r}.`)}function XA(r,e){try{ot.copyFileSync(r,e,ot.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}bv(e)}var ni=class{constructor(e){this.toolProvider=e}resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),n=Le.resolve(t);try{if(ot.statSync(n).isDirectory()){uf(n);let o=Le.join(n,`screenshot-${KA()}.png`);return pf(o,n),o}}catch(o){if(o.code!=="ENOENT")throw o}if(Le.extname(n).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${n}`);let i=Le.dirname(n);return uf(i),pf(n,i),n}async captureToPath(e,t,n){let i=Le.dirname(Le.resolve(t));uf(i),pf(Le.resolve(t),i);let o=`/data/local/tmp/devecocli-${JA()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:Le.resolve(t),remotePath:o,display:n})}async capture(e){try{await this.createRemoteScreenshot(e),await this.receiveScreenshotFile(e)}finally{await this.removeRemoteScreenshot(e)}}async getRemoteScreenshotSize(e){let t=["-t",e.serial,"shell","ls","-l",e.remotePath];f(`Executing: ${e.hdcPath} ${t.join(" ")}`);let n=await C(e.hdcPath,t);return n.exitCode===0?vv(n.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let n=hv(e,t);f(`Executing: ${e.hdcPath} ${n.join(" ")}`);let i=await C(e.hdcPath,n),o=await this.getRemoteScreenshotSize(e);return{created:o!==void 0&&o>0,output:yv(gv(i.stdout,i.stderr))}}async createRemoteScreenshot(e){let t="";for(let n of[void 0,"png"]){let i=await this.tryCreateRemoteScreenshot(e,n);if(i.created)return;if(e.display!==void 0&&wv(i.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
|
|
58
61
|
snapshot_display output:
|
|
59
62
|
${i.output}`);i.output&&(t=i.output)}throw new Error(t?`Screenshot was not created on device: ${e.remotePath}.
|
|
60
63
|
snapshot_display output:
|
|
61
|
-
${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,r){let i=["-t",e.serial,"file","recv",e.remotePath,r];p(`Executing: ${e.hdcPath} ${i.join(" ")}`);let o=await ie(e.hdcPath,i);return o.exitCode!==0&&p(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),IP(t,e.remotePath)}async receiveScreenshotFile(e){let t=Ge.mkdtempSync(Ae.join(Ae.dirname(e.localPath),".devecocli-screenshot-"));try{let r=await this.tryReceiveScreenshot(e,t,Ae.join(t,Ae.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Ae.join(t,"screenshot.png"));if(!r)throw new Error(`Screenshot file was not created in ${t}.`);AP(r,e.localPath)}finally{Ge.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];p(`Executing: ${e.hdcPath} ${t.join(" ")}`),await ie(e.hdcPath,t)}};import Yf from"path";import{randomBytes as lC}from"crypto";import*as Vi from"fs";import*as yf from"path";import{homedir as DP}from"os";var RP="deveco-cli",gf,$l=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function TP(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":dl(n))||yf.join(DP(),".local","share",RP);try{return ls(t)}catch(r){throw new $l(r instanceof Error?r.message:String(r))}}function W(){if(gf!==void 0)return gf;let n=TP();try{if(Vi.existsSync(n))return Vi.realpathSync(n)}catch{}return n}async function nt(n,e){let r=await new yr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}var Gi="com.huawei.hmos.screenrecorder",nn="com.huawei.hmos.screenrecorder.ServiceExtAbility",vf="/data/local/tmp",w=class extends Error{constructor(t,r=t,i){super(r,i);this.code=t;this.name="ScreenRecordError"}};var jl=/^\s*uri \[([^\]]*)\]\s*$/,xP=/^\s*uri \[/,NP=/AbilityRecord ID\s*[:#]\s*(\d+)/,LP=/start time \[(\d+)\]/,MP=/bundle name \[([^\]]*)\]/,OP=/main name \[([^\]]*)\]/,_P=/\[(?:Fail|E\d{5,})\]|^\s*(?:error|Error)(?::|\s)/m,FP=nn.slice(nn.lastIndexOf(".")+1);function $P(n){let e=[],t;for(let r of n.split(/\r?\n/))jl.test(r)?(t=[r],e.push(t)):t&&t.push(r);return e}function jP(n){let e={};for(let t of n){let r=jl.exec(t);if(r){e.uri=r[1].trim();continue}let i=NP.exec(t);if(i&&(e.id=Number(i[1]),!Number.isSafeInteger(e.id)))throw new w("DUMP_PARSE_FAILED",`Unparseable AbilityRecord ID in aa dump output: ${i[1]}`);let o=LP.exec(t);if(o){e.startedAtMs=Number(o[1]);continue}let s=MP.exec(t);if(s){e.bundleName=s[1].trim();continue}let a=OP.exec(t);a&&(e.mainName=a[1].trim())}return e}function wf(n){let e=n.mainName;if((!n.bundleName||!e)&&n.uri){let t=n.uri.split("/").filter(Boolean);t.length>=3&&(n.bundleName??=t[0],e??=t[t.length-1])}return{bundleName:n.bundleName,abilityName:e}}function HP(n){let{bundleName:e,abilityName:t}=wf(n);return e!==Gi||!t?!1:t===nn||t===FP}function UP(n){if(_P.test(n))throw new w("DUMP_PARSE_FAILED",`Unexpected aa dump output: ${n.trim().split(/\r?\n/)[0]??""}`);if(!n.includes("ExtensionRecords")&&!n.includes("AbilityRecord ID"))throw new w("DUMP_PARSE_FAILED","aa dump output has no recognizable extension-record structure");for(let t of n.split(/\r?\n/))if(xP.test(t)&&!jl.test(t))throw new w("DUMP_PARSE_FAILED","aa dump output has an unterminated uri line; output may be truncated");let e=$P(n);if(e.length===0&&n.replace(/ExtensionRecords:\s*/,"").trim()!=="")throw new w("DUMP_PARSE_FAILED","aa dump output has no complete ability records; output may be truncated");return e}function Sf(n){if(!n.trim())throw new w("DUMP_PARSE_FAILED","aa dump output is empty; the device state is unknown");let e=new Map;for(let t of UP(n)){let r=jP(t);if(!HP(r))continue;if(r.id===void 0)throw new w("DUMP_PARSE_FAILED","Recorder ability block is missing its AbilityRecord ID");let{bundleName:i,abilityName:o}=wf(r);e.set(r.id,{abilityRecordId:r.id,bundleName:i??Gi,abilityName:o??nn,startedAtMs:r.startedAtMs})}return[...e.values()]}function Hl(n,e){if(n.length>1)throw new w("AMBIGUOUS_DEVICE_STATE",`Multiple screen recorder ability records: ${n.map(r=>r.abilityRecordId).join(", ")}`);let t=n[0];return t?{status:e?.abilityRecordId===t.abilityRecordId?"recording":"busy",activeId:t.abilityRecordId,session:e}:{status:"idle",session:e}}function on(n,e){return!n||!e?n===e:n.fileName===e.fileName&&n.abilityRecordId===e.abilityRecordId&&n.startTime===e.startTime&&n.localPath===e.localPath}function bf(n){return n.status==="recording"?{plan:"error",error:new w("CLI_RECORDING_ACTIVE","A CLI recording session is already running; run stop first")}:n.status==="busy"?{plan:"error",error:new w("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; run stop --force first")}:n.session?{plan:"discard-first",session:n.session}:{plan:"start-new"}}function Ef(n){return n.status==="idle"&&!n.session?{plan:"start-new"}:{plan:"error",error:new w("STATE_CHANGED","Device state changed while discarding the interrupted registration; not starting")}}function Pf(n,e){return n.status==="busy"?e?{plan:"force-stop-external",activeId:n.activeId}:{plan:"error",error:new w("EXTERNAL_RECORDING","Recording was not started by this CLI. Stop it on the device or run stop --force.")}:n.session?{plan:"finalize-session",session:n.session}:{plan:"error",error:new w("NO_CLI_SESSION","No CLI recording session on this device")}}function Cf(n,e,t){return on(n,e)?{plan:"proceed"}:t==="interactive"?{plan:"completed-elsewhere"}:{plan:"error",error:new w("SESSION_CHANGED","The recording session changed; leaving the current one untouched")}}function kf(n){return n.status==="busy"?{plan:"error",error:new w("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; not toggling")}:n.status==="recording"?{plan:"stop-recording"}:{plan:"retrieve"}}function If(n,e){if(n.length===0)return{outcome:"gone"};if(n.length>1)return{outcome:"error",error:new w("STATE_CHANGED","Multiple recorder records while confirming stop; not toggling again")};let t=n[0].abilityRecordId;return t!==e?{outcome:"error",error:new w("STATE_CHANGED",`A different recording (ID ${t}) appeared while stopping; leaving it alone`)}:{outcome:"still-recording",activeId:t}}function Af(n){return n.length===1?{outcome:"confirmed",record:n[0]}:n.length>1?{outcome:"error",error:new w("AMBIGUOUS_DEVICE_STATE","Multiple recorder records after start; refusing to pick one")}:{outcome:"pending"}}function Df(n,e){if(n.length===0)return{plan:"already-stopped"};if(n.length>1)return{plan:"error",error:new w("AMBIGUOUS_DEVICE_STATE","Multiple recorder records; refusing to force-stop")};let t=n[0];return e!==void 0&&t.abilityRecordId!==e?{plan:"error",error:new w("STATE_CHANGED","The recording changed while stopping; leaving it alone")}:{plan:"stop",currentId:t.abilityRecordId,startedAtMs:t.startedAtMs}}function Rf(n){return n.status==="idle"&&n.session?{status:"idle",note:"interrupted session found; retrievable via ui screenrecord stop"}:{status:n.status}}function Tf(n,e){return!on(n.session,e)||n.status!=="recording"}function Ul(n,e){return n.startTime+e}function xf(n,e,t){return t+Math.max(0,e-n)}import vr from"fs";import Ff from"path";import{randomBytes as GP}from"crypto";import{lock as qP}from"proper-lockfile";import qi from"path";var BP=/^[A-Za-z0-9][A-Za-z0-9.-]*\.mp4$/;function Fn(n){return Buffer.from(n,"utf8").toString("hex")}function sn(n,e){return String(n).padStart(e,"0")}function Nf(n){return`${sn(n.getFullYear(),4)}${sn(n.getMonth()+1,2)}${sn(n.getDate(),2)}-${sn(n.getHours(),2)}${sn(n.getMinutes(),2)}${sn(n.getSeconds(),2)}${sn(n.getMilliseconds(),3)}`}function WP(n){return n.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/[. ]+$/,"").replace(/^[. ]+/,"")||"device"}function Lf(n,e){if(!/^[a-z0-9]{4}$/.test(e))throw new w("INVALID_RECORDING_PATH",`Internal: bad random suffix ${JSON.stringify(e)}`);return`devecocli-${Nf(n)}-${e}.mp4`}function Mf(n,e,t){return`${WP(n)}-${Nf(e)}-${t}.mp4`}function Of(n,e){if(!BP.test(n))throw new w("INVALID_RECORDING_PATH",`Unsafe device file name: ${JSON.stringify(n)}`);return`${vf}/devecocli-${e}-${n}`}var VP=20;function _f(n){let e=qi.dirname(n),t=qi.extname(n),r=qi.basename(n,t),i=[n];i.push(qi.join(e,`${r}-recovered${t}`));for(let o=2;o<VP;o++)i.push(qi.join(e,`${r}-recovered-${o}${t}`));return i}var zP=5*6e4,JP=5*6e4,YP=1e4,KP=6e4,Bl=200;function XP(n){if(!Number.isInteger(n)||n<=0)return"unknown";try{return process.kill(n,0),"alive"}catch(e){let t=e.code;return t==="ESRCH"?"dead":t==="EPERM"?"alive":"unknown"}}function $f(n){return new Promise(e=>setTimeout(e,n))}function ZP(){return GP(8).toString("hex")}async function jf(n){let e;try{e=await vr.promises.readFile(n,"utf8")}catch{return}try{let t=JSON.parse(e);return typeof t.token=="string"?t.token:void 0}catch{return}}var Os=class{constructor(e,t={}){this.recordDir=e;this.releaseGuardWaitMs=t.releaseGuardWaitMs??YP}releaseGuardWaitMs;lockPath(e){return Ff.join(this.recordDir,`${Fn(e)}.lock`)}guardPath(e){return Ff.join(this.recordDir,`${Fn(e)}.guard`)}async withDeviceLock(e,t,r=KP){let i=await this.acquire(e,r),o;try{o=await t(i)}catch(s){try{await this.releaseOwned(e,i)}catch(a){p(`lock release failed after action error: ${a.message}`)}throw s}return await this.releaseOwned(e,i),o}async withGuard(e,t,r=0){let i=Date.now()+r;for(;;){let o;try{o=await qP(this.guardPath(e),{realpath:!1,stale:zP,update:1e3,retries:0})}catch(s){if(s.code!=="ELOCKED"||Date.now()>=i)throw s;await $f(Math.min(Bl,i-Date.now()));continue}try{return await t()}finally{await o()}}}async acquire(e,t){await vr.promises.mkdir(this.recordDir,{recursive:!0});let r=ZP(),i=this.lockPath(e),o=Date.now()+t;for(;;){let s=!1;try{await this.withGuard(e,async()=>{s=await this.tryCreateOrReclaim(i,r)})}catch(a){if(a.code!=="ELOCKED")throw a}if(s)return this.buildLease(i,r);if(Date.now()+Bl>o)throw new w("LOCK_BUSY",`Timed out waiting ${t}ms for the device lock (${e})`);await $f(Bl)}}async tryCreateOrReclaim(e,t){let r;try{r=await vr.promises.open(e,"wx")}catch(i){if(i.code!=="EEXIST")throw i;return await this.reclaimIfDead(e),!1}try{let i={pid:process.pid,createdAt:Date.now(),token:t};await r.writeFile(JSON.stringify(i)),await r.sync()}finally{await r.close()}return!0}async reclaimIfDead(e){let t,r;try{t=await vr.promises.readFile(e,"utf8"),r=await vr.promises.stat(e)}catch(o){if(o.code==="ENOENT")return;throw o}let i;try{let o=JSON.parse(t);typeof o.pid=="number"&&typeof o.createdAt=="number"&&typeof o.token=="string"&&(i=o)}catch{}if(i){XP(i.pid)==="dead"&&await vr.promises.unlink(e);return}Date.now()-r.mtimeMs>JP&&await vr.promises.unlink(e)}buildLease(e,t){let r=new AbortController;return{token:t,signal:r.signal,assertOwned:async()=>{if(await jf(e)!==t)throw r.abort(),new w("LOCK_LOST","Lost the device lock; aborting this operation")}}}async releaseOwned(e,t){let r=this.lockPath(e);try{await this.withGuard(e,async()=>{await jf(r)===t.token&&await vr.promises.unlink(r)},this.releaseGuardWaitMs)}catch(i){throw new w("LOCK_RELEASE_FAILED",`Could not release the device lock (${e}): ${i.message}. The lock stays in place; it is reclaimed by the dead-PID or corrupt-age rule once this process exits.`,{cause:i})}}};import{execa as QP}from"execa";var Wl=15e3,Hf=10*6e4,eC=3,Uf=400;function tC(n){return new Promise(e=>setTimeout(e,n))}function rC(n){return async(e,t)=>{p(`Executing: ${n} ${e.join(" ")}`);let r=await QP(n,e,{reject:!1,timeout:t.timeoutMs??Wl,cancelSignal:t.signal,stdout:"pipe",stderr:"pipe"});return{stdout:typeof r.stdout=="string"?r.stdout:"",stderr:typeof r.stderr=="string"?r.stderr:"",exitCode:r.exitCode??-1}}}var _s=class n{runner;constructor(e){this.runner=rC(e)}async runReadOnly(e,t){let r={stdout:"",stderr:"",exitCode:-1},i=t!==void 0?Date.now()+t:void 0;for(let o=0;o<eC;o++){let s=i!==void 0?i-Date.now():void 0;r=await this.runner(e,s===void 0?{}:{timeoutMs:Math.max(1,s)});let a=`${r.stdout}
|
|
62
|
-
${
|
|
63
|
-
${e.stderr}`.trim();if(e.exitCode!==0||
|
|
64
|
-
`)[0]??""}`)}async observeOnce(e,t){let
|
|
65
|
-
`)[0]??""}`);return Math.round(i*1e3)}async toggleOnce(e,t,
|
|
66
|
-
`)[0]??""}`);let s=[...i.stdout.matchAll(/"(file:\/\/[^"]+)"/g)].map(c=>c[1]),a=Number(o[1]);if(a!==0){if(a>1||s.length>1)throw new
|
|
67
|
-
`)[0]??""}`)}async receiveFile(e,t,
|
|
68
|
-
`)[0]??""}`)}async removeStaging(e,t){return(await this.runReadOnly(["-t",e,"shell","rm","-f",t],Wl)).exitCode===0}};import zt from"fs";import Ft from"path";import{createFile as nC}from"mp4box";var Wf=".devecocli-record-";function $n(n,e){return new w("INVALID_RECORDING_PATH",e instanceof Error?`${n}: ${e.message}`:n,e instanceof Error?{cause:e}:void 0)}async function Vl(n){try{return{stat:await zt.promises.stat(n)}}catch(e){let t=e.code;return t==="ENOENT"?null:{code:t??"UNKNOWN"}}}async function Bf(n){let e=await Vl(n);if(!e)throw $n(`Directory does not exist: ${n}`);if("code"in e)throw $n(`Directory is not accessible: ${n}`);if(!e.stat.isDirectory())throw $n(`Path is not a directory: ${n}`);try{await zt.promises.access(n,zt.constants.W_OK)}catch(t){throw $n(`Directory is not writable: ${n}`,t)}}async function Gl(n){if(await Vl(n))throw new w("DESTINATION_EXISTS",`Destination already exists: ${n}`)}async function ql(n,e,t,r){if(!n?.trim())throw $n("--path is required.");let i=Ft.resolve(n.trim()),o=await Vl(i);if(o&&"stat"in o&&o.stat.isDirectory()){await Bf(i);let a=Ft.join(i,Mf(e,t,r));return await Gl(a),a}if(o)throw new w("DESTINATION_EXISTS",`Destination already exists: ${i}`);if(Ft.extname(i).toLowerCase()!==".mp4")throw $n(`Destination must be an existing directory or a new .mp4 file: ${i}`);let s=Ft.dirname(i);return await Bf(s),i}async function Vf(n){return zt.promises.mkdtemp(Ft.join(Ft.dirname(n),Wf))}var iC=4*1024*1024;async function oC(n){let e=await zt.promises.open(n,"r");try{let{size:t}=await e.stat(),r=nC(),i=0;for(let s=0;s<t;){let a=Math.min(iC,t-s),c=Buffer.alloc(a),{bytesRead:l}=await e.read(c,0,a,s);if(l<=0)break;let d=c.buffer.slice(c.byteOffset,c.byteOffset+l);d.fileStart=s,i=r.appendBuffer(d,s+l>=t),s+=l}r.flush();let o=r.getBox("moov");return{size:t,complete:i===t,hasMovieHeader:o?.mvhd!==void 0,videoTrackCount:o?.mvhd!==void 0?r.getInfo().videoTracks.length:0}}finally{await e.close()}}async function Gf(n){let e;try{e=await oC(n)}catch(t){throw new w("SAVE_FAILED",`Cannot inspect received file: ${t.message}`,{cause:t})}if(e.size===0)throw new w("MEDIA_NOT_READY","Received file is empty");if(!e.complete||!e.hasMovieHeader)throw new w("MEDIA_NOT_READY","Received file is not a complete MP4");if(e.videoTrackCount<1)throw new w("MEDIA_NOT_READY","Received file has no video track");return e.size}async function sC(n){let e=await zt.promises.open(n,"r+");try{await e.sync()}finally{await e.close()}}async function aC(n){try{let e=await zt.promises.open(Ft.dirname(n),"r");try{await e.sync()}finally{await e.close()}}catch{}}async function qf(n,e){await sC(n);for(let t of _f(e))try{return await zt.promises.link(n,t),await aC(t),t}catch(r){if(r.code==="EEXIST")continue;throw new w("SAVE_FAILED",`Cannot publish recording to ${t}: ${r.message}`,{cause:r})}throw new w("DESTINATION_UNAVAILABLE",`All recovery names are taken near ${e}`)}async function zf(n,e){let t=Ft.dirname(e),r=Ft.basename(n);Ft.dirname(n)!==t||!r.startsWith(Wf)||await zt.promises.rm(n,{recursive:!0,force:!0}).catch(()=>{})}import Jt from"fs";import Fs from"path";import{randomBytes as cC}from"crypto";function Jf(n,e){let t=n,r=i=>new w("SESSION_CORRUPT",`Invalid recording session ${i} in ${e}`);if(!t||typeof t!="object")throw r("object");if(typeof t.fileName!="string"||t.fileName.length===0||t.fileName!==Fs.basename(t.fileName)||t.fileName.includes(".."))throw r("fileName");if(typeof t.abilityRecordId!="number"||!Number.isSafeInteger(t.abilityRecordId)||t.abilityRecordId<=0)throw r("abilityRecordId");if(typeof t.startTime!="number"||!Number.isFinite(t.startTime))throw r("startTime");if(typeof t.localPath!="string"||t.localPath.length===0||!Fs.isAbsolute(t.localPath))throw r("localPath");return{fileName:t.fileName,abilityRecordId:t.abilityRecordId,startTime:t.startTime,localPath:t.localPath}}var $s=class{constructor(e){this.recordDir=e}sessionPath(e){return Fs.join(this.recordDir,`${Fn(e)}.json`)}async read(e){let t=this.sessionPath(e),r;try{r=await Jt.promises.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return;throw new w("SESSION_CORRUPT",`Cannot read recording session: ${o.message}`,{cause:o})}let i;try{i=JSON.parse(r)}catch(o){throw new w("SESSION_CORRUPT",`Recording session file is not valid JSON: ${t}`,{cause:o})}return Jf(i,t)}async createAtomic(e,t,r){await Jt.promises.mkdir(this.recordDir,{recursive:!0});let i=this.sessionPath(e),o=Fs.join(this.recordDir,`${Fn(e)}.${cC(6).toString("hex")}.tmp`),s=JSON.stringify(Jf(t,"input")),a;try{a=await Jt.promises.open(o,"wx")}catch(c){throw new w("SESSION_PUBLISH_FAILED",`Cannot create session temp file: ${c.message}`,{cause:c})}try{await a.writeFile(s),await a.sync()}catch(c){throw await a.close().catch(()=>{}),await Jt.promises.unlink(o).catch(()=>{}),new w("SESSION_PUBLISH_FAILED",`Cannot write session temp file: ${c.message}`,{cause:c})}await a.close();try{if(await r.assertOwned(),await this.exists(i))throw new w("SESSION_CHANGED",`A recording session was created concurrently for ${e}`);await Jt.promises.link(o,i),await this.syncDir()}finally{await Jt.promises.unlink(o).catch(()=>{})}}async deleteIfSame(e,t,r){await r.assertOwned();let i=await this.read(e);if(i){if(!on(i,t))throw new w("SESSION_CHANGED","The recording session changed hands; leaving the new record untouched");await Jt.promises.unlink(this.sessionPath(e)),await this.syncDir()}}async exists(e){try{return await Jt.promises.lstat(e),!0}catch{return!1}}async syncDir(){try{let e=await Jt.promises.open(this.recordDir,"r");try{await e.sync()}finally{await e.close()}}catch{}}};var dC={startConfirmMs:1e4,stopConfirmMs:15e3,stopReadyMs:3e3,observeIntervalMs:250,foregroundPollMs:1e3,mediaReadyMs:3e4,mediaBackoffMs:[250,500,1e3,2e3],mediaRecvAttempts:3,lockWaitMs:6e4,interactiveLockWaitMs:10*6e4,foregroundFailureBudget:3},Kf=4e3;function zi(n){return new Promise(e=>setTimeout(e,n))}function js(){return lC(2).toString("hex")}var Xf=["SIGINT","SIGTERM","SIGHUP"];function uC(n,e){let t=()=>{n.requested||(n.requested=!0,e?.(),n.wake())};for(let r of Xf)process.on(r,t);return()=>{for(let r of Xf)process.off(r,t)}}var wr=class{constructor(e,t={}){this.toolProvider=e;let r=Yf.join(W(),"record");this.deps={store:t.store??new $s(r),lock:t.lock??new Os(r),device:t.device??new _s(e.hdcPath),timing:{...dC,...t.timing}}}deps;async startDetached(e,t){let r=await this.resolveTarget(e),i=await ql(t,r.name,new Date,js());return this.startSession(r,i)}async recordInteractively(e,t,r){let i=new Set,o={requested:!1,wake:()=>{for(let a of i)a()}},s=uC(o,r.onStopRequested);try{let a=await this.resolveTarget(e),c=await ql(t,a.name,new Date,js()),l=await this.startSession(a,c);return r.onStarted(),await this.waitForInteractiveCompletion(l,o,i)}finally{s()}}async waitForInteractiveCompletion(e,t,r){let i,o=()=>(i??=this.deps.lock.withDeviceLock(e.serial,a=>this.finalizeLocked(e.serial,e.session,"interactive",a),this.deps.timing.interactiveLockWaitMs),i),s=0;for(;;){if(t.requested)return await o();let a;try{a=await this.readSnapshot(e.serial),s=0}catch(c){if(s+=1,s>=this.deps.timing.foregroundFailureBudget)throw c;await this.waitPoll(t,r);continue}if(Tf(a,e.session))return await o();await this.waitPoll(t,r)}}async stopRecording(e,t){let r=await this.resolveTarget(e);return this.deps.lock.withDeviceLock(r.serial,async i=>{let o=await this.readSnapshot(r.serial),s=Pf(o,t);if(s.plan==="force-stop-external")return await this.stopExternal(r.serial,s.activeId,i),{kind:"external-stopped"};if(s.plan==="error")throw s.error;return this.finalizeLocked(r.serial,s.session,"stop-or-recover",i)},this.deps.timing.lockWaitMs)}async getRecordingStatus(e){let t=await this.resolveTarget(e);for(let r=0;r<3;r++){let i=await this.deps.store.read(t.serial),o=await this.deps.device.observeOnce(t.serial),s=await this.deps.store.read(t.serial);if(!on(i,s))continue;let a=Hl(o,s);return Rf(a)}throw new w("STATE_CHANGING","The recording session keeps changing; try again")}async resolveTarget(e){let t=await oe.from(this.toolProvider).getConnectedEntries();if(t.length===0)throw new w("NO_ACTIVE_DEVICES","No active devices found. Connect a physical device; screen recording does not support emulators.");let r=await nt(this.toolProvider,e),i=t.find(o=>o.serial===r);if(i?.isEmulator)throw new w("EMULATOR_NOT_SUPPORTED","Screen recording is only supported on physical devices");return{serial:r,name:i?.name??r}}async readSnapshot(e){let t=await this.deps.store.read(e),r=await this.deps.device.observeOnce(e);return Hl(r,t)}async startSession(e,t){return this.deps.lock.withDeviceLock(e.serial,r=>this.startSessionLocked(e,t,r),this.deps.timing.lockWaitMs)}async startSessionLocked(e,t,r){let i=await this.readSnapshot(e.serial),o=bf(i);if(o.plan==="error")throw o.error;if(o.plan==="discard-first"){await this.deps.store.deleteIfSame(e.serial,o.session,r);let s=await this.readSnapshot(e.serial),a=Ef(s);if(a.plan==="error")throw a.error}return this.toggleAndRegister(e,t,r)}async toggleAndRegister(e,t,r){await Gl(t);let i=Lf(new Date,js()),o=Date.now(),s=Date.now()+this.deps.timing.startConfirmMs;await r.assertOwned(),await this.deps.device.toggleOnce(e.serial,i,r,Math.max(1,s-Date.now()));let a=await this.waitForStarted(e.serial,s),c={fileName:i,abilityRecordId:a.abilityRecordId,startTime:o,localPath:t};return await this.registerSession(e.serial,c,r),{serial:e.serial,session:c}}async registerSession(e,t,r){try{await this.deps.store.createAtomic(e,t,r)}catch(i){throw await this.abortUnregistered(e,t,r),new w(i.code??"SESSION_PUBLISH_FAILED",`Recording started on device (file ${t.fileName}) but could not be registered: ${i.message}. Check the device gallery.`,{cause:i})}}async withinDeadline(e,t,r){try{return await r(Math.max(1,e-Date.now()))}catch(i){throw Date.now()>=e?t:i}}async waitForStarted(e,t){for(;;){let r=t-Date.now();if(r<=0)throw new w("START_CONFIRM_TIMEOUT","Device screen may be locked");let i=await this.withinDeadline(t,new w("START_CONFIRM_TIMEOUT","Device screen may be locked"),s=>this.deps.device.observeOnce(e,s)),o=Af(i);if(o.outcome==="error")throw o.error;if(o.outcome==="confirmed"){if(Date.now()>t)throw new w("START_CONFIRM_TIMEOUT","Device screen may be locked");return o.record}await zi(Math.min(this.deps.timing.observeIntervalMs,r))}}async observeActiveId(e,t,r){let i=await this.deps.device.observeOnce(e,r),o=If(i,t);if(o.outcome==="error")throw o.error;return o.outcome==="gone"?void 0:o.activeId}async waitForStopped(e,t,r){for(;;){let i=r-Date.now();if(i<=0)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(r,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),s=>this.observeActiveId(e,t,s))===void 0)return;await zi(Math.min(this.deps.timing.observeIntervalMs,i))}}async awaitStopReady(e,t,r,i){for(;;){let o=i-Date.now();if(o<=0)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(i,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),a=>this.observeActiveId(e,t,a))===void 0)return"vanished";if(Date.now()>=r){if(Date.now()>i)throw new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");return"ready"}await zi(Math.min(this.deps.timing.observeIntervalMs,r-Date.now(),o))}}async abortUnregistered(e,t,r){try{let i=Date.now()+this.deps.timing.stopConfirmMs,o=Ul(t,this.deps.timing.stopReadyMs);await this.awaitStopReady(e,t.abilityRecordId,o,i)==="ready"&&await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now()))}catch(i){p(`abortUnregistered: best-effort stop failed: ${i.message}`)}}async finalizeLocked(e,t,r,i){let o=await this.deps.store.read(e),s=Cf(o,t,r);if(s.plan==="completed-elsewhere")return{kind:"completed-elsewhere"};if(s.plan==="error")throw s.error;let a=await this.readSnapshot(e),c=kf(a);if(c.plan==="error")throw c.error;if(c.plan==="stop-recording"){let l=Date.now()+this.deps.timing.stopConfirmMs;return this.stopLiveRecording(e,t,i,l)}return this.retrieveAndPublish(e,t,i)}async stopLiveRecording(e,t,r,i){let o=Ul(t,this.deps.timing.stopReadyMs);return await this.awaitStopReady(e,t.abilityRecordId,o,i)==="vanished"?this.retrieveAndPublish(e,t,r):(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,i-Date.now())),await this.waitForStopped(e,t.abilityRecordId,i),this.retrieveAndPublish(e,t,r))}async stopExternal(e,t,r){let i=await this.deps.device.observeOnce(e),o=Df(i,t);if(o.plan==="already-stopped")return;if(o.plan==="error")throw o.error;let s=Date.now()+this.deps.timing.stopConfirmMs;o.startedAtMs!==void 0&&!await this.awaitForeignStopReady(e,o.currentId,o.startedAtMs,s)||(await r.assertOwned(),await this.deps.device.toggleOnce(e,void 0,r,Math.max(1,s-Date.now())),await this.waitForStopped(e,o.currentId,s))}async awaitForeignStopReady(e,t,r,i){let o=await this.withinDeadline(i,new w("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),c=>this.deps.device.readUptimeMs(e,c)),s=xf(o-r,this.deps.timing.stopReadyMs,Date.now());return await this.awaitStopReady(e,t,s,i)==="ready"}async retrieveAndPublish(e,t,r){let i=[],o=await this.waitForMediaUri(e,t.fileName),s=await Vf(t.localPath);try{let a=await this.receiveUntilValid(e,o,t,s,r,i);await r.assertOwned();let c=await qf(a,t.localPath);return await this.deleteSessionAfterSave(e,t,r,c),{kind:"saved",localPath:c,warnings:i}}finally{await zf(s,t.localPath)}}async waitForMediaUri(e,t){let r=Date.now()+this.deps.timing.mediaReadyMs,i=0;for(;;){let o=r-Date.now();if(o<=0)throw new w("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`);let s=await this.withinDeadline(r,new w("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`),c=>this.deps.device.queryMediaUri(e,t,c));if(s&&Date.now()<=r)return s;let a=Math.min(this.deps.timing.mediaBackoffMs[Math.min(i,this.deps.timing.mediaBackoffMs.length-1)]??Kf,Kf,o);i+=1,await zi(a)}}async receiveUntilValid(e,t,r,i,o,s){for(let a=0;a<this.deps.timing.mediaRecvAttempts;a++){await o.assertOwned();let c=Of(r.fileName,js()),l=await this.receiveOnce(e,t,c,i,r.fileName,o,s);try{return await Gf(l),l}catch(d){if(d.code!=="MEDIA_NOT_READY")throw d;p(`Received file incomplete (attempt ${a+1}); retrying export`),await zi(this.deps.timing.mediaBackoffMs[0]??250)}}throw new w("MEDIA_NOT_READY",`Received file for ${r.fileName} is incomplete after ${this.deps.timing.mediaRecvAttempts} attempts; session kept`)}async receiveOnce(e,t,r,i,o,s,a){let c=Yf.join(i,o);try{await this.deps.device.exportToStaging(e,t,r),await this.deps.device.receiveFile(e,r,c,s.signal)}finally{await this.deps.device.removeStaging(e,r)||a.push(`Failed to remove device staging file: ${r}`)}return c}async deleteSessionAfterSave(e,t,r,i){try{await this.deps.store.deleteIfSame(e,t,r)}catch(o){throw new w(o.code??"SESSION_DELETE_FAILED",`Recording saved to ${i}, but the session record could not be removed: ${o.message}. A later stop may create a recovered copy.`,{cause:o})}}async waitPoll(e,t){await new Promise(r=>{let i=setTimeout(()=>{t.delete(o),r()},this.deps.timing.foregroundPollMs),o=()=>{t.delete(o),clearTimeout(i),r()};t.add(o)})}};var Hs={left:"0",right:"1",up:"2",down:"3"};function Me(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function zl(n,e){n!==void 0&&Me(n,e)}function Zf(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Us(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Ji(n){if(n===void 0)return;let e=Number(n);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return n}function Qf(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function eh(n,e,t,r=!0){if(t&&!e)throw new Error("--window must be used with --id");if(n&&e)throw new Error("Coordinates and --id are mutually exclusive");if(r&&!n&&!e)throw new Error("Either provide x y coordinates or use --id")}function jn(n,e,t,r,i=!0){Zf(n,e),Us(t,"--id"),zl(n,"x"),zl(e,"y"),Qf(r),eh(n!==void 0,!!t,!!r,i)}async function $t(n){let e=await P.new(),t=await nt(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Hn(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new qt(n,e).listWindows({all:!0}),c=new tn(n);return pC(c,e,a,i,o)}async function pC(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new S(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await n.dumpFullTree(e,0,i,!1);return fC(s,r)}return mC(n,e,t,r)}async function mC(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of _n([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new S(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new S(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new S(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");return th(s[0].node,r)}function fC(n,e){let t=_n(n,e);if(t.length===0)throw new S(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new S(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return th(t[0],e)}function th(n,e){let t=n.bounds;if(!t)throw new S(`Node "${e}" has no bounds.`,"Node has no bounds.");let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function pt(n,e,t){let r=["-t",e,"shell",...t];p(`Executing: ${n} ${r.join(" ")}`);let i=await ie(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import{deflateSync as hC,inflateSync as gC}from"zlib";import yC from"fs";var rh=8,nh=32,vC=.06,wC=.04,Jl=10,Bs=class n{whiteBits=null;blackBits=null;analyzeRgb(e,t,r){if(e<8||t<8||r.length<e*t*3)return null;let i=this.cropChrome(e,t,r),o=this.hashBits(i.width,i.height,i.rgb),s=Math.min(this.hammingDistance(o,this.solidRefBits(255)),this.hammingDistance(o,this.solidRefBits(0)));return{phash:this.bitsToHex(o),hamming:s,isBlank:s<=Jl}}analyzeFile(e){let t;try{t=yC.readFileSync(e)}catch{return null}let r=this.decodePngRgb(t);return r?this.analyzeRgb(r.width,r.height,r.rgb):null}static encodePngRgb(e,t,r){let i=n.pngCrcTable(),o=[Buffer.from(`\x89PNG\r
|
|
64
|
+
${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,n){let i=["-t",e.serial,"file","recv",e.remotePath,n];f(`Executing: ${e.hdcPath} ${i.join(" ")}`);let o=await C(e.hdcPath,i);return o.exitCode!==0&&f(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),YA(t,e.remotePath)}async receiveScreenshotFile(e){let t=ot.mkdtempSync(Le.join(Le.dirname(e.localPath),".devecocli-screenshot-"));try{let n=await this.tryReceiveScreenshot(e,t,Le.join(t,Le.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Le.join(t,"screenshot.png"));if(!n)throw new Error(`Screenshot file was not created in ${t}.`);XA(n,e.localPath)}finally{ot.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];f(`Executing: ${e.hdcPath} ${t.join(" ")}`),await C(e.hdcPath,t)}};import eb from"path";import{randomBytes as AT}from"crypto";async function T(r,e){let n=await new dn(r).selectDevice(e);if(!n)throw new Error("No device selected. Use `devecocli device list` to see targets.");return n}var Is="com.huawei.hmos.screenrecorder",ii="com.huawei.hmos.screenrecorder.ServiceExtAbility",Pv="/data/local/tmp",S=class extends Error{constructor(t,n=t,i){super(n,i);this.code=t;this.name="ScreenRecordError"}};var ff=/^\s*uri \[([^\]]*)\]\s*$/,ZA=/^\s*uri \[/,QA=/AbilityRecord ID\s*[:#]\s*(\d+)/,eT=/start time \[(\d+)\]/,tT=/bundle name \[([^\]]*)\]/,rT=/main name \[([^\]]*)\]/,nT=/\[(?:Fail|E\d{5,})\]|^\s*(?:error|Error)(?::|\s)/m,iT=ii.slice(ii.lastIndexOf(".")+1);function oT(r){let e=[],t;for(let n of r.split(/\r?\n/))ff.test(n)?(t=[n],e.push(t)):t&&t.push(n);return e}function sT(r){let e={};for(let t of r){let n=ff.exec(t);if(n){e.uri=n[1].trim();continue}let i=QA.exec(t);if(i&&(e.id=Number(i[1]),!Number.isSafeInteger(e.id)))throw new S("DUMP_PARSE_FAILED",`Unparseable AbilityRecord ID in aa dump output: ${i[1]}`);let o=eT.exec(t);if(o){e.startedAtMs=Number(o[1]);continue}let s=tT.exec(t);if(s){e.bundleName=s[1].trim();continue}let a=rT.exec(t);a&&(e.mainName=a[1].trim())}return e}function Cv(r){let e=r.mainName;if((!r.bundleName||!e)&&r.uri){let t=r.uri.split("/").filter(Boolean);t.length>=3&&(r.bundleName??=t[0],e??=t[t.length-1])}return{bundleName:r.bundleName,abilityName:e}}function aT(r){let{bundleName:e,abilityName:t}=Cv(r);return e!==Is||!t?!1:t===ii||t===iT}function cT(r){if(nT.test(r))throw new S("DUMP_PARSE_FAILED",`Unexpected aa dump output: ${r.trim().split(/\r?\n/)[0]??""}`);if(!r.includes("ExtensionRecords")&&!r.includes("AbilityRecord ID"))throw new S("DUMP_PARSE_FAILED","aa dump output has no recognizable extension-record structure");for(let t of r.split(/\r?\n/))if(ZA.test(t)&&!ff.test(t))throw new S("DUMP_PARSE_FAILED","aa dump output has an unterminated uri line; output may be truncated");let e=oT(r);if(e.length===0&&r.replace(/ExtensionRecords:\s*/,"").trim()!=="")throw new S("DUMP_PARSE_FAILED","aa dump output has no complete ability records; output may be truncated");return e}function kv(r){if(!r.trim())throw new S("DUMP_PARSE_FAILED","aa dump output is empty; the device state is unknown");let e=new Map;for(let t of cT(r)){let n=sT(t);if(!aT(n))continue;if(n.id===void 0)throw new S("DUMP_PARSE_FAILED","Recorder ability block is missing its AbilityRecord ID");let{bundleName:i,abilityName:o}=Cv(n);e.set(n.id,{abilityRecordId:n.id,bundleName:i??Is,abilityName:o??ii,startedAtMs:n.startedAtMs})}return[...e.values()]}function mf(r,e){if(r.length>1)throw new S("AMBIGUOUS_DEVICE_STATE",`Multiple screen recorder ability records: ${r.map(n=>n.abilityRecordId).join(", ")}`);let t=r[0];return t?{status:e?.abilityRecordId===t.abilityRecordId?"recording":"busy",activeId:t.abilityRecordId,session:e}:{status:"idle",session:e}}function oi(r,e){return!r||!e?r===e:r.fileName===e.fileName&&r.abilityRecordId===e.abilityRecordId&&r.startTime===e.startTime&&r.localPath===e.localPath}function Rv(r){return r.status==="recording"?{plan:"error",error:new S("CLI_RECORDING_ACTIVE","A CLI recording session is already running; run stop first")}:r.status==="busy"?{plan:"error",error:new S("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; run stop --force first")}:r.session?{plan:"discard-first",session:r.session}:{plan:"start-new"}}function Dv(r){return r.status==="idle"&&!r.session?{plan:"start-new"}:{plan:"error",error:new S("STATE_CHANGED","Device state changed while discarding the interrupted registration; not starting")}}function xv(r,e){return r.status==="busy"?e?{plan:"force-stop-external",activeId:r.activeId}:{plan:"error",error:new S("EXTERNAL_RECORDING","Recording was not started by this CLI. Stop it on the device or run stop --force.")}:r.session?{plan:"finalize-session",session:r.session}:{plan:"error",error:new S("NO_CLI_SESSION","No CLI recording session on this device")}}function Iv(r,e,t){return oi(r,e)?{plan:"proceed"}:t==="interactive"?{plan:"completed-elsewhere"}:{plan:"error",error:new S("SESSION_CHANGED","The recording session changed; leaving the current one untouched")}}function Av(r){return r.status==="busy"?{plan:"error",error:new S("EXTERNAL_RECORDING","A recording not started by this CLI is in progress; not toggling")}:r.status==="recording"?{plan:"stop-recording"}:{plan:"retrieve"}}function Tv(r,e){if(r.length===0)return{outcome:"gone"};if(r.length>1)return{outcome:"error",error:new S("STATE_CHANGED","Multiple recorder records while confirming stop; not toggling again")};let t=r[0].abilityRecordId;return t!==e?{outcome:"error",error:new S("STATE_CHANGED",`A different recording (ID ${t}) appeared while stopping; leaving it alone`)}:{outcome:"still-recording",activeId:t}}function Nv(r){return r.length===1?{outcome:"confirmed",record:r[0]}:r.length>1?{outcome:"error",error:new S("AMBIGUOUS_DEVICE_STATE","Multiple recorder records after start; refusing to pick one")}:{outcome:"pending"}}function _v(r,e){if(r.length===0)return{plan:"already-stopped"};if(r.length>1)return{plan:"error",error:new S("AMBIGUOUS_DEVICE_STATE","Multiple recorder records; refusing to force-stop")};let t=r[0];return e!==void 0&&t.abilityRecordId!==e?{plan:"error",error:new S("STATE_CHANGED","The recording changed while stopping; leaving it alone")}:{plan:"stop",currentId:t.abilityRecordId,startedAtMs:t.startedAtMs}}function Mv(r){return r.status==="idle"&&r.session?{status:"idle",note:"interrupted session found; retrievable via ui screenrecord stop"}:{status:r.status}}function Ov(r,e){return!oi(r.session,e)||r.status!=="recording"}function hf(r,e){return r.startTime+e}function Lv(r,e,t){return t+Math.max(0,e-r)}import un from"fs";import Bv from"path";import{randomBytes as pT}from"crypto";import{lock as fT}from"proper-lockfile";import As from"path";var lT=/^[A-Za-z0-9][A-Za-z0-9.-]*\.mp4$/;function so(r){return Buffer.from(r,"utf8").toString("hex")}function si(r,e){return String(r).padStart(e,"0")}function Fv(r){return`${si(r.getFullYear(),4)}${si(r.getMonth()+1,2)}${si(r.getDate(),2)}-${si(r.getHours(),2)}${si(r.getMinutes(),2)}${si(r.getSeconds(),2)}${si(r.getMilliseconds(),3)}`}function dT(r){return r.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/[. ]+$/,"").replace(/^[. ]+/,"")||"device"}function $v(r,e){if(!/^[a-z0-9]{4}$/.test(e))throw new S("INVALID_RECORDING_PATH",`Internal: bad random suffix ${JSON.stringify(e)}`);return`devecocli-${Fv(r)}-${e}.mp4`}function jv(r,e,t){return`${dT(r)}-${Fv(e)}-${t}.mp4`}function Hv(r,e){if(!lT.test(r))throw new S("INVALID_RECORDING_PATH",`Unsafe device file name: ${JSON.stringify(r)}`);return`${Pv}/devecocli-${e}-${r}`}var uT=20;function Uv(r){let e=As.dirname(r),t=As.extname(r),n=As.basename(r,t),i=[r];i.push(As.join(e,`${n}-recovered${t}`));for(let o=2;o<uT;o++)i.push(As.join(e,`${n}-recovered-${o}${t}`));return i}var mT=5*6e4,hT=5*6e4,gT=1e4,yT=6e4,gf=200;function wT(r){if(!Number.isInteger(r)||r<=0)return"unknown";try{return process.kill(r,0),"alive"}catch(e){let t=e.code;return t==="ESRCH"?"dead":t==="EPERM"?"alive":"unknown"}}function Wv(r){return new Promise(e=>setTimeout(e,r))}function vT(){return pT(8).toString("hex")}async function Vv(r){let e;try{e=await un.promises.readFile(r,"utf8")}catch{return}try{let t=JSON.parse(e);return typeof t.token=="string"?t.token:void 0}catch{return}}var ll=class{constructor(e,t={}){this.recordDir=e;this.releaseGuardWaitMs=t.releaseGuardWaitMs??gT}releaseGuardWaitMs;lockPath(e){return Bv.join(this.recordDir,`${so(e)}.lock`)}guardPath(e){return Bv.join(this.recordDir,`${so(e)}.guard`)}async withDeviceLock(e,t,n=yT){let i=await this.acquire(e,n),o;try{o=await t(i)}catch(s){try{await this.releaseOwned(e,i)}catch(a){f(`lock release failed after action error: ${a.message}`)}throw s}return await this.releaseOwned(e,i),o}async withGuard(e,t,n=0){let i=Date.now()+n;for(;;){let o;try{o=await fT(this.guardPath(e),{realpath:!1,stale:mT,update:1e3,retries:0})}catch(s){if(s.code!=="ELOCKED"||Date.now()>=i)throw s;await Wv(Math.min(gf,i-Date.now()));continue}try{return await t()}finally{await o()}}}async acquire(e,t){await un.promises.mkdir(this.recordDir,{recursive:!0});let n=vT(),i=this.lockPath(e),o=Date.now()+t;for(;;){let s=!1;try{await this.withGuard(e,async()=>{s=await this.tryCreateOrReclaim(i,n)})}catch(a){if(a.code!=="ELOCKED")throw a}if(s)return this.buildLease(i,n);if(Date.now()+gf>o)throw new S("LOCK_BUSY",`Timed out waiting ${t}ms for the device lock (${e})`);await Wv(gf)}}async tryCreateOrReclaim(e,t){let n;try{n=await un.promises.open(e,"wx")}catch(i){if(i.code!=="EEXIST")throw i;return await this.reclaimIfDead(e),!1}try{let i={pid:process.pid,createdAt:Date.now(),token:t};await n.writeFile(JSON.stringify(i)),await n.sync()}finally{await n.close()}return!0}async reclaimIfDead(e){let t,n;try{t=await un.promises.readFile(e,"utf8"),n=await un.promises.stat(e)}catch(o){if(o.code==="ENOENT")return;throw o}let i;try{let o=JSON.parse(t);typeof o.pid=="number"&&typeof o.createdAt=="number"&&typeof o.token=="string"&&(i=o)}catch{}if(i){wT(i.pid)==="dead"&&await un.promises.unlink(e);return}Date.now()-n.mtimeMs>hT&&await un.promises.unlink(e)}buildLease(e,t){let n=new AbortController;return{token:t,signal:n.signal,assertOwned:async()=>{if(await Vv(e)!==t)throw n.abort(),new S("LOCK_LOST","Lost the device lock; aborting this operation")}}}async releaseOwned(e,t){let n=this.lockPath(e);try{await this.withGuard(e,async()=>{await Vv(n)===t.token&&await un.promises.unlink(n)},this.releaseGuardWaitMs)}catch(i){throw new S("LOCK_RELEASE_FAILED",`Could not release the device lock (${e}): ${i.message}. The lock stays in place; it is reclaimed by the dead-PID or corrupt-age rule once this process exits.`,{cause:i})}}};import{execa as bT}from"execa";var yf=15e3,Gv=10*6e4,ST=3,qv=400;function ET(r){return new Promise(e=>setTimeout(e,r))}function PT(r){return async(e,t)=>{f(`Executing: ${r} ${e.join(" ")}`);let n=await bT(r,e,{reject:!1,timeout:t.timeoutMs??yf,cancelSignal:t.signal,stdout:"pipe",stderr:"pipe"});return{stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",exitCode:n.exitCode??-1}}}var dl=class r{runner;constructor(e){this.runner=PT(e)}async runReadOnly(e,t){let n={stdout:"",stderr:"",exitCode:-1},i=t!==void 0?Date.now()+t:void 0;for(let o=0;o<ST;o++){let s=i!==void 0?i-Date.now():void 0;n=await this.runner(e,s===void 0?{}:{timeoutMs:Math.max(1,s)});let a=`${n.stdout}
|
|
65
|
+
${n.stderr}`;if(n.exitCode===0||Bt(a)!=="transient")return n;if(i!==void 0&&Date.now()+qv>i)break;await ET(qv)}return n}static assertUsable(e,t){let n=`${e.stdout}
|
|
66
|
+
${e.stderr}`.trim();if(e.exitCode!==0||Bt(n)!=="ok")throw new S(t,`hdc command failed (exit ${e.exitCode}): ${n.split(`
|
|
67
|
+
`)[0]??""}`)}async observeOnce(e,t){let n=await this.runReadOnly(["-t",e,"shell","aa","dump","-e"],t);return r.assertUsable(n,"DUMP_PARSE_FAILED"),kv(n.stdout)}async readUptimeMs(e,t){let n=await this.runReadOnly(["-t",e,"shell","cat","/proc/uptime"],t);r.assertUsable(n,"DUMP_PARSE_FAILED");let i=Number(/^([\d.]+)/.exec(n.stdout.trim())?.[1]);if(!Number.isFinite(i)||i<=0)throw new S("DUMP_PARSE_FAILED",`Unparseable /proc/uptime output: ${n.stdout.trim().split(`
|
|
68
|
+
`)[0]??""}`);return Math.round(i*1e3)}async toggleOnce(e,t,n,i){await n.assertOwned();let o=["-t",e,"shell","aa","start","-b",Is,"-a",ii];t!==void 0&&o.push("--ps","CustomizedFileName",t);try{let s=await this.runner(o,{timeoutMs:i??yf,signal:n.signal});return s.exitCode!==0?(f(`aa start exited ${s.exitCode}: ${s.stderr||s.stdout}`),{transport:"uncertain",stdout:s.stdout,stderr:s.stderr}):{transport:"returned",stdout:s.stdout,stderr:s.stderr}}catch(s){return f(`aa start transport failure: ${s.message}`),{transport:"uncertain",stderr:s.message}}}async queryMediaUri(e,t,n){let i=await this.runReadOnly(["-t",e,"shell","mediatool","query",t,"-u"],n);r.assertUsable(i,"MEDIA_QUERY_FAILED");let o=/find\s+(\d+)\s+result/i.exec(i.stdout);if(!o)throw new S("MEDIA_QUERY_FAILED",`Unparseable mediatool query output: ${i.stdout.trim().split(`
|
|
69
|
+
`)[0]??""}`);let s=[...i.stdout.matchAll(/"(file:\/\/[^"]+)"/g)].map(c=>c[1]),a=Number(o[1]);if(a!==0){if(a>1||s.length>1)throw new S("MEDIA_AMBIGUOUS",`mediatool returned ${a} entries for ${t}`);if(s.length!==1)throw new S("MEDIA_QUERY_FAILED",`mediatool reported 1 entry but no URI for ${t}`);return s[0]}}async exportToStaging(e,t,n){let i=await this.runner(["-t",e,"shell","mediatool","recv",t,n],{timeoutMs:Gv});if(r.assertUsable(i,"SAVE_FAILED"),!i.stdout.includes(n))throw new S("SAVE_FAILED",`mediatool recv did not confirm ${n}: ${i.stdout.trim().split(`
|
|
70
|
+
`)[0]??""}`)}async receiveFile(e,t,n,i){let o=await this.runner(["-t",e,"file","recv",t,n],{timeoutMs:Gv,signal:i});if(o.exitCode!==0)throw new S("SAVE_FAILED",`hdc file recv failed (exit ${o.exitCode}): ${(o.stderr||o.stdout).split(`
|
|
71
|
+
`)[0]??""}`)}async removeStaging(e,t){return(await this.runReadOnly(["-t",e,"shell","rm","-f",t],yf)).exitCode===0}};import Or from"fs";import pr from"path";import{createFile as CT}from"mp4box";var Jv=".devecocli-record-";function ao(r,e){return new S("INVALID_RECORDING_PATH",e instanceof Error?`${r}: ${e.message}`:r,e instanceof Error?{cause:e}:void 0)}async function wf(r){try{return{stat:await Or.promises.stat(r)}}catch(e){let t=e.code;return t==="ENOENT"?null:{code:t??"UNKNOWN"}}}async function zv(r){let e=await wf(r);if(!e)throw ao(`Directory does not exist: ${r}`);if("code"in e)throw ao(`Directory is not accessible: ${r}`);if(!e.stat.isDirectory())throw ao(`Path is not a directory: ${r}`);try{await Or.promises.access(r,Or.constants.W_OK)}catch(t){throw ao(`Directory is not writable: ${r}`,t)}}async function vf(r){if(await wf(r))throw new S("DESTINATION_EXISTS",`Destination already exists: ${r}`)}async function bf(r,e,t,n){if(!r?.trim())throw ao("--path is required.");let i=pr.resolve(r.trim()),o=await wf(i);if(o&&"stat"in o&&o.stat.isDirectory()){await zv(i);let a=pr.join(i,jv(e,t,n));return await vf(a),a}if(o)throw new S("DESTINATION_EXISTS",`Destination already exists: ${i}`);if(pr.extname(i).toLowerCase()!==".mp4")throw ao(`Destination must be an existing directory or a new .mp4 file: ${i}`);let s=pr.dirname(i);return await zv(s),i}async function Kv(r){return Or.promises.mkdtemp(pr.join(pr.dirname(r),Jv))}var kT=4*1024*1024;async function RT(r){let e=await Or.promises.open(r,"r");try{let{size:t}=await e.stat(),n=CT(),i=0;for(let s=0;s<t;){let a=Math.min(kT,t-s),c=Buffer.alloc(a),{bytesRead:l}=await e.read(c,0,a,s);if(l<=0)break;let d=c.buffer.slice(c.byteOffset,c.byteOffset+l);d.fileStart=s,i=n.appendBuffer(d,s+l>=t),s+=l}n.flush();let o=n.getBox("moov");return{size:t,complete:i===t,hasMovieHeader:o?.mvhd!==void 0,videoTrackCount:o?.mvhd!==void 0?n.getInfo().videoTracks.length:0}}finally{await e.close()}}async function Yv(r){let e;try{e=await RT(r)}catch(t){throw new S("SAVE_FAILED",`Cannot inspect received file: ${t.message}`,{cause:t})}if(e.size===0)throw new S("MEDIA_NOT_READY","Received file is empty");if(!e.complete||!e.hasMovieHeader)throw new S("MEDIA_NOT_READY","Received file is not a complete MP4");if(e.videoTrackCount<1)throw new S("MEDIA_NOT_READY","Received file has no video track");return e.size}async function DT(r){let e=await Or.promises.open(r,"r+");try{await e.sync()}finally{await e.close()}}async function xT(r){try{let e=await Or.promises.open(pr.dirname(r),"r");try{await e.sync()}finally{await e.close()}}catch{}}async function Xv(r,e){await DT(r);for(let t of Uv(e))try{return await Or.promises.link(r,t),await xT(t),t}catch(n){if(n.code==="EEXIST")continue;throw new S("SAVE_FAILED",`Cannot publish recording to ${t}: ${n.message}`,{cause:n})}throw new S("DESTINATION_UNAVAILABLE",`All recovery names are taken near ${e}`)}async function Zv(r,e){let t=pr.dirname(e),n=pr.basename(r);pr.dirname(r)!==t||!n.startsWith(Jv)||await Or.promises.rm(r,{recursive:!0,force:!0}).catch(()=>{})}import Lr from"fs";import ul from"path";import{randomBytes as IT}from"crypto";function Qv(r,e){let t=r,n=i=>new S("SESSION_CORRUPT",`Invalid recording session ${i} in ${e}`);if(!t||typeof t!="object")throw n("object");if(typeof t.fileName!="string"||t.fileName.length===0||t.fileName!==ul.basename(t.fileName)||t.fileName.includes(".."))throw n("fileName");if(typeof t.abilityRecordId!="number"||!Number.isSafeInteger(t.abilityRecordId)||t.abilityRecordId<=0)throw n("abilityRecordId");if(typeof t.startTime!="number"||!Number.isFinite(t.startTime))throw n("startTime");if(typeof t.localPath!="string"||t.localPath.length===0||!ul.isAbsolute(t.localPath))throw n("localPath");return{fileName:t.fileName,abilityRecordId:t.abilityRecordId,startTime:t.startTime,localPath:t.localPath}}var pl=class{constructor(e){this.recordDir=e}sessionPath(e){return ul.join(this.recordDir,`${so(e)}.json`)}async read(e){let t=this.sessionPath(e),n;try{n=await Lr.promises.readFile(t,"utf8")}catch(o){if(o.code==="ENOENT")return;throw new S("SESSION_CORRUPT",`Cannot read recording session: ${o.message}`,{cause:o})}let i;try{i=JSON.parse(n)}catch(o){throw new S("SESSION_CORRUPT",`Recording session file is not valid JSON: ${t}`,{cause:o})}return Qv(i,t)}async createAtomic(e,t,n){await Lr.promises.mkdir(this.recordDir,{recursive:!0});let i=this.sessionPath(e),o=ul.join(this.recordDir,`${so(e)}.${IT(6).toString("hex")}.tmp`),s=JSON.stringify(Qv(t,"input")),a;try{a=await Lr.promises.open(o,"wx")}catch(c){throw new S("SESSION_PUBLISH_FAILED",`Cannot create session temp file: ${c.message}`,{cause:c})}try{await a.writeFile(s),await a.sync()}catch(c){throw await a.close().catch(()=>{}),await Lr.promises.unlink(o).catch(()=>{}),new S("SESSION_PUBLISH_FAILED",`Cannot write session temp file: ${c.message}`,{cause:c})}await a.close();try{if(await n.assertOwned(),await this.exists(i))throw new S("SESSION_CHANGED",`A recording session was created concurrently for ${e}`);await Lr.promises.link(o,i),await this.syncDir()}finally{await Lr.promises.unlink(o).catch(()=>{})}}async deleteIfSame(e,t,n){await n.assertOwned();let i=await this.read(e);if(i){if(!oi(i,t))throw new S("SESSION_CHANGED","The recording session changed hands; leaving the new record untouched");await Lr.promises.unlink(this.sessionPath(e)),await this.syncDir()}}async exists(e){try{return await Lr.promises.lstat(e),!0}catch{return!1}}async syncDir(){try{let e=await Lr.promises.open(this.recordDir,"r");try{await e.sync()}finally{await e.close()}}catch{}}};var TT={startConfirmMs:1e4,stopConfirmMs:15e3,stopReadyMs:3e3,observeIntervalMs:250,foregroundPollMs:1e3,mediaReadyMs:3e4,mediaBackoffMs:[250,500,1e3,2e3],mediaRecvAttempts:3,lockWaitMs:6e4,interactiveLockWaitMs:10*6e4,foregroundFailureBudget:3},tb=4e3;function Ts(r){return new Promise(e=>setTimeout(e,r))}function fl(){return AT(2).toString("hex")}var rb=["SIGINT","SIGTERM","SIGHUP"];function NT(r,e){let t=()=>{r.requested||(r.requested=!0,e?.(),r.wake())};for(let n of rb)process.on(n,t);return()=>{for(let n of rb)process.off(n,t)}}var pn=class{constructor(e,t={}){this.toolProvider=e;let n=eb.join(j(),"record");this.deps={store:t.store??new pl(n),lock:t.lock??new ll(n),device:t.device??new dl(e.hdcPath),timing:{...TT,...t.timing}}}deps;async startDetached(e,t){let n=await this.resolveTarget(e),i=await bf(t,n.name,new Date,fl());return this.startSession(n,i)}async recordInteractively(e,t,n){let i=new Set,o={requested:!1,wake:()=>{for(let a of i)a()}},s=NT(o,n.onStopRequested);try{let a=await this.resolveTarget(e),c=await bf(t,a.name,new Date,fl()),l=await this.startSession(a,c);return n.onStarted(),await this.waitForInteractiveCompletion(l,o,i)}finally{s()}}async waitForInteractiveCompletion(e,t,n){let i,o=()=>(i??=this.deps.lock.withDeviceLock(e.serial,a=>this.finalizeLocked(e.serial,e.session,"interactive",a),this.deps.timing.interactiveLockWaitMs),i),s=0;for(;;){if(t.requested)return await o();let a;try{a=await this.readSnapshot(e.serial),s=0}catch(c){if(s+=1,s>=this.deps.timing.foregroundFailureBudget)throw c;await this.waitPoll(t,n);continue}if(Ov(a,e.session))return await o();await this.waitPoll(t,n)}}async stopRecording(e,t){let n=await this.resolveTarget(e);return this.deps.lock.withDeviceLock(n.serial,async i=>{let o=await this.readSnapshot(n.serial),s=xv(o,t);if(s.plan==="force-stop-external")return await this.stopExternal(n.serial,s.activeId,i),{kind:"external-stopped"};if(s.plan==="error")throw s.error;return this.finalizeLocked(n.serial,s.session,"stop-or-recover",i)},this.deps.timing.lockWaitMs)}async getRecordingStatus(e){let t=await this.resolveTarget(e);for(let n=0;n<3;n++){let i=await this.deps.store.read(t.serial),o=await this.deps.device.observeOnce(t.serial),s=await this.deps.store.read(t.serial);if(!oi(i,s))continue;let a=mf(o,s);return Mv(a)}throw new S("STATE_CHANGING","The recording session keeps changing; try again")}async resolveTarget(e){let t=await ce.from(this.toolProvider).getConnectedEntries();if(t.length===0)throw new S("NO_ACTIVE_DEVICES","No active devices found. Connect a physical device; screen recording does not support emulators.");let n=await T(this.toolProvider,e),i=t.find(o=>o.serial===n);if(i?.isEmulator)throw new S("EMULATOR_NOT_SUPPORTED","Screen recording is only supported on physical devices");return{serial:n,name:i?.name??n}}async readSnapshot(e){let t=await this.deps.store.read(e),n=await this.deps.device.observeOnce(e);return mf(n,t)}async startSession(e,t){return this.deps.lock.withDeviceLock(e.serial,n=>this.startSessionLocked(e,t,n),this.deps.timing.lockWaitMs)}async startSessionLocked(e,t,n){let i=await this.readSnapshot(e.serial),o=Rv(i);if(o.plan==="error")throw o.error;if(o.plan==="discard-first"){await this.deps.store.deleteIfSame(e.serial,o.session,n);let s=await this.readSnapshot(e.serial),a=Dv(s);if(a.plan==="error")throw a.error}return this.toggleAndRegister(e,t,n)}async toggleAndRegister(e,t,n){await vf(t);let i=$v(new Date,fl()),o=Date.now(),s=Date.now()+this.deps.timing.startConfirmMs;await n.assertOwned(),await this.deps.device.toggleOnce(e.serial,i,n,Math.max(1,s-Date.now()));let a=await this.waitForStarted(e.serial,s),c={fileName:i,abilityRecordId:a.abilityRecordId,startTime:o,localPath:t};return await this.registerSession(e.serial,c,n),{serial:e.serial,session:c}}async registerSession(e,t,n){try{await this.deps.store.createAtomic(e,t,n)}catch(i){throw await this.abortUnregistered(e,t,n),new S(i.code??"SESSION_PUBLISH_FAILED",`Recording started on device (file ${t.fileName}) but could not be registered: ${i.message}. Check the device gallery.`,{cause:i})}}async withinDeadline(e,t,n){try{return await n(Math.max(1,e-Date.now()))}catch(i){throw Date.now()>=e?t:i}}async waitForStarted(e,t){for(;;){let n=t-Date.now();if(n<=0)throw new S("START_CONFIRM_TIMEOUT","Device screen may be locked");let i=await this.withinDeadline(t,new S("START_CONFIRM_TIMEOUT","Device screen may be locked"),s=>this.deps.device.observeOnce(e,s)),o=Nv(i);if(o.outcome==="error")throw o.error;if(o.outcome==="confirmed"){if(Date.now()>t)throw new S("START_CONFIRM_TIMEOUT","Device screen may be locked");return o.record}await Ts(Math.min(this.deps.timing.observeIntervalMs,n))}}async observeActiveId(e,t,n){let i=await this.deps.device.observeOnce(e,n),o=Tv(i,t);if(o.outcome==="error")throw o.error;return o.outcome==="gone"?void 0:o.activeId}async waitForStopped(e,t,n){for(;;){let i=n-Date.now();if(i<=0)throw new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(n,new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),s=>this.observeActiveId(e,t,s))===void 0)return;await Ts(Math.min(this.deps.timing.observeIntervalMs,i))}}async awaitStopReady(e,t,n,i){for(;;){let o=i-Date.now();if(o<=0)throw new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");if(await this.withinDeadline(i,new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),a=>this.observeActiveId(e,t,a))===void 0)return"vanished";if(Date.now()>=n){if(Date.now()>i)throw new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent");return"ready"}await Ts(Math.min(this.deps.timing.observeIntervalMs,n-Date.now(),o))}}async abortUnregistered(e,t,n){try{let i=Date.now()+this.deps.timing.stopConfirmMs,o=hf(t,this.deps.timing.stopReadyMs);await this.awaitStopReady(e,t.abilityRecordId,o,i)==="ready"&&await this.deps.device.toggleOnce(e,void 0,n,Math.max(1,i-Date.now()))}catch(i){f(`abortUnregistered: best-effort stop failed: ${i.message}`)}}async finalizeLocked(e,t,n,i){let o=await this.deps.store.read(e),s=Iv(o,t,n);if(s.plan==="completed-elsewhere")return{kind:"completed-elsewhere"};if(s.plan==="error")throw s.error;let a=await this.readSnapshot(e),c=Av(a);if(c.plan==="error")throw c.error;if(c.plan==="stop-recording"){let l=Date.now()+this.deps.timing.stopConfirmMs;return this.stopLiveRecording(e,t,i,l)}return this.retrieveAndPublish(e,t,i)}async stopLiveRecording(e,t,n,i){let o=hf(t,this.deps.timing.stopReadyMs);return await this.awaitStopReady(e,t.abilityRecordId,o,i)==="vanished"?this.retrieveAndPublish(e,t,n):(await n.assertOwned(),await this.deps.device.toggleOnce(e,void 0,n,Math.max(1,i-Date.now())),await this.waitForStopped(e,t.abilityRecordId,i),this.retrieveAndPublish(e,t,n))}async stopExternal(e,t,n){let i=await this.deps.device.observeOnce(e),o=_v(i,t);if(o.plan==="already-stopped")return;if(o.plan==="error")throw o.error;let s=Date.now()+this.deps.timing.stopConfirmMs;o.startedAtMs!==void 0&&!await this.awaitForeignStopReady(e,o.currentId,o.startedAtMs,s)||(await n.assertOwned(),await this.deps.device.toggleOnce(e,void 0,n,Math.max(1,s-Date.now())),await this.waitForStopped(e,o.currentId,s))}async awaitForeignStopReady(e,t,n,i){let o=await this.withinDeadline(i,new S("STOP_CONFIRM_TIMEOUT","The recording did not stop in time; session kept, no re-toggle sent"),c=>this.deps.device.readUptimeMs(e,c)),s=Lv(o-n,this.deps.timing.stopReadyMs,Date.now());return await this.awaitStopReady(e,t,s,i)==="ready"}async retrieveAndPublish(e,t,n){let i=[],o=await this.waitForMediaUri(e,t.fileName),s=await Kv(t.localPath);try{let a=await this.receiveUntilValid(e,o,t,s,n,i);await n.assertOwned();let c=await Xv(a,t.localPath);return await this.deleteSessionAfterSave(e,t,n,c),{kind:"saved",localPath:c,warnings:i}}finally{await Zv(s,t.localPath)}}async waitForMediaUri(e,t){let n=Date.now()+this.deps.timing.mediaReadyMs,i=0;for(;;){let o=n-Date.now();if(o<=0)throw new S("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`);let s=await this.withinDeadline(n,new S("MEDIA_NOT_READY",`Timed out waiting for ${t} in the media library; session kept for a later stop`),c=>this.deps.device.queryMediaUri(e,t,c));if(s&&Date.now()<=n)return s;let a=Math.min(this.deps.timing.mediaBackoffMs[Math.min(i,this.deps.timing.mediaBackoffMs.length-1)]??tb,tb,o);i+=1,await Ts(a)}}async receiveUntilValid(e,t,n,i,o,s){for(let a=0;a<this.deps.timing.mediaRecvAttempts;a++){await o.assertOwned();let c=Hv(n.fileName,fl()),l=await this.receiveOnce(e,t,c,i,n.fileName,o,s);try{return await Yv(l),l}catch(d){if(d.code!=="MEDIA_NOT_READY")throw d;f(`Received file incomplete (attempt ${a+1}); retrying export`),await Ts(this.deps.timing.mediaBackoffMs[0]??250)}}throw new S("MEDIA_NOT_READY",`Received file for ${n.fileName} is incomplete after ${this.deps.timing.mediaRecvAttempts} attempts; session kept`)}async receiveOnce(e,t,n,i,o,s,a){let c=eb.join(i,o);try{await this.deps.device.exportToStaging(e,t,n),await this.deps.device.receiveFile(e,n,c,s.signal)}finally{await this.deps.device.removeStaging(e,n)||a.push(`Failed to remove device staging file: ${n}`)}return c}async deleteSessionAfterSave(e,t,n,i){try{await this.deps.store.deleteIfSame(e,t,n)}catch(o){throw new S(o.code??"SESSION_DELETE_FAILED",`Recording saved to ${i}, but the session record could not be removed: ${o.message}. A later stop may create a recovered copy.`,{cause:o})}}async waitPoll(e,t){await new Promise(n=>{let i=setTimeout(()=>{t.delete(o),n()},this.deps.timing.foregroundPollMs),o=()=>{t.delete(o),clearTimeout(i),n()};t.add(o)})}};var ml={left:"0",right:"1",up:"2",down:"3"};function We(r,e){let t=Number(r);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Sf(r,e){r!==void 0&&We(r,e)}function nb(r,e){if(r===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function hl(r,e){if(r!==void 0&&r.length===0)throw new Error(`${e} must not be empty`)}function Ns(r){if(r===void 0)return;let e=Number(r);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return r}function ib(r){if(r!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(r))throw new Error("--window must consist of letters, digits, - or _")}function ob(r,e,t,n=!0){if(t&&!e)throw new Error("--window must be used with --id");if(r&&e)throw new Error("Coordinates and --id are mutually exclusive");if(n&&!r&&!e)throw new Error("Either provide x y coordinates or use --id")}function co(r,e,t,n,i=!0){nb(r,e),hl(t,"--id"),Sf(r,"x"),Sf(e,"y"),ib(n),ob(r!==void 0,!!t,!!n,i)}async function fr(r){let e=await P.new(),t=await T(e,r);return{hdcPath:e.hdcPath,deviceId:t}}async function lo(r,e,t,n,i,o){if(t!==void 0&&n!==void 0)return{x:t,y:n};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Nr(r,e).listWindows({all:!0}),c=new _r(r);return _T(c,e,a,i,o)}async function _T(r,e,t,n,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new w(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");let s=await r.dumpFullTree(e,0,i,!1);return OT(s,n)}return MT(r,e,t,n)}async function MT(r,e,t,n){let i=[...new Set(t.map(a=>a.displayId))],o=await r.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of no([c],n))s.push({node:l,displayId:a});if(s.length===0)throw new w(`Node "${n}" not found.`,"Node not found.");if(s.length>1)throw new w(`Multiple nodes found with id "${n}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new w(`Node "${n}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`,"The current command only supports operations on the primary display.");return sb(s[0].node,n)}function OT(r,e){let t=no(r,e);if(t.length===0)throw new w(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new w(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return sb(t[0],e)}function sb(r,e){let t=r.bounds;if(!t)throw new w(`Node "${e}" has no bounds.`,"Node has no bounds.");let[n,i,o,s]=t;return{x:Math.ceil((n+o)/2),y:Math.ceil((i+s)/2)}}async function Rt(r,e,t){let n=["-t",e,"shell",...t];f(`Executing: ${r} ${n.join(" ")}`);let i=await C(r,n);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import{deflateSync as LT,inflateSync as FT}from"zlib";import $T from"fs";var ab=8,cb=32,jT=.06,HT=.04,Ef=10,gl=class r{whiteBits=null;blackBits=null;analyzeRgb(e,t,n){if(e<8||t<8||n.length<e*t*3)return null;let i=this.cropChrome(e,t,n),o=this.hashBits(i.width,i.height,i.rgb),s=Math.min(this.hammingDistance(o,this.solidRefBits(255)),this.hammingDistance(o,this.solidRefBits(0)));return{phash:this.bitsToHex(o),hamming:s,isBlank:s<=Ef}}analyzeFile(e){let t;try{t=$T.readFileSync(e)}catch{return null}let n=this.decodePngRgb(t);return n?this.analyzeRgb(n.width,n.height,n.rgb):null}static encodePngRgb(e,t,n){let i=r.pngCrcTable(),o=[Buffer.from(`\x89PNG\r
|
|
69
72
|
|
|
70
|
-
`,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,o.push(
|
|
73
|
+
`,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,o.push(r.pngChunk("IHDR",s,i));let a=Buffer.alloc((e*3+1)*t);for(let c=0;c<t;c++)a[c*(e*3+1)]=0,Buffer.from(n.buffer,n.byteOffset+c*e*3,e*3).copy(a,c*(e*3+1)+1);return o.push(r.pngChunk("IDAT",LT(a),i)),o.push(r.pngChunk("IEND",Buffer.alloc(0),i)),Buffer.concat(o)}cropChrome(e,t,n){let i=Math.floor(t*jT),o=Math.floor(t*(1-HT));if(o<=i+8)return{width:e,height:t,rgb:n};let s=o-i,a=new Uint8Array(e*s*3);for(let c=0;c<s;c++){let l=(i+c)*e*3;a.set(n.subarray(l,l+e*3),c*e*3)}return{width:e,height:s,rgb:a}}hashBits(e,t,n){let i=this.toGray(e,t,n),o=this.resizeGray(i,cb,cb),s=this.dct2(o),a=[];for(let d=0;d<ab;d++)a.push(s[d].slice(0,ab));let c=this.stabilizeDct(a),l=this.median(c);return c.map(d=>d>l)}solidRefBits(e){return e===255?this.whiteBits??=this.solidBits(255,255,255):this.blackBits??=this.solidBits(0,0,0)}solidBits(e,t,n){let o=new Uint8Array(12288);for(let s=0;s<4096;s++)o[s*3]=e,o[s*3+1]=t,o[s*3+2]=n;return this.hashBits(64,64,o)}hammingDistance(e,t){let n=Math.min(e.length,t.length),i=Math.abs(e.length-t.length);for(let o=0;o<n;o++)e[o]!==t[o]&&i++;return i}bitsToHex(e){let t=0n;for(let i of e)t=t<<1n|(i?1n:0n);let n=Math.max(1,Math.ceil(e.length/4));return t.toString(16).padStart(n,"0")}toGray(e,t,n){let i=[];for(let o=0;o<t;o++){let s=[];for(let a=0;a<e;a++){let c=(o*e+a)*3;s.push(.299*n[c]+.587*n[c+1]+.114*n[c+2])}i.push(s)}return i}resizeGray(e,t,n){let i=e.length,o=e[0]?.length??0;if(o===t&&i===n)return e;let s=[];for(let a=0;a<n;a++){let c=(a+.5)*i/n-.5,l=Math.max(0,Math.min(i-1,Math.floor(c))),d=Math.max(0,Math.min(i-1,l+1)),h=c-l,y=[];for(let D=0;D<t;D++){let K=(D+.5)*o/t-.5,we=Math.max(0,Math.min(o-1,Math.floor(K))),ut=Math.max(0,Math.min(o-1,we+1)),tr=K-we,Un=e[l][we],Bn=e[l][ut],Wn=e[d][we],Ig=e[d][ut];y.push(Un*(1-tr)*(1-h)+Bn*tr*(1-h)+Wn*(1-tr)*h+Ig*tr*h)}s.push(y)}return s}stabilizeDct(e){let t=e.flat(),n=Math.abs(t[0]??0),i=Math.max(.001,n*1e-8);return t.map(o=>Math.abs(o)<i?0:o)}median(e){if(e.length===0)return 0;let t=[...e].sort((i,o)=>i-o),n=Math.floor(t.length/2);return t.length%2?t[n]:.5*(t[n-1]+t[n])}dct2(e){let t=e.length,n=a=>{let c=new Array(t).fill(0);for(let l=0;l<t;l++){let d=0;for(let h=0;h<t;h++)d+=a[h]*Math.cos(Math.PI*(h+.5)*l/t);c[l]=d}return c},i=e.map(n),o=[];for(let a=0;a<t;a++)o.push(n(i.map(c=>c[a])));let s=[];for(let a=0;a<t;a++){let c=[];for(let l=0;l<t;l++)c.push(o[l][a]);s.push(c)}return s}decodePngRgb(e){let t=this.parsePngChunks(e);if(!t)return null;let n;try{n=FT(Buffer.concat(t.idat))}catch{return null}let i=this.pngScanlinesToRgb(n,t.width,t.height,t.colorType);return{width:t.width,height:t.height,rgb:i}}parsePngChunks(e){if(e.length<8||e.subarray(0,8).toString("binary")!==`\x89PNG\r
|
|
71
74
|
|
|
72
|
-
`)return null;let t=8,
|
|
73
|
-
`),"Multiple devices found.")}let
|
|
75
|
+
`)return null;let t=8,n=0,i=0,o=0,s=0,a=[];for(;t+8<=e.length;){let c=e.readUInt32BE(t),l=e.subarray(t+4,t+8).toString("ascii"),d=e.subarray(t+8,t+8+c);if(t+=12+c,l==="IHDR")n=d.readUInt32BE(0),i=d.readUInt32BE(4),o=d[8],s=d[9];else if(l==="IDAT")a.push(d);else if(l==="IEND")break}return!n||!i||o!==8||s!==2&&s!==6?null:{width:n,height:i,colorType:s,idat:a}}pngScanlinesToRgb(e,t,n,i){let o=i===6?4:3,s=t*o,a=new Uint8Array(t*n*3),c=0,l=new Uint8Array(s),d=new Uint8Array(s);for(let h=0;h<n;h++){let y=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(y,d,l,o);for(let D=0;D<t;D++){let K=(h*t+D)*3,we=D*o;a[K]=d[we],a[K+1]=d[we+1],a[K+2]=d[we+2]}l.set(d)}return a}applyPngFilter(e,t,n,i){for(let o=0;o<t.length;o++){let s=o>=i?t[o-i]:0,a=n[o],c=o>=i?n[o-i]:0;e===1?t[o]=t[o]+s&255:e===2?t[o]=t[o]+a&255:e===3?t[o]=t[o]+Math.floor((s+a)/2)&255:e===4&&(t[o]=t[o]+this.paeth(s,a,c)&255)}}paeth(e,t,n){let i=e+t-n,o=Math.abs(i-e),s=Math.abs(i-t),a=Math.abs(i-n);return o<=s&&o<=a?e:s<=a?t:n}static pngChunk(e,t,n){let i=Buffer.concat([Buffer.from(e,"ascii"),t]),o=Buffer.alloc(12+t.length);return o.writeUInt32BE(t.length,0),i.copy(o,4),o.writeUInt32BE(r.pngCrc(i,n),8+t.length),o}static pngCrcTable(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let i=0;i<8;i++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e}static pngCrc(e,t){let n=4294967295;for(let i=0;i<e.length;i++)n=t[(n^e[i])&255]^n>>>8;return(n^4294967295)>>>0}};import Fr from"fs";import Wt from"path";import{randomUUID as qT}from"crypto";var UT=/^smoke-screenshot-\d+\.png$/,BT=/^smoke-crash-\d+\.log$/,WT=/^run-\d+-\d+-[0-9a-f]{4}$/;function lb(r){return`smoke-screenshot-${r}.png`}function db(r){return`smoke-crash-${r}.log`}function ub(r){return UT.test(r)||BT.test(r)}var _s="RUNNING",Pf="ENDED",VT=1440*60*1e3,GT=1440*60*1e3;function pb(r,e,t){return`run-${r}-${e}-${t}`}function fb(r){return WT.test(r)}function mb(r){try{let e=JSON.parse(r);if(typeof e.pid!="number"||typeof e.startedAt!="number"||!Number.isFinite(e.pid)||!Number.isFinite(e.startedAt))return null;let t={pid:e.pid,startedAt:e.startedAt};return typeof e.endedAt=="number"&&Number.isFinite(e.endedAt)&&(t.endedAt=e.endedAt),t}catch{}return null}function hb(r,e,t){return r===null?!0:r==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=VT:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=GT?!0:!t.isPidAlive(e.pid)}var zT="smoke";function JT(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}var Ms=class{constructor(e,t=JT){this.baseDir=e;this.isPidAlive=t;this.runsRoot=Wt.join(e,zT)}runsRoot;static resolveBaseDir(e,t){return t??Wt.join(e,".hvigor")}createRun(){let e=Wt.join(this.runsRoot,pb(Date.now(),process.pid,qT().slice(0,4)));Fr.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return Fr.writeFileSync(Wt.join(e,_s),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,_s),n={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};Fr.writeFileSync(Wt.join(e,Pf),JSON.stringify(n),"utf8"),Fr.rmSync(Wt.join(e,_s),{force:!0})}catch(t){f(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{Fr.rmSync(e,{recursive:!0,force:!0})}catch(t){f(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=Fr.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!ub(t.name)||this.removeQuietly(Wt.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let n;try{n=Fr.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let i of n){if(!i.isDirectory()||!fb(i.name))continue;let o=Wt.join(this.runsRoot,i.name);if(Wt.resolve(o)===Wt.resolve(e))continue;let s=this.readMarkerState(o);hb(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(o)}}readMarkerState(e){let t=this.readMarker(e,Pf);if(t!==void 0)return{kind:"ended",marker:t};let n=this.readMarker(e,_s);return n!==void 0?{kind:"running",marker:n}:{kind:null,marker:null}}readMarker(e,t){try{return mb(Fr.readFileSync(Wt.join(e,t),"utf8"))}catch(n){return n.code==="ENOENT"?void 0:null}}removeQuietly(e){try{Fr.rmSync(e,{recursive:!0,force:!0})}catch(t){f(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var gb=3e3;function YT(){let r=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(r===void 0||r==="")return gb;let e=Number(r);return Number.isFinite(e)&&e>=0?Math.floor(e):gb}var wl=class{constructor(e,t,n){this.hdc=t;this.projectRoot=n;this.hilog=new dn(e),this.screenshots=new ni(e)}phash=new gl;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=YT();t>0&&await new Promise(i=>setTimeout(i,t));let n;try{n=await this.hdc.pidofBundle(e.targetDeviceId,e.bundleName)}catch(i){return console.warn(Os(`Smoke: process check failed (${i.message}); smoke skipped.`)),{processAlive:!0,phashBlank:null,processCheckSkipped:!0}}return n?this.collectScreenshotEvidence(e):{processAlive:!1,phashBlank:null,crashLogPath:await this.writeCrashLogFile(e)}}openRun(e){let t=new Ms(Ms.resolveBaseDir(this.projectRoot,e.screenshotDir)),n=t.createRun();t.prune(n),this.runStore=t,this.runDir=n}artifactPath(e){return KT.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{yl.rmSync(t,{force:!0})}catch(n){f(`Smoke: discard artifact failed (${t}): ${n.message}`)}this.runStore&&this.runDir&&this.runStore.discard(this.runDir)}finalizeRun(){this.runStore&&this.runDir&&this.runStore.finalize(this.runDir)}async collectScreenshotEvidence(e){let t=this.artifactPath(lb(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(i){return this.skipBlank(`screenshot failed (${i.message})`)}if(!yl.existsSync(t)||yl.statSync(t).size<=32)return this.skipBlank("screenshot file missing or empty");let n=this.phash.analyzeFile(t);return n?{processAlive:!0,phashBlank:n.isBlank,phash:n.phash,phashHamming:n.hamming,screenshotPath:t}:this.skipBlank("failed to analyze screenshot",t)}skipBlank(e,t){return console.warn(Os(`Smoke: ${e}; blank check skipped.`)),{processAlive:!0,phashBlank:null,screenshotPath:t,screenshotSkipped:!0}}async writeCrashLogFile(e){let t;try{t=await this.hilog.getLatestCrashLog(e.targetDeviceId,e.bundleName)}catch(n){console.warn(Os(`Smoke: crash log query failed (${n.message}).`));return}if(!t?.trim()){console.warn(Os("Smoke: no crash log found on device."));return}try{let n=this.artifactPath(db(Date.now()));return yl.writeFileSync(n,t,"utf8"),n}catch(n){console.warn(Os(`Smoke: failed to save crash log (${n.message}).`));return}}};var vl=class{judge(e){if(!e.processAlive)return this.verdict("FAIL_CRASH","Application process died after launch (possible crash).",e);if(e.phashBlank===!0)return this.verdict("FAIL_BLANK",`Blank/solid screen after launch (hamming ${e.phashHamming} \u2264 ${Ef}, hash=${e.phash||"-"}).`,e);let t=e.phashBlank===null?"Process alive; screenshot unavailable, blank check skipped.":"Process alive; screenshot is not a solid blank screen.";return this.verdict("PASS",t,e)}verdict(e,t,n){return{status:e,reason:t,evidence:n,passed:e==="PASS"}}};var bl=class{inspector;judge=new vl;formatter=new Qc;constructor(e,t,n){let i=n??new le(e);this.inspector=new wl(e,i,t)}async execute(e){let t=await this.inspector.collect(e),n=this.judge.judge(t);if(n.passed){this.inspector.discardEvidence(t),console.log(this.formatter.formatPass(n));return}throw this.inspector.finalizeRun(),this.formatter.toTraceError(n,e)}};async function Cf(r){await new bl(r.toolProvider,r.projectRoot,r.hdcAdapter).execute(r)}function kf(r){let e=r.indexOf("@"),t=e!==-1?r.substring(0,e):r,n=e!==-1?r.substring(e+1):"default";return{moduleName:t,targetName:n}}async function El(r,e){let t=await r.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await r.listDevicesWithName();throw new w("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
76
|
+
`),"Multiple devices found.")}let n=await r.getDeviceInfo(t,e);if(!n)throw new Error("No active devices found.");if(!e){let i=await r.getDeviceName(n.serial);console.log(`Auto-selected device: ${i} (${n.serial})`)}return n.serial}function Rf(r,e){if(e&&e.length>0)return e;let t=r.profile.modules.filter(n=>{let i=r.getModuleType(n.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let n=t[0].name;return console.log(`Auto-selected module: ${n}`),[n]}throw new w(`Specify module(s) using --module <name> [<name>...].
|
|
74
77
|
Available runnable modules:
|
|
75
|
-
`+t.map(
|
|
76
|
-
`),"Specify module error.")}function
|
|
77
|
-
Installing artifacts to device ${e}...`),await
|
|
78
|
+
`+t.map(n=>` - ${n.name}`).join(`
|
|
79
|
+
`),"Specify module error.")}function yb(r,e,t){if(t)return t;let n=e.find(({moduleName:o})=>r.getModuleType(o)==="entry");if(n)return r.getMainAbility(n.moduleName);let i=e.find(({moduleName:o})=>r.getModuleType(o)==="feature");if(i)return r.getMainAbility(i.moduleName)}async function wb(r,e,t,n,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
80
|
+
Installing artifacts to device ${e}...`),await r.installApp(e,n),i){console.log(`Launching ${t}/${i}...`);let s=await r.launchApp(e,t,i);console.log(Ls(`
|
|
78
81
|
Application '${t}': ${s}`))}else console.log(`
|
|
79
|
-
Application '${t}' installed successfully (no ability to launch).`)}function
|
|
80
|
-
`+Zi("Build completed successfully.")),y}async function OC(n,e){let t=U.discover(process.cwd());console.warn(zs("Ensure the project source is trusted before proceeding."));let r=await P.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await $C(n,t,r);return}if(n.hotreload){await FC(n,t,r);return}if(n.apply){await HC(n,t,r);return}return fh(n,t,r)}async function _C(n,e,t){n.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let r=new tt(e,t.rootDir),i=setInterval(async()=>{await r.isDaemonAlive()||(clearInterval(i),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function FC(n,e,t){if(n.hotreload==="stop"){await rf(t,e);return}let i=Zl(e,n.module).map(Xl),{moduleName:o,targetName:s}=i[0];Ml(n.module,o);let a=new Le(t),c=oe.from(t),l=await Js(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let y=e.getBundleName(g),I=ph(e,i,n.ability);As.generate(e.rootDir,o,g,t);let le=new tt(t,e.rootDir);console.log(Zi("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await le.ensureDaemonRunning();let z=[`${o}@${g}`];for(let xt of e.collectNonHarDependentModuleList(o))z.includes(`${xt}@${g}`)||z.push(`${xt}@${g}`);console.log(Zi("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let xe=new On(e.rootDir,t);await xe.startWatchSession({moduleSpecs:z,productName:g});let at=tf(e,o,s,d,g);await mh(a,l,y,at,I,!!n.uninstall),console.log(Zi("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.")),await _C(xe,t,e)}async function $C(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Qi.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Zl(e,n.module),{moduleName:o}=Xl(i[0]);Ml(n.module,o);let s=oe.from(t),a=await Js(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName(c);ef(e,o,r);let d=[`${o}@${c}`],g=await Qm({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function jC(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function fh(n,e,t){let i=Zl(e,n.module).map(Xl);for(let{moduleName:z}of i){let xe=e.getModuleType(z);if(xe!=="entry"&&xe!=="feature"&&xe!=="shared")throw new S(`Module '${z}' '${xe}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new Le(t),s=oe.from(t),a=await Js(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",g;n.skipBuild||(g=await MC(e,t,i,l,d));let y=jC(e,i,c,l),I=e.getBundleName(l),le=ph(e,i,n.ability);return await mh(o,a,I,y,le,!!n.uninstall),le&&await Kl({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:o,targetDeviceId:a,bundleName:I}),g}async function HC(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Qi.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Qi.join(e.rootDir,".hvigor",r),o=oe.from(t),s=await Js(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(y=>e.getModuleType(y.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new ks(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(y){console.warn(zs(`[Apply] failed: ${y.message}`)),console.warn(zs('[Apply] Falling back to full "devecocli run"...')),await fh(n,e,t);return}console.log(zs('[Apply] Done. If changes did not take effect, check <module>/build/config/buildConfig.json for content, or run "devecocli run" for a full build.')),await Kl({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var hh=LC;import{Command as pk}from"commander";import*as sd from"path";import{red as Ph,cyan as Qs,yellow as id}from"colorette";import{execa as ea}from"execa";import{spawn as JC}from"child_process";import*as wh from"fs";import*as Ks from"path";import{yellow as YC,cyan as KC}from"colorette";import XC from"proper-lockfile";function Un(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-common"}function mt(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.5-Test.4"}function Bn(){return"daily"}function Pt(){return Number.isFinite(1),1}var jt="@deveco-test/deveco-cli-knowledgebase";function Wn(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as eo from"fs";import*as to from"path";var UC={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Ql=new Map,Sr=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=to.join(e,"cache.json"),this.lockFilePath=to.join(e,"check.lock")}async writeSuccess(e,t=[],r,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=Ql.get(this.cacheFilePath);if(e)return e;try{let t=eo.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Ql.set(this.cacheFilePath,r),r}catch{return{...UC}}}async write(e){p(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await eo.promises.mkdir(to.dirname(this.cacheFilePath),{recursive:!0}),await eo.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Ql.set(this.cacheFilePath,e)}};import{createRequire as BC}from"module";import{dirname as WC,join as Vn}from"path";import{pathToFileURL as VC}from"url";import{readFile as gh,access as ed}from"fs/promises";import*as yh from"semver";var GC=BC(import.meta.url);async function qC(){try{let n=GC.resolve("@deveco-test/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await gh(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:WC(n)}}catch{return null}}async function zC(){let n=W(),e=Vn(n,"doc-data","current.json"),t;try{t=JSON.parse(await gh(e,"utf8"))}catch{return null}let r=Vn(n,"doc-data",t.version);try{return await ed(Vn(r,"dist","engine","index.js")),await ed(Vn(r,"docs.zip")),await ed(Vn(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function vh(){return[await zC(),await qC()].filter(e=>e!==null).sort((e,t)=>yh.rcompare(e.version,t.version))}async function Gn(){let n=Pt();for(let e of await vh())if(e.apiVersion<=n)return e.version;return null}async function Ys(){let n=Pt(),e=await vh(),t=!1;for(let r of e){if(r.apiVersion>n){p(`docs: skip candidate v${r.version} (apiVersion ${r.apiVersion} > ${n})`),t=!0;continue}try{let i=Vn(r.dir,"dist","engine","index.js");return await import(VC(i).href)}catch(i){p(`docs: candidate v${r.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw t?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please run `devecocli docs update` or reinstall CLI")}var ro=class{constructor(e){this.actionCommand=e}cache=new Sr(Ks.join(W(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=mt(),t=Bn(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&dr(c,e)>0&&a.push(YC(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.log();for(let d of a)console.log(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){p(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=Pt(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let r=this.cache.getLatestCompatibleDocsVersion();if(!r)return{message:null,stale:!1};let i=await Gn();return i&&dr(r,i)<=0?{message:null,stale:!1}:{message:KC(`New docs version ${r} available, run \`devecocli docs update\` to upgrade`),stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await ZC(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];p(`Executing: ${process.execPath} ${e.join(" ")}`),JC(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{p("Update check lock held by another process, skipping")}}};async function ZC(n,e){await wh.promises.mkdir(Ks.dirname(n),{recursive:!0});let t=await XC.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import{execa as td}from"execa";import*as Sh from"semver";function rd(n){return{version:n.version,apiVersion:n.apiVersion??0,dist:n.dist}}function no(n){return Array.isArray(n)?n[0]:n}async function QC(n){p(`Executing: npm view ${n} --json`);let{stdout:e}=await td("npm",["view",n,"--json"]);return no(JSON.parse(e))}async function qn(n){p(`Executing: npm view ${jt} --json`);let{stdout:e}=await td("npm",["view",jt,"--json"]),t=no(JSON.parse(e)),r=rd(t);if(r.apiVersion<=n)return{latest:r,compatible:r};let i=ek(t.versions,n);if(i)return{latest:r,compatible:i};p(`Executing: npm view ${jt} versions --json`);let{stdout:o}=await td("npm",["view",jt,"versions","--json"]),s=JSON.parse(o);for(let a=s.length-1;a>=0;a--){let c=s[a];if(c===r.version)continue;let l=rd(await QC(`${jt}@${c}`));if(l.apiVersion<=n)return{latest:r,compatible:l}}return{latest:r,compatible:null}}function ek(n,e){if(!n||typeof n!="object"||Array.isArray(n))return null;let t=Object.entries(n).filter(([,r])=>(r.apiVersion??0)<=e).map(([r,i])=>rd({...i,version:i.version??r}));return t.length===0?null:(t.sort((r,i)=>Sh.rcompare(r.version,i.version)),t[0])}import{execa as bh}from"execa";import*as Ct from"path";import*as ue from"fs/promises";import*as Eh from"crypto";async function tk(n,e){let t=`${n}.tmp.${process.pid}`;await ue.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ue.rename(t,n)}function rk(n,e){let t=e.indexOf("-");if(t<0)return!1;let r=e.slice(0,t),i=e.slice(t+1);if(r!=="sha512")return!1;let o=Buffer.from(i,"base64");return Eh.createHash(r).update(n).digest().equals(o)}async function nk(n,e,t){p(`Executing: npm pack ${jt}@${n}`);let{stdout:r}=await bh("npm",["pack",`${jt}@${n}`],{cwd:t}),i=r.trim().split(`
|
|
81
|
-
`).pop(),o=
|
|
82
|
-
${
|
|
82
|
+
Application '${t}' installed successfully (no ability to launch).`)}function QT(r){let e={event:v.CommandExecuted,args:["run",...r.module?["--module"]:[],...r.device?["--device"]:[],...r.product?["--product"]:[],...r.buildMode?["--build-mode"]:[],...r.ability?["--ability"]:[],...r.uninstall?["--uninstall"]:[],...r.skipBuild?["--skip-build"]:[],...r.apply?["--apply"]:[],...r.hotreload?["--hotreload"]:[],...r.hotreloadApply?["--hotreload-apply"]:[]]};return r.buildMode&&(e.build_mode=r.buildMode),r.module&&(e.module_count=r.module.length),e}var eN=new XT("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/").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.").action(async r=>{let e=QT(r),t=Date.now(),n=!0,i=null;try{let o=await rN(r,e);o&&(o.ohpmMemoryMb&&(e.ohpm_install_memory=o.ohpmMemoryMb),o.syncMemoryMb&&(e.hvigor_sync_memory=o.syncMemoryMb),o.buildMemoryMb&&(e.hvigor_build_memory=o.buildMemoryMb))}catch(o){n=!1,i=Z(o),console.error(ZT(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(e,o)}});async function tN(r,e,t,n,i){let o=new Ji(e,r.rootDir),s=new ht(e,r.rootDir),a=new Set;for(let{moduleName:y,targetName:D}of t)for(let K of r.collectNonHarDependentModuleList(y))a.add(`${K}@${D}`);let c=[...a],l=zp(r,c),d={type:"modules",modulesToBuild:c,moduleTasks:l},h=await xr(r.rootDir,()=>(lr.removeAll(r),Jp(o,s,n,i,d,r.rootDir)),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
|
|
83
|
+
`+Ls("Build completed successfully.")),h}async function rN(r,e){let t=W.discover(process.cwd());await rt.warnInvalidBundledLinks(t.rootDir),console.warn(Sl("Ensure the project source is trusted before proceeding."));let n=await P.new();if(r.skipBuild||n.assertJava(),e.bundle_name=t.getBundleName(),r.hotreloadApply){await oN(r,t,n);return}if(r.hotreload){await iN(r,t,n);return}if(r.apply){await aN(r,t,n);return}return vb(r,t,n)}async function nN(r,e,t){r.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let n=new ht(e,t.rootDir),i=setInterval(async()=>{await n.isDaemonAlive()||(clearInterval(i),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function iN(r,e,t){if(r.hotreload==="stop"){await iv(t,e);return}let i=Rf(e,r.module).map(kf),{moduleName:o,targetName:s}=i[0];rf(r.module,o);let a=new le(t),c=ce.from(t),l=await El(c,r.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=r.product||"default";e.validateProduct(h);let y=e.getBundleName(h),D=yb(e,i,r.ability);Jc.generate(e.rootDir,o,h,t);let K=new ht(t,e.rootDir);console.log(Ls("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await K.ensureDaemonRunning();let we=[`${o}@${h}`];for(let Un of e.collectNonHarDependentModuleList(o))we.includes(`${Un}@${h}`)||we.push(`${Un}@${h}`);console.log(Ls("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let ut=new ro(e.rootDir,t);await ut.startWatchSession({moduleSpecs:we,productName:h});let tr=nv(e,o,s,d,h);await wb(a,l,y,tr,D,!!r.uninstall),console.log(Ls("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.")),await nN(ut,t,e)}async function oN(r,e,t){let n=r.hotreloadApply;if(!n)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Fs.basename(n)!==n)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n}`);let i=Rf(e,r.module),{moduleName:o}=kf(i[0]);rf(r.module,o);let s=ce.from(t),a=await El(s,r.device),c=r.product||"default";e.validateProduct(c);let l=e.getBundleName(c);rv(e,o,n);let d=[`${o}@${c}`],h=await tv({applyFileName:n,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function sN(r,e,t,n){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of r.collectNonHarDependentModuleList(o)){i.add(r.findArtifactPath(a,s,t,n));for(let c of r.findRemoteHspPaths(a,s,n))i.add(c)}return[...i]}async function vb(r,e,t){let i=Rf(e,r.module).map(kf);for(let{moduleName:we}of i){let ut=e.getModuleType(we);if(ut!=="entry"&&ut!=="feature"&&ut!=="shared")throw new w(`Module '${we}' '${ut}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let o=new le(t),s=ce.from(t),a=await El(s,r.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=r.product||"default";e.validateProduct(l);let d=r.buildMode||"debug",h;r.skipBuild||(h=await tN(e,t,i,l,d));let y=sN(e,i,c,l),D=e.getBundleName(l),K=yb(e,i,r.ability);return await wb(o,a,D,y,K,!!r.uninstall),K&&await Cf({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:o,targetDeviceId:a,bundleName:D}),h}async function aN(r,e,t){let n=r.apply;if(!n)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Fs.basename(n)!==n)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n}`);let i=Fs.join(e.rootDir,".hvigor",n),o=ce.from(t),s=await El(o,r.device),a=r.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(y=>e.getModuleType(y.name)==="entry")?.name,d=l?e.getMainAbility(l,r.ability):r.ability||"EntryAbility",h=new zc(t,e.rootDir);try{await h.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(y){console.warn(Sl(`[Apply] failed: ${y.message}`)),console.warn(Sl('[Apply] Falling back to full "devecocli run"...')),await vb(r,e,t);return}console.log(Sl('[Apply] Done. If changes did not take effect, run "devecocli run" for a full build.')),await Cf({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var bb=eN;import{Command as bN}from"commander";import*as Af from"path";import{red as Pb,cyan as Rl,yellow as xf}from"colorette";import{execa as Dl}from"execa";import{execa as cN}from"execa";function Pl(r){return Array.isArray(r)?r[0]:r}async function uo(r){let e=on();f(`Executing: npm view ${jt}@${e} --json`);let{stdout:t}=await cN("npm",["view",`${jt}@${e}`,"--json"]),n=Pl(JSON.parse(t)),i=typeof n.version=="string"?n.version.trim():n["dist-tags"]?.[e]?.trim();if(!i)throw new Error(`Could not resolve version for ${jt}@${e}`);let o=n.versions?.[i],s=n.dist??o?.dist;if(!s)throw new Error(`Could not resolve dist for ${jt}@${e}`);let a=n.apiVersion??o?.apiVersion??0,c={version:i,apiVersion:a,dist:s};return c.apiVersion<=r?{latest:c,compatible:c}:{latest:c,compatible:null}}import{execa as Sb}from"execa";import*as Vt from"path";import*as ye from"fs/promises";import*as Eb from"crypto";async function lN(r,e){let t=`${r}.tmp.${process.pid}`;await ye.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ye.rename(t,r)}function dN(r,e){let t=e.indexOf("-");if(t<0)return!1;let n=e.slice(0,t),i=e.slice(t+1);if(n!=="sha512")return!1;let o=Buffer.from(i,"base64");return Eb.createHash(n).update(r).digest().equals(o)}async function uN(r,e,t){f(`Executing: npm pack ${jt}@${r}`);let{stdout:n}=await Sb("npm",["pack",`${jt}@${r}`],{cwd:t}),i=n.trim().split(`
|
|
84
|
+
`).pop(),o=Vt.join(t,i),s=await ye.readFile(o);if(!dN(s,e))throw await ye.unlink(o).catch(()=>{}),new Error("Documentation package integrity verification failed");return o}async function pN(r,e,t){let n=Vt.join(t,e),i=Vt.join(t,`.tmp-${e}-${process.pid}`);return await ye.rm(n,{recursive:!0,force:!0}),await ye.rm(i,{recursive:!0,force:!0}),await ye.mkdir(i,{recursive:!0}),f(`Executing: tar -xzf ${Vt.basename(r)} -C ${i}`),await Sb("tar",["-xzf",r,"-C",i]),await ye.rename(Vt.join(i,"package"),n),await ye.rm(i,{recursive:!0,force:!0}),await ye.unlink(r).catch(()=>{}),await ye.access(Vt.join(n,"dist","engine","index.js")),await ye.access(Vt.join(n,"docs.zip")),await ye.access(Vt.join(n,"index.zip")),n}async function Cl(r,e,t){await ye.mkdir(e,{recursive:!0});let n=await uN(r.version,r.dist.integrity,e);return await pN(n,r.version,e),await lN(Vt.join(e,"current.json"),{version:r.version,apiVersion:r.apiVersion,installedAt:Date.now(),installedBy:t}),{version:r.version,apiVersion:r.apiVersion}}import*as kl from"fs";import*as po from"path";import{execa as fN}from"execa";import{yellow as mN}from"colorette";function hN(r){return r?r.endsWith(".ts"):!0}function gN(r,e){let t=po.join(r,"package.json");try{return JSON.parse(kl.readFileSync(t,"utf8")).name===e}catch{return!1}}function yN(r,e){let t;try{t=po.dirname(kl.realpathSync(r))}catch{return null}for(let n=0;n<20&&t&&t!==po.dirname(t);n++){if(gN(t,e))return t;t=po.dirname(t)}return null}async function wN(){try{f("Executing: npm root -g");let{stdout:r}=await fN("npm",["root","-g"]);return r.trim()||null}catch(r){return f(`[install-check] npm root -g failed: ${r instanceof Error?r.message:String(r)}`),null}}function vN(r,e){return mp(r,e)}async function Df(r){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if(hN(e))return;let t=await wN();if(!t)return;let n=yN(e,r);if(!n){f("[install-check] running package root not found, skipping");return}vN(n,t)||(console.log(),console.log(mN(`Warning: devecocli is running from
|
|
85
|
+
${n}
|
|
83
86
|
but \`npm\` in PATH installs global packages to
|
|
84
87
|
${t}
|
|
85
88
|
The devecocli binary in PATH does not match the npm that \`devecocli update\` uses.
|
|
86
89
|
The update would land in the wrong place and would not reach the binary you are running.
|
|
87
90
|
Continuing with update \u2014 abort if this is unexpected.
|
|
88
|
-
Fix: run \`which -a devecocli\` (Windows: \`where devecocli\`) to list all shims, remove the stale one, or reinstall with the matching npm: \`npm install -g ${
|
|
89
|
-
${
|
|
90
|
-
New version found: ${o} (current: ${e})`)),console.log(
|
|
91
|
-
CLI successfully updated to ${o}`)),await
|
|
91
|
+
Fix: run \`which -a devecocli\` (Windows: \`where devecocli\`) to list all shims, remove the stale one, or reinstall with the matching npm: \`npm install -g ${r}@latest\`.`)))}var Tf=new bN("update").description("Update deveco-cli to latest");Tf.command("_check",{hidden:!0}).action(async()=>{let r=Date.now(),e=new sn(Af.join(j(),"update"));try{let t=on(),n=ji();f(`Executing: npm view ${n}@${t} --json`);let{stdout:i}=await Dl("npm",["view",`${n}@${t}`,"--json"]),{latestVersion:o,blockedVersions:s}=EN(i,t),a=await SN().catch(c=>{f(`Docs version check failed: ${c instanceof Error?c.message:String(c)}`)});await e.writeSuccess(o,s,cr(),t,a),await Cb(r,!0,null)}catch(t){await e.writeError(t instanceof Error?t.message:String(t));let n=t,i=n.code??n.name??"UnknownError";await Cb(r,!1,i)}});async function SN(){let r=$t(),{latest:e,compatible:t}=await uo(r);return{latestDocsVersion:e.version,latestDocsApiVersion:e.apiVersion,latestCompatibleDocsVersion:t?.version??null,checkedAgainstDocsApi:r}}function EN(r,e){let t=Pl(JSON.parse(r)),n=null;typeof t.version=="string"?n=t.version.trim():t["dist-tags"]?.[e]&&(n=t["dist-tags"][e].trim());let i=[];return Array.isArray(t.blockedVersions)?i=t.blockedVersions:n&&t.versions?.[n]?.blockedVersions&&(i=t.versions[n].blockedVersions),{latestVersion:n,blockedVersions:i}}var PN={event:v.CommandExecuted,args:["update"]},CN={event:v.CommandExecuted,args:["update","_check"]};async function If(r,e,t){let n={duration_ms:Date.now()-r,success:e,error_code:t};await R.track(PN,n).catch(()=>{})}async function Cb(r,e,t){let n={duration_ms:Date.now()-r,success:e,error_code:t};await R.track(CN,n).catch(()=>{})}async function kN(r,e,t){let n=t,i=n.code??n.name??"UnknownError";console.error(Pb(`Failed to update ${r}`)),n.message&&console.error(Pb(n.message)),await If(e,!1,i),process.exit(1)}Tf.action(async()=>{if(Hi()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await Df(ji());let r=Date.now(),e=cr(),t=on(),n=ji();console.log(Rl("Checking for updates..."));try{let{stdout:i}=await Dl("npm",["view",n,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(xf(`
|
|
92
|
+
${n} is already up to date (v${e}, tag: ${t})`)),await If(r,!0,null);return}console.log(Rl(`
|
|
93
|
+
New version found: ${o} (current: ${e})`)),console.log(Rl(`Updating ${n}...`)),await Dl("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(xf(`
|
|
94
|
+
CLI successfully updated to ${o}`)),await RN(o).catch(s=>{f(`Docs auto-sync failed: ${s instanceof Error?s.message:String(s)}`)}),await If(r,!0,null)}catch(i){await kN(n,r,i)}});async function RN(r){let e=ji();f(`Executing: npm view ${e}@${r} --json`);let{stdout:t}=await Dl("npm",["view",`${e}@${r}`,"--json"]),n=Pl(JSON.parse(t)),i=typeof n.supportedDocsApi=="number"?n.supportedDocsApi:$t(),{compatible:o}=await uo(i);if(!o){f("Docs auto-sync: no compatible docs version found, skipping");return}let s=Af.join(j(),"doc-data"),a=await Bi();(!a||nn(o.version,a)>0)&&await Cl({version:o.version,apiVersion:o.apiVersion,dist:o.dist},s,"cli-update"),console.log(xf(`Docs has been automatically synced to the compatible version ${o.version}`));let c=await uo(i).catch(()=>null);c?.compatible&&nn(c.compatible.version,o.version)>0&&console.log(Rl(`New docs version ${c.compatible.version} available, run \`devecocli docs update\` to upgrade`))}var kb=Tf;import{Command as sO,Option as fS}from"commander";import{execa as xl}from"execa";function Fe(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}function Rb(r){let e=r.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as DN}from"child_process";var xN=2500;function IN(r,e,t,n,i,o){r.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?n():i(a||`Emulator process exited with code ${s}`)})}function AN(r,e,t,n){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),r.removeAllListeners(),r.stderr?.removeAllListeners(),r.stderr?.destroy(),r.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),r.removeAllListeners(),r.stderr?.removeAllListeners();try{r.kill()}catch{}n(new Error(d))}},l=setTimeout(a,xN);r.once("error",d=>c(d.message)),IN(r,l,s,a,c,o)}function Db(r,e,t){f(`Spawning emulator: ${r} ${t.join(" ")}`);let n=[],i=DN(r,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});i.stderr?.on("data",a=>n.push(a));let o=i.pid!==void 0&&!Ze()?zi(i.pid,500,!0):void 0,s=new Promise((a,c)=>{AN(i,n,a,c)});return{pid:i.pid,started:s,tracker:o}}import*as fo from"path";function TN(r){let e=new Set,t=[];for(let n of r){let i=JSON.stringify(n);e.has(i)||(e.add(i),t.push(n))}return t}function NN(r){let e=r.instancePath?.trim();if(e)return fo.dirname(fo.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?fo.dirname(fo.normalize(t)).replace(/\\/g,"/"):""}function _N(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function xb(r,e,t){let n=[...r],i=t?.bootMode??e;return i&&n.push("-bootmode",i),t?.hdcPort!==void 0&&n.push("-hdcport",String(t.hdcPort)),t?.noWindow&&n.push("-noWindow"),n}function MN(r,e,t,n){let i=[xb(["-start",r],t,n)],o=NN(e);if(o)for(let s of _N(e.imageRoot))i.push(xb(["-hvd",r,"-path",o,...s],t,n));return TN(i)}async function Ib(r,e,t,n,i){let o=new Error("No start strategy ran"),s=MN(r,e,n,i);for(let a of s){let c;try{return c=t(a),await c.started,{ok:!0,args:a,tracker:c.tracker}}catch(l){if(c?.tracker)try{await c.tracker.stop()}catch{}o=l}}return{ok:!1,lastError:o}}function ON(r){let e=r.normalize("NFKC").match(/^\s*chargingStatus\s*:\s*(\d+)\s*$/im);if(!e)return;let t=Number(e[1]);if(t===1||t===3)return!0;if(t===0||t===2)return!1}async function Nf(r){return(await ce.withHdcPath(r).listDevices()).map(t=>t.serial).filter(ur)}async function _f(r){let e=await Nf(r);return e.length===0?[]:(await Promise.all(e.map(n=>qc(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Ab(r,e){return(await _f(r)).includes(e)}async function Tb(r,e){let t=await ce.withHdcPath(r).listDevicesWithName(),n=e.normalize("NFKC").replace(/\s+/g," ").trim(),i=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===n);if(!i||!ur(i.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let o=["-t",i.serial,"shell","hidumper","-s","3302","-a","-i"];f(`Executing: ${r} ${o.join(" ")}`);let s=await C(r,o);if(s.exitCode===0){let a=ON(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as ho from"path";import{existsSync as LN,statSync as FN}from"fs";function mo(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function $N(r){let e=mo(r,["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,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return n.trim()}return""}function jN(r){return mo(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function HN(r,e){for(let t of e){let n=r[t];if(!(n==null||n===""))return n===!0||String(n).toLowerCase()==="true"}}function UN(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=ho.dirname(ho.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=E.ensurePathWithinRoot(t,ho.join(t,n.name));LN(i)&&FN(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function BN(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=jN(t),i=mo(t,["deviceType","DeviceType","devicetype"]),o=mo(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:$N(t),path:mo(t,["path","Path","hvdPath","hvd_path"]),imageRoot:mo(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:i||void 0,osVersion:o||void 0,hotBoot:HN(t,["isHotBoot","ishotboot","hotBoot"])}}).filter(t=>t.name):null}catch{return null}}function WN(r){let e=[],t=/^(name|isrunning|ishotboot|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,i;for(;(i=t.exec(r))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=o.toLowerCase();a==="isrunning"?n.isRunning=s.trim().toLowerCase()==="true":a==="ishotboot"?n.hotBoot=s.trim().toLowerCase()==="true":a==="instancepath"?n.instancePath=s.trim():a==="path"?n.path=s.trim():a==="imageroot"?n.imageRoot=s.trim():a==="devicetype"?n.deviceType=s.trim():a==="os.osversion"&&(n.osVersion=s.trim())}}return n&&e.push(n),e}function Nb(r){let t=BN(r)??WN(r);return UN(t),t}function Mf(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function VN(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function GN(r){let e=Mf(r,["osVersion","OsVersion","OSVersion"]),t=Mf(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=Mf(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function _b(r,e=()=>!0){let t=r.trim();if(!t)return[];try{let n=JSON.parse(t);if(!Array.isArray(n))return[];let i=[];for(let o of n){if(!o||typeof o!="object")continue;let s=o;if(!e(s))continue;let a=GN(s);a&&i.push(a)}return i}catch{return[]}}function Mb(r){return _b(r)}function Ob(r){return _b(r,VN)}var Lb=/no images are available/i,qN=/Scenario simulation failed\s*[::]/i,zN="7.0.0";function $r(r){return r.normalize("NFKC").trim().toLowerCase()}function JN(r){let e=r.message||"";return Lb.test(e)}function KN(r){return r.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function $s(r,e){return`${r} ${e.join(" ")}`.trim()}function YN(r){switch(r.type){case"gps":return`${r.type}:${r.key}=${r.value}`;case"sensor":return`${r.type}:${r.key}=${r.value}`;case"rotation":case"volume":return`${r.type}:${r.direction}`;case"folded-state":return`${r.type}:${r.state}`;case"battery":return`${r.type}:${r.level}`;case"battery-status":return`${r.type}:${r.status}`;default:return r.type}}var go=class r{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,n){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=n}static from(e){return new r(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return f(`Executing: ${$s(this.emulatorPath,e)}`),xl(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Db(this.emulatorPath,this.sdkPath,e)}async listEmulators(e){let t=["-list","-details"];e!==void 0&&t.push("-instancePath",e);let{stdout:n}=await this.executeEmulator(t);return Nb(n)}async listEmulatorDetails(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return e}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set(Fe(n.name),n.deviceType)}catch{}return e}async startEmulator(e,t){let n=await this.listEmulators(),i=Fe(e),o=n.find(c=>Fe(c.name)===i);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let s=o.name;if(await this.isAlreadyRunning(s,o))return{status:"already-running"};let a=await Ib(s,o,c=>this.executeEmulatorDetached(c),o.hotBoot===!1?"coldboot":"snapshot",t);if(a.ok)return{status:"started",args:a.args,tracker:a.tracker};if(await this.isAlreadyRunning(s))return{status:"already-running"};throw new w(`Unable to start emulator "${e}". All methods failed.
|
|
92
95
|
Last error: ${a.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
|
|
93
|
-
Last error: ${a.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:
|
|
94
|
-
`).trim(),a=
|
|
95
|
-
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(
|
|
96
|
-
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e){let t=await this.listEmulators(e.instancePath),
|
|
97
|
-
`)}),!await this.waitForEmulatorPresenceByList(t,e.instancePath))throw new
|
|
98
|
-
The device may be running.`,"Failed to delete device, The device may be running.");let a=["-delete",s];return t!==void 0&&a.push("-instancePath",t),a.push("-force"),await this.runEmulatorChecked(a,{printOutputOnSuccess:!1}),s}};import{
|
|
99
|
-
`)}async function oo(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=V(o),console.error(Yk(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(n,o)}}function Zk(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(De(t.name));r&&(t.deviceType=r)}}var Qk=["Name","Serial","Kind","Device Type"];function eI(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function Bh(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function tI(){console.log(Kk(" No active devices.")),console.log(Xk(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function rI(n){let t=[...n].sort(Bh).map(eI);console.log(Xt(Qk,t))}function nI(n){return{name:n.name??n.serial,serial:n.serial,kind:n.isEmulator?"emulator":"device",deviceType:n.deviceType}}function iI(n){let e=[...n].sort(Bh);console.log(JSON.stringify(e.map(nI),null,2))}async function oI(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Xn.from(e).getDeviceTypeByName();Zk(n,r)}async function jh(n,e,t,r="table"){try{let i=await n.getConnectedEntries();if(await oI(i,e),t?.stop(),r==="json"){iI(i);return}i.length===0?tI():rI(i)}catch(i){throw new S(`Failed to list devices: ${i.message}`,"Failed to list devices.")}finally{t?.stop()}}async function sI(n,e){let t=await n.listDevices();if(t.length<2)return;let r=["Multiple devices connected. Specify a device with:"];for(let i of t){let o=await n.getDeviceName(i.serial);r.push(` ${e} -t ${i.serial} # ${o}`)}throw new S(r.join(`
|
|
100
|
-
|
|
96
|
+
Last error: ${a.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:Ab(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),n=Fe(e),i=t.find(a=>Fe(a.name)===n);if(!i)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new w(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(i.name,i))throw new w(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!(t.assumedCharging?!0:await Tb(this.hdcPath,i.name))&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let o=this.buildControlArgs(i.name,t);f(`[EmulatorManager] control ${YN(t)} -> ${$s(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{extraReject:t.type==="folded-state"?[qN]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(r.supportedControlPaths.has(e))return;let t=["-version"];f(`Executing: ${$s(this.emulatorPath,t)}`);let{stdout:n,stderr:i,exitCode:o}=await xl(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[n,i].filter(Boolean).join(`
|
|
97
|
+
`).trim(),a=KN(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(P.compareVersion(a,zN)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);r.supportedControlPaths.add(e)}buildControlArgs(e,t){let n=["-instance",e];switch(t.type){case"shake":return[...n,"-shake"];case"power":return[...n,"-power"];case"rotation":return[...n,"-rotation",t.direction];case"volume":return[...n,"-volume",t.direction];case"folded-state":return[...n,"-foldedState",t.state];case"battery":return[...n,"-battery",String(t.level)];case"battery-status":return[...n,"-batteryStatus",String(t.status)];case"gps":return[...n,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...n,"-outdoorRunning"];case"outdoor-cycling":return[...n,"-outdoorCycling"];case"driving-navigation":return[...n,"-drivingNavigation"];case"sensor":return[...n,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unknown emulator control action type: ${t.type}`)}}async executeEmulatorInherit(e){f(`Executing: ${$s(this.emulatorPath,e)}`);let{exitCode:t}=await xl(this.emulatorPath,e,{stdio:"inherit",env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1});if(t!==0)throw new Error(`Emulator exited with code ${t===null?"null":t}.`)}async installEmulatorImage(e){let t=["-install","-deviceType",e.deviceType,"-osVersion",e.osVersion];e.force&&t.push("-force"),await this.executeEmulatorInherit(t)}async hasAvailableEmulatorImage(e){let t=await this.listEmulatorImages({deviceType:e.deviceType}),n=$r(e.deviceType),i=$r(e.osVersion);return Mb(t).some(o=>$r(o.deviceType)===n&&$r(o.osVersion)===i)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let n;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!JN(o))throw o;n=o}(n!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,n)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:n}=await this.executeEmulator(t);return n}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,n){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=n!==void 0?`Primary uninstall failed: ${n.message}
|
|
98
|
+
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(n=>n.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),n=Ob(t),i=$r(e.deviceType),o=$r(e.osVersion);return n.filter(s=>$r(s.deviceType)===i&&($r(s.osVersion)===o||$r(s.softwareVersion)===o))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Lb]})}async runEmulatorChecked(e,t){f(`Executing: ${$s(this.emulatorPath,e)}`);let{stdout:n,stderr:i,exitCode:o}=await xl(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[n,i].filter(Boolean).join(`
|
|
99
|
+
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e){let t=await this.listEmulators(e.instancePath),n=Fe(e.name),i=t.find(o=>Fe(o.name)===n);if(i)if(e.force)await this.deleteVirtualDevice(i.name,e.instancePath);else throw new w(`Emulator "${e.name}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return n}buildCreateVirtualDeviceArgs(e){let t=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];e.instancePath!==void 0&&t.push("-instancePath",e.instancePath),e.imageRoot!==void 0&&t.push("-imageRoot",e.imageRoot),e.screenProfile!==void 0&&t.push("-screenProfile",e.screenProfile),e.screen?.length&&t.push("-screen",...e.screen),e.storage!==void 0&&t.push("-storage",String(e.storage)),e.memory!==void 0&&t.push("-memory",String(e.memory));let n=e.hotBoot??(Rb(e.osVersion)?!0:void 0);return n!==void 0&&t.push("-hotBoot",String(n)),t}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e),n=this.buildCreateVirtualDeviceArgs(e);if(await this.runEmulatorChecked(n,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
100
|
+
`)}),!await this.waitForEmulatorPresenceByList(t,e.instancePath))throw new w(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`,"Emulator was reported as created, but it did not appear in the emulator list within the waiting period.")}async waitForEmulatorPresenceByList(e,t,n=1e4,i=500){let o=Date.now()+n;for(;Date.now()<o;){if((await this.listEmulators(t)).some(c=>Fe(c.name)===e))return!0;await new Promise(c=>setTimeout(c,i))}return!1}async deleteVirtualDevice(e,t){let n=await this.listEmulators(t),i=Fe(e),o=n.find(c=>Fe(c.name)===i);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let s=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(s,o))throw new w(`Failed to delete device: ${s}
|
|
101
|
+
The device may be running.`,"Failed to delete device, The device may be running.");let a=["-delete",s];return t!==void 0&&a.push("-instancePath",t),a.push("-force"),await this.runEmulatorChecked(a,{printOutputOnSuccess:!1}),s}};import{yellow as aO,gray as cO}from"colorette";import lO from"ora";import{green as XN}from"colorette";var ZN=[[4352,4447],[9001,9002],[11904,42191],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65281,65376],[65504,65510],[127744,129535],[131072,173791],[173824,177983],[177984,178207],[178208,183983],[183984,191456]],QN=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],e_=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Fb(r,e){for(let[t,n]of e)if(r>=t&&r<=n)return!0;return!1}function Of(r){let e=r.replace(e_,""),t=0,n=0;for(;n<e.length;){let i=e.codePointAt(n);if(i===void 0)break;Fb(i,QN)||(Fb(i,ZN)?t+=2:t+=1),n+=i>65535?2:1}return t}function $b(r,e){let t=Of(r);return r+" ".repeat(Math.max(0,e-t))}function t_(r,e){return r.map((t,n)=>{let i=Of(t);for(let o of e){let s=o.cells[n]??"";i=Math.max(i,Of(s))}return i})}function jr(r,e){let t=t_(r,e),n=[];n.push(r.map((i,o)=>$b(i,t[o])).join(" ")),n.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>$b(s??"",t[a])).join(" ").trimEnd();n.push(i.highlight?XN(o):o)}return n.join(`
|
|
102
|
+
`)}import{red as r_}from"colorette";async function N(r,e){let t=Date.now(),n=!0,i=null;try{await e()}catch(o){n=!1,i=Z(o),console.error(r_(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(r,o)}}async function _(){try{let r=await P.new();return{manager:ce.from(r),toolProvider:r}}catch(r){throw new w(`Failed to initialize device manager: ${r.message}`,"Failed to initialize device manager.")}}import{Command as n_,Option as Uf}from"commander";import{yellow as Bf}from"colorette";import{existsSync as Hb}from"fs";import Hr from"ora";function jb(r,e){let t=r.match(e);return t?t[1]:void 0}function Lf(r){let e=[],t=r.split(/(?=AbilityRecord ID #)/);for(let n of t){let i=n.match(/^\s*state #(\w+)/m);i&&i[1].toUpperCase()==="FOREGROUND"&&e.push({bundleName:jb(n,/app name \[([^\]]+)\]/),abilityName:jb(n,/main name \[([^\]]+)\]/)})}return e}function Ff(r){let e=[],t=o=>{typeof o.bundleName=="string"&&e.push({bundleName:o.bundleName,label:typeof o.label=="string"?o.label:void 0})},n;try{n=JSON.parse(r)}catch{n=null}if(Array.isArray(n)){for(let o of n)t(o);if(e.length>0)return e}let i=r.match(/\{[^{}]+\}/g)??[];for(let o of i)try{t(JSON.parse(o))}catch{}return e}function $f(r){let e=r.indexOf("{");if(e===-1)return null;try{return JSON.parse(r.slice(e))}catch{return null}}function jf(r){let e=r.trim();return{success:!/error:\s*failed to start|error code:\s*\d+|the specified ability does not exist/i.test(e),message:e}}function Hf(r){let e=r.hapModuleInfos,t=Array.isArray(e)&&e[0]?e[0]:void 0;return{bundleName:r.name,entryModuleName:r.entryModuleName,mainAbility:t?.mainAbility,versionCode:r.versionCode,versionName:r.versionName}}var mr=class{constructor(e){this.hdcPath=e}async listInstalledApps(e){let t=["-t",e,"shell","bm","dump","-a","-l"];f(`Executing: ${this.hdcPath} ${t.join(" ")}`);let n=await C(this.hdcPath,t);if(n.exitCode!==0)throw new Error(`bm dump -a -l failed: ${(n.stderr||n.stdout).trim()}`);return n.stdout}async getAppInfo(e,t){let n=["-t",e,"shell","bm","dump","-n",t];f(`Executing: ${this.hdcPath} ${n.join(" ")}`);let i=await C(this.hdcPath,n);if(i.exitCode!==0)throw new Error(`bm dump -n ${t} failed: ${(i.stderr||i.stdout).trim()}`);return i.stdout}async getForegroundApp(e){let t=["-t",e,"shell","aa","dump","-l"];f(`Executing: ${this.hdcPath} ${t.join(" ")}`);let n=await C(this.hdcPath,t);if(n.exitCode!==0)throw new Error(`aa dump -l failed: ${(n.stderr||n.stdout).trim()}`);return n.stdout}async startApp(e,t,n,i,o){let s=["-t",e,"shell","aa","start"];t&&s.push("-b",t),n&&s.push("-a",n),i&&s.push("-A",i),o&&s.push("-U",o),f(`Executing: ${this.hdcPath} ${s.join(" ")}`);let a=await C(this.hdcPath,s);if(a.exitCode!==0)throw new Error(`aa start failed: ${(a.stderr||a.stdout).trim()}`);return a.stdout}async clearAppData(e,t){let n=["-t",e,"shell","bm","clean","-d","-n",t];f(`Executing: ${this.hdcPath} ${n.join(" ")}`);let i=await C(this.hdcPath,n);if(i.exitCode!==0)throw new Error(`bm clean -d -n ${t} failed: ${(i.stderr||i.stdout).trim()}`);return i.stdout}async clearAppCache(e,t){let n=["-t",e,"shell","bm","clean","-c","-n",t];f(`Executing: ${this.hdcPath} ${n.join(" ")}`);let i=await C(this.hdcPath,n);if(i.exitCode!==0)throw new Error(`bm clean -c -n ${t} failed: ${(i.stderr||i.stdout).trim()}`);return i.stdout}};function i_(r,e){if(e==="json")console.log(JSON.stringify(r,null,2));else if(r.length>0)for(let t of r){let n=t.label||"";console.log(`${t.bundleName} ${n}`)}else console.log(Bf("No installed apps found."))}async function o_(r,e,t="default"){let n=await T(r,e),i=new mr(r.hdcPath),o=Hr({text:"Listing installed apps...",color:"cyan"}).start();try{let s=await i.listInstalledApps(n);o.stop();let a=Ff(s);i_(a,t)}catch(s){throw o.stop(),new w(`Failed to list apps: ${s.message}`,"Failed to list apps.")}}function s_(r,e){if(r.length>0)if(e==="json")console.log(JSON.stringify(r,null,2));else for(let t of r)console.log(`${t.bundleName??""}#${t.abilityName??""}`);else console.log(e==="json"?"[]":Bf("No foreground app."))}async function a_(r,e,t="default"){let n=await T(r,e),i=new mr(r.hdcPath),o=Hr({text:"Querying foreground app...",color:"cyan"}).start();try{let s=await i.getForegroundApp(n);o.stop();let a=Lf(s);s_(a,t)}catch(s){throw o.stop(),new w(`Failed to get foreground app: ${s.message}`,"Failed to get foreground app.")}}async function c_(r,e,t,n="default"){let i=await T(r,t),o=new mr(r.hdcPath),s=Hr({text:`Querying app info for ${e}...`,color:"cyan"}).start();try{let a=await o.getAppInfo(i,e);s.stop();let c=$f(a);if(!c)throw new w(`No app info found for ${e}. The app may not be installed.`,"No app info found. The app may not be installed.");if(n==="json")console.log(JSON.stringify(c,null,2));else{let l=Hf(c);console.log(` bundleName: ${l.bundleName??"-"}`),console.log(` entryModuleName: ${l.entryModuleName??"-"}`),console.log(` mainAbility: ${l.mainAbility??"-"}`),console.log(` versionCode: ${l.versionCode??"-"}`),console.log(` versionName: ${l.versionName??"-"}`)}}catch(a){throw s.stop(),new w(`Failed to get app info: ${a.message}`,"Failed to get app info.")}}async function l_(r,e){if(!e.bundle&&!e.action&&!e.uri)throw new w("At least one of --bundle, --action, or --uri must be provided.","At least one of --bundle, --action, or --uri must be provided.");if(e.bundle&&!e.ability)throw new w("--ability is required when --bundle is specified.","--ability is required when --bundle is specified.");let t=await T(r,e.device),n=new mr(r.hdcPath),i=e.bundle??"(no bundle)",o=Hr({text:`Starting app ${i}...`,color:"cyan"}).start();try{let s=await n.startApp(t,e.bundle,e.ability,e.action,e.uri);o.stop();let{success:a,message:c}=jf(s);if(!a)throw new w(`Failed to start app: ${c}`,"Failed to start app. The app or ability may not be installed.");console.log(`App ${i}: ${c}`)}catch(s){throw o.stop(),new w(`Failed to start app: ${s.message}`,"Failed to start app.")}}async function d_(r,e){let t=await T(r,e.device),n=new le(r),i=Hr({text:`Stopping app ${e.bundle}...`,color:"cyan"}).start();try{let o=await n.forceStopApp(t,e.bundle);i.stop();let s=o.trim();if(s&&/error|failed|not found|not installed/i.test(s))throw new w(s,"Failed to stop app.");console.log(`Stopped app ${e.bundle}.`)}catch(o){throw i.stop(),new w(o.message,"Failed to stop app.")}}function u_(r,e){if(r.length===0&&!e.shared?.length)throw new w("At least one package file or --shared must be provided.","At least one package file or --shared must be provided.");for(let t of r)if(!Hb(t))throw new w(`HAP file not found: ${t}`,"HAP file not found.");if(e.shared){for(let t of e.shared)if(!Hb(t))throw new w(`Shared HSP file not found: ${t}`,"Shared HSP file not found.")}}function p_(r,e){let t=[];return r.length>0&&t.push(r.length===1?r[0]:`${r.length} packages`),e.shared?.length&&t.push(`${e.shared.length} shared HSP(s)`),t.join(" + ")}async function f_(r,e,t){let n=await T(r,t.device);u_(e,t);let i={replace:t.replace,shared:t.shared,wait:t.wait,user:t.user},o=new le(r),s=p_(e,t),a=Hr({text:`Installing ${s}...`,color:"cyan"}).start();try{await o.installApp(n,e,i),a.stop(),console.log(`Installed ${s}.`)}catch(c){throw a.stop(),new w(c.message,"Failed to install app.")}}async function m_(r,e){let t=await T(r,e.device),n=new le(r),i=Hr({text:`Uninstalling ${e.bundle}...`,color:"cyan"}).start();try{let o=await n.uninstallApp(t,e.bundle);i.stop(),console.log(o?`Uninstalled ${e.bundle}.`:Bf(`${e.bundle} was not installed.`))}catch(o){throw i.stop(),new w(`Failed to uninstall app: ${o.message}`,"Failed to uninstall app.")}}async function h_(r,e){E.assertBundleNameStrict(e.bundle);let t=await T(r,e.device),n=new mr(r.hdcPath),i=Hr({text:`Clearing cache for ${e.bundle}...`,color:"cyan"}).start();try{let o=await n.clearAppCache(t,e.bundle);i.stop();let s=o.trim();if(s&&/error|failed|not found|not installed/i.test(s))throw new w(s,"Failed to clear app cache.");console.log(`Cleared cache for ${e.bundle}.`)}catch(o){throw i.stop(),new w(o.message,"Failed to clear app cache.")}}async function g_(r,e){E.assertBundleNameStrict(e.bundle);let t=await T(r,e.device),n=new mr(r.hdcPath),i=Hr({text:`Clearing data for ${e.bundle}...`,color:"cyan"}).start();try{let o=await n.clearAppData(t,e.bundle);i.stop();let s=o.trim();if(s&&/error|failed|not found|not installed/i.test(s))throw new w(s,"Failed to clear app data.");console.log(`Cleared data for ${e.bundle}.`)}catch(o){throw i.stop(),new w(o.message,"Failed to clear app data.")}}var Gt=new n_("app").description("Manage apps on a connected device");Gt.command("list").description("List installed apps").option("--device <name|serial>","Target device (name or serial)").addOption(new Uf("--format <format>","Output format").choices(["default","json"]).default("default")).action(async r=>{let{device:e,format:t}=r,n={event:v.CommandExecuted,args:["device","app","list",...t==="json"?["--format","json"]:[],...e?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await o_(i,e,t)})});Gt.command("foreground").description("Show current foreground app info").option("--device <name|serial>","Target device (name or serial)").addOption(new Uf("--format <format>","Output format").choices(["default","json"]).default("default")).action(async r=>{let{device:e,format:t}=r,n={event:v.CommandExecuted,args:["device","app","foreground",...t==="json"?["--format","json"]:[],...e?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await a_(i,e,t)})});Gt.command("info").description("Show app info").option("--device <name|serial>","Target device (name or serial)").addOption(new Uf("--format <format>","Output format").choices(["default","json"]).default("default")).argument("<bundleName>","Bundle name to query").action(async(r,e)=>{let{device:t,format:n}=e,i={event:v.CommandExecuted,args:["device","app","info","<bundleName>",...n==="json"?["--format","json"]:[],...t?["--device"]:[]]};await N(i,async()=>{let{toolProvider:o}=await _();await c_(o,r,t,n)})});Gt.command("start").description("Start an app on the device").option("--device <name|serial>","Target device (name or serial)").option("--bundle <name>","Bundle name (e.g. com.example.app)").option("--ability <name>","Ability to start (-a)").option("--action <action>","Action to send (-A)").option("--uri <uri>","URI to start with (-U)").action(async r=>{let e={event:v.CommandExecuted,args:["device","app","start",...r.bundle?["--bundle"]:[],...r.ability?["--ability"]:[],...r.action?["--action"]:[],...r.uri?["--uri"]:[],...r.device?["--device"]:[]]};await N(e,async()=>{let{toolProvider:t}=await _();await l_(t,r)})});Gt.command("install").description("Install package(s) on the device").option("--device <name|serial>","Target device (name or serial)").option("--replace","Override install").option("--shared <path>","Inter-app shared HSP path (repeatable)",(r,e)=>[...e,r],[]).option("--wait <seconds>","Install wait time in seconds",r=>parseInt(r,10)).option("--user <userId>","Target user ID").argument("[files...]","Local package path(s) to install (hap/hsp)").action(async(r,e)=>{let t={event:v.CommandExecuted,args:["device","app","install",...r.map(()=>"<file>"),...e.replace?["--replace"]:[],...e.shared?.length?["--shared"]:[],...e.wait!==void 0?["--wait"]:[],...e.user?["--user"]:[],...e.device?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await f_(n,r,e)})});Gt.command("uninstall").description("Uninstall an app from the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async r=>{let e={event:v.CommandExecuted,args:["device","app","uninstall","--bundle",...r.device?["--device"]:[]]};await N(e,async()=>{let{toolProvider:t}=await _();await m_(t,r)})});Gt.command("stop").description("Stop an app on the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async r=>{let e={event:v.CommandExecuted,args:["device","app","stop","--bundle",...r.device?["--device"]:[]]};await N(e,async()=>{let{toolProvider:t}=await _();await d_(t,r)})});Gt.command("clearcache").description("Clear app cache on the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async r=>{let e={event:v.CommandExecuted,args:["device","app","clearcache","--bundle",...r.device?["--device"]:[]]};await N(e,async()=>{let{toolProvider:t}=await _();await h_(t,r)})});Gt.command("cleardata").description("Clear app data on the device").option("--device <name|serial>","Target device (name or serial)").requiredOption("--bundle <name>","Bundle name").action(async r=>{let e={event:v.CommandExecuted,args:["device","app","cleardata","--bundle",...r.device?["--device"]:[]]};await N(e,async()=>{let{toolProvider:t}=await _();await g_(t,r)})});import{Command as fn}from"commander";import{red as Ub,yellow as y_}from"colorette";import mn from"ora";function Ve(r){let e=`${r.stdout}
|
|
103
|
+
${r.stderr}`;if(/testhelper.*(?:not found|inaccessible)/i.test(e))throw new Error("testhelper is not available on this device. Please upgrade the device system version to support this command.")}var yt=class{constructor(e){this.toolProvider=e}async getDeviceType(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","param","get","const.product.devicetype"])).stdout}async wakeScreen(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","wakeup"])).stdout}async suspendScreen(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","suspend"])).stdout}async getScreenStatus(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","PowerManagerService","-a","-s"])).stdout}async getDisplayInfo(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","DisplayManagerService","-a","-a"])).stdout}async swipeScreen(e,t,n,i,o,s=6e3){let a=await C(this.toolProvider.hdcPath,["-t",e,"shell","uitest","uiInput","swipe",String(t),String(n),String(i),String(o),String(s)]);if(a.exitCode!==0)throw new Error(a.stderr||a.stdout||"swipe failed");return a.stdout}async getTime(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-time"]);return Ve(t),t.stdout}async setTime(e,t){let n=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-time",t]);return Ve(n),n.stdout}async getTimezone(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-timezone"]);return Ve(t),t.stdout}async setTimezone(e,t){let n=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-timezone",t]);return Ve(n),n.stdout}};function ai(r){let e=r.match(/\[DISPLAY INFO\][\s\S]*?Width:\s*(\d+)[\s\S]*?Height:\s*(\d+)/);return e?{width:Number(e[1]),height:Number(e[2])}:null}function Wf(r){let e=r.match(/Current State:\s*(\w+)/);return e?e[1]:null}var yo=class{constructor(e){this.toolProvider=e}async getDisplayInfo(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","DisplayManagerService","-a","-a"])).stdout}async setScreenTimeout(e,t){return await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","PowerManagerService","-a","-f"]),(await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","timeout","-o",String(t)])).stdout}async setScreenNeverSleep(e){return await C(this.toolProvider.hdcPath,["-t",e,"shell","power-shell","timeout","-r"]),(await C(this.toolProvider.hdcPath,["-t",e,"shell","hidumper","-s","PowerManagerService","-a","-t"])).stdout}};var w_=["phone","tablet"];async function Vf(r,e){let i=(await new yt(r).getDeviceType(e)).trim().toLowerCase();if(!w_.includes(i))throw new w(`This command is only supported on phone and tablet devices (current: ${i||"unknown"}).`,"Unsupported device type.")}async function v_(r,e){let t=await T(r,e),n=new yt(r),i=mn({text:"Waking screen...",color:"cyan"}).start();try{let o=await n.wakeScreen(t);i.stop();let s=o.trim();console.log(s||"Screen woken.")}catch(o){throw i.stop(),new w(`Failed to wake screen: ${o.message}`,"Failed to wake screen.")}}async function b_(r,e){let t=await T(r,e),n=new yt(r),i=mn({text:"Suspending screen...",color:"cyan"}).start();try{let o=await n.suspendScreen(t);i.stop();let s=o.trim();console.log(s||"Screen suspended.")}catch(o){throw i.stop(),new w(`Failed to suspend screen: ${o.message}`,"Failed to suspend screen.")}}async function S_(r,e){let t=await T(r,e),n=new yt(r),i=mn({text:"Querying screen status...",color:"cyan"}).start();try{let o=await n.getScreenStatus(t);i.stop();let s=Wf(o);console.log(s?` Screen State: ${s}`:y_("No screen state found in output."))}catch(o){throw i.stop(),new w(`Failed to get screen status: ${o.message}`,"Failed to get screen status.")}}async function E_(r,e){let t=await T(r,e);await Vf(r,t);let n=new yt(r),i=mn({text:"Unlocking screen...",color:"cyan"}).start();try{await n.wakeScreen(t);let o=await n.getDisplayInfo(t),s=ai(o);if(!s)throw new Error("Failed to parse screen resolution from display info");let a=Math.round(s.width/2),c=Math.round(s.height*.98),l=c-Math.round(s.height/2);await n.swipeScreen(t,a,c,a,l),i.stop(),console.log(`Screen unlocked: swipe (${a}, ${c}) -> (${a}, ${l})`)}catch(o){throw i.stop(),new w(`Failed to unlock screen: ${o.message}`,"Failed to unlock screen.")}}async function P_(r,e){let t=await T(r,e);await Vf(r,t);let n=new yt(r),i=mn({text:"Opening control center...",color:"cyan"}).start();try{let o=await n.getDisplayInfo(t),s=ai(o);if(!s)throw new Error("Failed to parse screen resolution from display info");let a=Math.round(s.width*4/5),c=Math.round(s.height*.02),l=c+Math.round(s.height/3);await n.swipeScreen(t,a,c,a,l),i.stop(),console.log(`Control center opened: swipe (${a}, ${c}) -> (${a}, ${l})`)}catch(o){throw i.stop(),new w(`Failed to open control center: ${o.message}`,"Failed to open control center.")}}async function C_(r,e){let t=await T(r,e);await Vf(r,t);let n=new yt(r),i=mn({text:"Opening notification center...",color:"cyan"}).start();try{let o=await n.getDisplayInfo(t),s=ai(o);if(!s)throw new Error("Failed to parse screen resolution from display info");let a=Math.round(s.width/5),c=Math.round(s.height*.02),l=c+Math.round(s.height/3);await n.swipeScreen(t,a,c,a,l),i.stop(),console.log(`Notification center opened: swipe (${a}, ${c}) -> (${a}, ${l})`)}catch(o){throw i.stop(),new w(`Failed to open notification center: ${o.message}`,"Failed to open notification center.")}}var k_=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;async function R_(r,e,t){let n=await T(r,t),i=new yt(r),o=e!==void 0;if(o&&!k_.test(e))throw new w(`Invalid time format. Time must be in 'YYYY-MM-DD HH:MM:SS' format (e.g. "2026-10-13 17:18:07").`,"Invalid time format.");let s=mn({text:o?`Setting time to ${e}...`:"Getting time...",color:"cyan"}).start();try{let a=o?await i.setTime(n,e):await i.getTime(n);s.stop();let c=a.trim();/^error/i.test(c)?(console.error(Ub(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new w(`Time ${o?"set":"get"} failed: ${a.message}`,`Time ${o?"set":"get"} failed.`)}}async function D_(r,e,t){let n=await T(r,t),i=new yt(r),o=e!==void 0,s=mn({text:o?`Setting timezone to ${e}...`:"Getting timezone...",color:"cyan"}).start();try{let a=o?await i.setTimezone(n,e):await i.getTimezone(n);s.stop();let c=a.trim();/^error/i.test(c)?(console.error(Ub(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new w(`Timezone ${o?"set":"get"} failed: ${a.message}`,`Timezone ${o?"set":"get"} failed.`)}}var Bb=[new fn("wake").description("Wake up the device screen").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","wake",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await v_(n,e)})}),new fn("sleep").description("Turn off the device screen").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","sleep",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await b_(n,e)})}),new fn("status").description("Query screen power state").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","status",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await S_(n,e)})}),new fn("unlock").description("Unlock the screen").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","unlock",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await E_(n,e)})}),new fn("open-control-center").description("Open the control center").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","open-control-center",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await P_(n,e)})}),new fn("open-notification-center").description("Open the notification center").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","open-notification-center",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await C_(n,e)})}),new fn("time").description("Get or set the device time").option("--device <name|serial>","Target device (name or serial)").argument("[datetime]","Datetime to set; omit to get current time").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","time",...r?["<datetime>"]:[],...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await R_(i,r,t)})}),new fn("timezone").description("Get or set the device timezone").option("--device <name|serial>","Target device (name or serial)").argument("[timezone]","Timezone to set; omit to get current timezone").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","timezone",...r?["<timezone>"]:[],...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await D_(i,r,t)})})];import{Command as OM,Option as LM}from"commander";import{yellow as FM}from"colorette";import ea from"ora";import{appendFileSync as h7}from"fs";var qt={TRACE:10,DEBUG:20,INFO:30,WARN:40,ERROR:50,SILENT:100},Vb={10:"TRACE",20:"DEBUG",30:"INFO",40:"WARN",50:"ERROR",100:"SILENT"};function Gf(r){if(typeof r=="number")return r;let e=String(r||"").toUpperCase();return e in qt?qt[e]:qt.INFO}function x_(r){return{write:r}}function I_({useStderr:r}={}){return x_((e,t)=>{let n=`${A_[Vb[e.level]]||""}${t}`;r||e.level>=qt.ERROR?process.stderr.write(n+`
|
|
104
|
+
`):process.stdout.write(n+`
|
|
105
|
+
`)})}var A_={TRACE:"",DEBUG:"",INFO:"",WARN:"",ERROR:""};function T_(r){let e=new Date(r),t=(n,i=2)=>String(n).padStart(i,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}var js=class r{name;level;transports;fields;timestamp;constructor(e={}){this.name=e.name||"hm",this.level=Gf(e.level??"info"),this.transports=e.transports||[I_()],this.fields={...e.fields||{}},this.timestamp=e.timestamp!==!1}child(e,t){return new r({name:e?`${this.name}:${e}`:this.name,level:this.level,transports:this.transports,fields:{...this.fields,...t||{}},timestamp:this.timestamp})}withFields(e){return this.child("",e)}setLevel(e){return this.level=Gf(e),this}addTransport(e){return this.transports.push(e),this}isLevelEnabled(e){return Gf(e)>=this.level}trace(e,...t){this._log(qt.TRACE,e,t)}debug(e,...t){this._log(qt.DEBUG,e,t)}info(e,...t){this._log(qt.INFO,e,t)}warn(e,...t){this._log(qt.WARN,e,t)}error(e,...t){this._log(qt.ERROR,e,t)}timeStart(e,t=qt.DEBUG){let n=Date.now();return i=>{let o=Date.now()-n;return this._log(t,`${e} cost ${o}ms${i?" "+i:""}`,[]),o}}_log(e,t,n){if(e<this.level)return;let i;try{i=typeof t=="string"?t:Wb(t),n&&n.length&&(i+=" "+n.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="string"?l:Wb(l)).join(" "))}catch{i=String(t)}let o=N_(this.fields),a=`${this.timestamp?`[${T_(Date.now())}] `:""}[${Vb[e]}] [${this.name}]${o} ${i}`,c={level:e,name:this.name,message:i,fields:{...this.fields},ts:Date.now()};for(let l of this.transports)try{l.write(c,a)}catch{}}};function N_(r){let e=Object.keys(r||{});return e.length?" "+e.map(t=>`${t}=${r[t]}`).join(" "):""}function Wb(r){try{return JSON.stringify(r)}catch{return String(r)}}var qf=new js({name:"hm",level:"info"});function zf(r={}){return qf=new js({name:"hm",...r}),qf}function Hs(r){return qf.child(r,{})}import{spawn as __}from"child_process";var wo=class extends Error{code;details;constructor(e,t={}){super(e,t.cause?{cause:t.cause}:void 0),this.name=new.target.name,this.code=t.code||new.target.code||"HM_ERROR",this.details=t.details,Error.captureStackTrace&&Error.captureStackTrace(this,new.target)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}},ci=class extends wo{static code="HDC_ERROR";args;stderr;constructor(e,t={}){super(e,{...t,code:t.code||"HDC_ERROR"}),this.args=t.details?.args||[],this.stderr=t.details?.stderr||""}},hn=class extends ci{static code="HDC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"HDC_TIMEOUT"})}},Us=class extends ci{static code="HDC_COMMAND_FAILED";constructor(e,t={}){super(e,{...t,code:"HDC_COMMAND_FAILED"})}},Dt=class extends wo{static code="DEVICE_ERROR";constructor(e,t={}){super(e,{...t,code:t.code||"DEVICE_ERROR"})}},gn=class extends Dt{static code="DEVICE_NOT_FOUND";constructor(e,t={}){super(e,{...t,code:"DEVICE_NOT_FOUND"})}},yn=class extends Dt{static code="DEVICE_FILE_ERROR";constructor(e,t={}){super(e,{...t,code:"DEVICE_FILE_ERROR"})}},hr=class extends wo{static code="RPC_ERROR";endpoint;constructor(e,t={}){super(e,{...t,code:t.code||"RPC_ERROR"}),this.endpoint=t.details?.endpoint||""}},gr=class extends hr{static code="RPC_LIFECYCLE_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_LIFECYCLE_ERROR"})}},Ur=class extends gr{static code="RPC_DISPOSED";constructor(e,t={}){super(e,{...t,code:"RPC_DISPOSED"})}},$e=class extends hr{static code="RPC_TRANSPORT_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_TRANSPORT_ERROR"})}},wn=class extends hr{static code="RPC_TIMEOUT";constructor(e,t={}){super(e,{...t,code:"RPC_TIMEOUT"})}},zt=class extends hr{static code="RPC_PROTOCOL_ERROR";constructor(e,t={}){super(e,{...t,code:"RPC_PROTOCOL_ERROR"})}},Bs=class extends hr{static code="RPC_REMOTE_ERROR";remote;constructor(e,t={}){super(e,{...t,code:"RPC_REMOTE_ERROR"}),this.remote=t.details?.remote}};function Gb(r){return r instanceof $e||r instanceof wn||r instanceof zt}function Jf(r){return r instanceof Ur?!1:Gb(r)||r instanceof gr}var Ws=class{args;code;stdout;stderr;durationMs;constructor({args:e,code:t=0,stdout:n="",stderr:i="",durationMs:o=0}){this.args=e,this.code=t,this.stdout=n,this.stderr=i,this.durationMs=o}get ok(){return this.code===0}get command(){return this.args.join(" ")}assertOk(e="hdc command"){if(this.ok)return this;throw new Us(`${e} failed: ${this.stderr||this.stdout||`exit ${this.code}`}`,{details:{args:this.args,stderr:this.stderr,stdout:this.stdout,code:this.code}})}toString(){return this.command}},Vs=class{bin;host;port;execTimeoutMs;logger;dfx;constructor(e={}){this.bin=e.bin||"hdc",this.host=e.host||"127.0.0.1",this.port=e.port??8710,this.execTimeoutMs=e.execTimeoutMs??1e4,this.logger=e.logger??null,this.dfx=e.dfx??null}async exec(e,t){throw new ci("HdcExecutor.exec() must be implemented by subclass")}get serverAddress(){return`${this.host||"127.0.0.1"}:${this.port??8710}`}serverPrefixArgs(){return(!this.host||this.host==="127.0.0.1"||this.host==="localhost")&&(this.port??8710)===8710?[]:["-s",this.serverAddress]}async listTargets(e){let t=await this.exec(["list","targets"],e);return qb(t.stdout)}};function qb(r){let e=String(r||"").trim();return!e||/\[Empty\]/i.test(e)||/^Empty$/i.test(e)?[]:e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t&&!/\[Empty\]/i.test(t)&&!/^Empty$/i.test(t))}function Kf(r){let e=[];for(let t of String(r||"").split(/\r?\n/)){let n=t.trim();if(!n||/\[Empty\]/i.test(n)||/^Empty$/i.test(n))continue;let i=/tcp:(\d+)\s+(\S+)/.exec(n);if(!i)continue;let o=Number(i[1]);Number.isInteger(o)&&e.push({hostPort:o,deviceEndpoint:i[2],taskString:`tcp:${o} ${i[2]}`})}return e}function Yf(r){let e=[];for(let t of String(r||"").split(/\r?\n/)){let n=t.trim();if(!n)continue;let i=/^(\S+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(n);i&&e.push({user:i[1],pid:Number(i[2]),cmd:i[4]})}return e}var li=class extends Vs{env;onStderr;windowsHide;constructor(e={}){super(e),this.env=e.env||process.env,this.onStderr=e.onStderr??null,this.windowsHide=e.windowsHide!==!1}_childEnv(){let e={...this.env};return this.host&&this.host!=="127.0.0.1"&&(e.HDC_SERVER_IP||(e.HDC_SERVER_IP=this.host),e.HDC_SERVER_PORT||(e.HDC_SERVER_PORT=String(this.port))),e}exec(e,t={}){let n=t.timeoutMs??this.execTimeoutMs,i=Date.now(),o=this.dfx?this.dfx.timer("hdc.exec",{cmd:e[0]}):null,s=[...this.serverPrefixArgs(),...e],a=this._childEnv();return new Promise((c,l)=>{let d=this.spawnHdcChild(s,a,o,l);d&&this.attachChildHandlers(d,e,n,i,o,c,l)})}spawnHdcChild(e,t,n,i){try{return f(`Executing: ${this.bin} ${e.join(" ")}`),__(this.bin,e,{env:t,stdio:["ignore","pipe","pipe"],windowsHide:this.windowsHide})}catch(o){return n&&n({ok:0}),i(new hn(`spawn ${this.bin} failed: ${o.message}`,{cause:o})),null}}attachChildHandlers(e,t,n,i,o,s,a){let c={outChunks:[],errChunks:[],settled:!1,timedOut:!1,timer:null};c.timer=setTimeout(()=>{c.timedOut=!0;try{e.kill("SIGKILL")}catch{}},n),e.stdout?.on("data",l=>{c.outChunks.length<4096&&c.outChunks.push(l)}),e.stderr?.on("data",l=>{c.errChunks.push(l),this.onStderr&&this.onStderr(l.toString())}),e.on("close",l=>{this.finalizeResult(l,t,n,i,o,c,s,a)}),e.on("error",l=>{this.handleChildError(l,t,o,c,a)})}finalizeResult(e,t,n,i,o,s,a,c){if(s.settled)return;s.settled=!0,s.timer&&clearTimeout(s.timer);let l=Buffer.concat(s.outChunks).toString("utf8").trim(),d=Buffer.concat(s.errChunks).toString("utf8").trim(),h=Date.now()-i;if(o&&o({ok:e===0?1:0}),this.dfx&&this.dfx.counter(e===0?"hdc.exec.ok":"hdc.exec.error",1,{cmd:t[0]}),this.logger&&this.logger.debug(`hdc ${t.join(" ")} -> code=${e} (${h}ms)`),s.timedOut){c(new hn(`hdc ${t.join(" ")} timeout after ${n}ms`,{details:{args:t,stdout:l,stderr:d}}));return}a(new Ws({args:t,code:e??-1,stdout:l,stderr:d,durationMs:h}))}handleChildError(e,t,n,i,o){i.settled||(i.settled=!0,i.timer&&clearTimeout(i.timer),n&&n({ok:0}),o(new hn(`hdc ${t.join(" ")} spawn error: ${e.message}`,{cause:e})))}};var zb=Object.freeze({hdc:{bin:"hdc",host:"127.0.0.1",port:8710,execTimeoutMs:1e4,maxOutputBytes:4194304},device:{autoSelectFirst:!0,queryVersion:!0,newUiTestMinVersion:"6.0.2.2",autoPushResources:!0,resourcesDir:"",fastModeDir:""},rpc:{mode:"fast",framing:"auto",connectTimeoutMs:5e3,requestTimeoutMs:3e4,socketIdleTimeoutMs:3e4,portRange:{start:1e4,end:19999},concurrency:"auto",maxInFlight:16,strictPairing:!1,timeoutKillsConnection:!1,recovery:{enabled:!0,maxAttempts:1,delayMs:200},fast:{connectTimeoutMs:1500,probeOnReuse:!0,keepOnRelease:!0,forceRestartOnProbeFailure:!0},operate:{fastHostPort:19801,startWaitMs:500,processWaitTimeoutMs:15e3,processCheckIntervalMs:200,checkListening:!0,resources:[]}},log:{level:"info",timestamp:!0,transports:["console"],file:""},dfx:{enabled:!0,sinks:["memory"],slowThresholdMs:1e3}}),M_={HM_HDC_BIN:"hdc.bin",HM_HDC_HOST:"hdc.host",HM_HDC_PORT:"hdc.port",HM_LOG_LEVEL:"log.level",HM_RPC_MODE:"rpc.mode",HM_RPC_REQUEST_TIMEOUT:"rpc.requestTimeoutMs"};function Al(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Xf(r){if(typeof structuredClone=="function")try{return structuredClone(r)}catch{}return JSON.parse(JSON.stringify(r))}function Il(r,e){let t=Xf(r);for(let[n,i]of Object.entries(e||{}))i!==void 0&&(Al(i)&&Al(t[n])?t[n]=Il(t[n],i):t[n]=Xf(i));return t}function O_(r,e){return e.split(".").reduce((t,n)=>{if(!(t==null||typeof t!="object"))return t[n]},r)}function Jb(r,e,t){let n=e.split("."),i=n.pop(),o=r;for(let s of n)Al(o[s])||(o[s]={}),o=o[s];return o[i]=t,r}var Tl=class{_data;constructor(e={}){this._data=Il(zb,L_()),e&&Object.keys(e).length&&(this._data=Il(this._data,e))}slice(e){let t=this.get(e);return Al(t)?t:{}}get(e,t){let n=O_(this._data,e);return n===void 0?t:n}set(e,t){return Jb(this._data,e,t),this}merge(e){return this._data=Il(this._data,e),this}snapshot(){return Xf(this._data)}toJSON(){return this.snapshot()}};function L_(){let r={};for(let[e,t]of Object.entries(M_)){let n=process.env[e];if(n===void 0||n==="")continue;let i=n;if(t==="hdc.port"||t==="rpc.requestTimeoutMs"){let o=Number(n);if(Number.isNaN(o))continue;i=o}Jb(r,t,i)}return r}function Gs(r){return new Tl(r)}var Nl=class{records;constructor(){this.records=[]}write(e){this.records.push(e)}select(e){return this.records.filter(t=>typeof e=="function"?e(t.name):t.name===e||t.name.startsWith(e+"."))}sum(e){return this.select(e).reduce((t,n)=>t+(n.value||0),0)}count(e){return this.select(e).length}snapshot(){return{counters:Kb(this.records,"counter"),timers:Kb(this.records,"timer"),events:this.records.filter(e=>e.type==="event").map(e=>({name:e.name,fields:e.fields,ts:e.ts}))}}reset(){this.records.length=0}};function Kb(r,e){let t={};for(let n of r){if(n.type!==e)continue;t[n.name]||(t[n.name]={count:0,sum:0,min:1/0,max:0,avg:0});let i=e==="counter"?n.value||0:n.durationMs||0;t[n.name].count+=1,t[n.name].sum+=i,t[n.name].min=Math.min(t[n.name].min,i),t[n.name].max=Math.max(t[n.name].max,i)}for(let n of Object.keys(t))t[n].avg=t[n].sum/t[n].count,t[n].min===1/0&&(t[n].min=0);return t}var _l=class r{enabled;tags;sinks;slowThresholdMs;logger;constructor(e={}){this.enabled=e.enabled!==!1,this.tags={...e.tags||{}},this.sinks=e.sinks||[new Nl],this.slowThresholdMs=e.slowThresholdMs??1e3,this.logger=e.logger??null}child(e){return new r({enabled:this.enabled,sinks:this.sinks,tags:{...this.tags,...e||{}},slowThresholdMs:this.slowThresholdMs,logger:this.logger})}counter(e,t=1,n={}){this._emit({type:"counter",name:e,value:t,fields:n})}event(e,t={}){this._emit({type:"event",name:e,fields:t})}timer(e,t={}){let n=Date.now();return(i={})=>{let o=Date.now()-n;return this._emit({type:"timer",name:e,fields:{...t,...i},durationMs:o}),this.slowThresholdMs>0&&o>this.slowThresholdMs&&this._emit({type:"event",name:"slow",fields:{...t,...i,metric:e,durationMs:o}}),o}}async span(e,t,n={}){let i=this.timer(e,n);try{let o=await t();return i({ok:1}),this.counter(`${e}.ok`,1,n),o}catch(o){throw i({ok:0}),this.counter(`${e}.error`,1,{...n,code:o?.code||o?.name}),o}}_emit(e){if(!this.enabled)return;let t={type:e.type,name:e.name,value:e.value,durationMs:e.durationMs,fields:{...this.tags,...e.fields||{}},ts:Date.now()};for(let n of this.sinks)try{n.write(t)}catch{}}snapshot(){let e=this.sinks.find(t=>t instanceof Nl);return e?e.snapshot():null}reset(){for(let e of this.sinks)typeof e.reset=="function"&&e.reset()}};function qs(r={}){return new _l(r)}function vo(r){return new Promise(e=>setTimeout(e,r))}async function Ml(r,{timeoutMs:e,intervalMs:t=200,firstDelayMs:n=0,description:i="condition"}){let o=Date.now()+e;n>0&&await vo(n);let s;for(;;){if(s=await r(),s)return s;if(Date.now()>=o){let a=new Error(`wait for ${i} timeout after ${e}ms`);throw a.name="TimeoutError",a}await vo(t)}}var bo=class{_tail;locked;constructor(){this._tail=Promise.resolve(),this.locked=!1}async runExclusive(e){let t,n=new Promise(o=>{t=o}),i=this._tail;this._tail=i.then(()=>n),await i.catch(()=>{}),this.locked=!0;try{return await e()}finally{this.locked=!1,t()}}},So=class{limit;used;_waiters;_idleWaiters;constructor(e=1){this.limit=Math.max(1,e|0),this.used=0,this._waiters=[],this._idleWaiters=[]}get available(){return Math.max(0,this.limit-this.used)}get waiting(){return this._waiters.length}get isIdle(){return this.used===0}acquire(){return new Promise((e,t)=>{this._waiters.push({resolve:e,reject:t}),this._dispatch()})}resize(e){let t=Math.max(1,e|0);t!==this.limit&&(this.limit=t,this._dispatch())}abortAll(e){let t=this._waiters.splice(0);for(let n of t)try{n.reject(e)}catch{}}drain(){return this.used===0?Promise.resolve():new Promise(e=>{this._idleWaiters.push({resolve:e})})}_dispatch(){for(;this._waiters.length>0&&this.used<this.limit;){let e=this._waiters.shift();this.used+=1;let t=!1;e.resolve(()=>{t||(t=!0,this.used-=1,this._dispatch(),this.used===0&&this._idleWaiters.length&&this._resolveIdleWaiters())})}}_resolveIdleWaiters(){let e=this._idleWaiters.splice(0);for(let t of e)t.resolve()}},di=class{_map;constructor(){this._map=new Map}run(e,t){let n=this._map.get(e);if(n)return n;let o=(async()=>t())().finally(()=>{this._map.get(e)===o&&this._map.delete(e)});return this._map.set(e,o),o}pending(e){return this._map.get(e)||null}has(e){return this._map.has(e)}keys(){return[...this._map.keys()]}};var F_=64*1024*1024,Zf={name:"length-prefixed",frameDelimited:!0,encode(r){let e=Buffer.from(typeof r=="string"?r:JSON.stringify(r),"utf8"),t=Buffer.alloc(4);return t.writeUInt32BE(e.length,0),Buffer.concat([t,e])},decode(r){if(r.length<4)return null;let e=r.readUInt32BE(0);if(e>F_||e<0)throw new zt(`invalid frame length ${e}`);if(r.length<4+e)return null;let t=r.subarray(4,4+e).toString("utf8"),n;try{n=JSON.parse(t)}catch{throw new zt(`response is not valid JSON: ${t.slice(0,200)}`)}return{value:n,rest:r.subarray(4+e)}}},Ol={name:"raw",frameDelimited:!1,encode(r){return Buffer.from(typeof r=="string"?r:JSON.stringify(r),"utf8")},decode(r){let e=r.toString("utf8").trim();if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}return{value:t,rest:Buffer.alloc(0)}}};function $_(r){if(!r||r.length===0)return null;let e=r[0];return e===123||e===91?"raw":"length-prefixed"}function Qf(r="auto"){return r==="raw"?Ol:r==="length-prefixed"?Zf:j_()}function j_(){let r=null;return{name:"auto",frameDelimited:!1,get detected(){return r},encode(e){return Ol.encode(e)},decode(e){return r||(r=$_(e)),r==="length-prefixed"?Zf.decode(e):Ol.decode(e)}}}var em=0;function yr(r="hm"){em=(em+1)%1e6;let e=new Date().toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),t=Math.random().toString(36).slice(2,8);return`${r}-${e}-${em.toString(36)}-${t}`}import tm from"net";function rm(r,e,t=500){return new Promise(n=>{let i=new tm.Socket,o=!1,s=a=>{o||(o=!0,i.destroy(),n(a))};i.setTimeout(t),i.once("connect",()=>s(!0)),i.once("timeout",()=>s(!1)),i.once("error",()=>s(!1));try{i.connect(e,r)}catch{s(!1)}})}async function nm({host:r="127.0.0.1",start:e=1e4,end:t=19999,exclude:n}={}){let i=new Set(n||[]);for(let o=e;o<=t;o++){if(i.has(o))continue;if(await U_(r,o))return o}throw new Error(`no free port in range ${e}-${t}`)}var H_=nm;function U_(r,e){return new Promise(t=>{let n=tm.createServer();n.once("error",()=>t(!1)),n.once("listening",()=>{n.close(()=>t(!0))}),n.listen(e,r)})}async function B_({host:r="127.0.0.1",start:e=1e4,end:t=19999,exclude:n,timeoutMs:i=500,stepDelayMs:o=0}={}){if(!r)throw new Error("getFreeRemotePort requires host");let s=new Set(n||[]);for(let a=e;a<=t;a++){if(s.has(a))continue;if(!await rm(r,a,i))return a;o>0&&await new Promise(l=>setTimeout(l,o))}throw new Error(`no free port on remote ${r} in range ${e}-${t}`)}async function Yb({hdcHost:r="127.0.0.1",start:e,end:t,exclude:n}={}){return!r||r==="127.0.0.1"||r==="localhost"?{port:await H_({host:r||"127.0.0.1",start:e,end:t,exclude:n}),scope:"local"}:{port:await B_({host:r,start:e,end:t,exclude:n,stepDelayMs:50}),scope:"remote"}}function Ll({host:r,port:e,timeoutMs:t=5e3,keepAliveMs:n}){return new Promise((i,o)=>{let s=new tm.Socket,a=!1,c=l=>{a||(a=!0,s.destroy(),o(l))};s.setTimeout(t),s.once("timeout",()=>{let l=new Error(`connect to ${r}:${e} timeout after ${t}ms`);l.code="ETIMEDOUT",c(l)}),s.once("error",c),s.connect(e,r,()=>{a||(a=!0,s.removeListener("error",c),s.removeListener("timeout",c),n&&n>0&&s.setKeepAlive(!0,n),s.setNoDelay(!0),i(s))})})}function Jt(r,e){let t=Xb(r),n=Xb(e),i=Math.max(t.length,n.length);for(let o=0;o<i;o++){let s=t[o]??0,a=n[o]??0;if(s>a)return 1;if(s<a)return-1}return 0}function Xb(r){return String(r||"").trim().split(/[.\-+_]/).filter(Boolean).map(e=>{let t=parseInt(e,10);return Number.isNaN(t)?0:t})}function Eo(r){let e=/(\d+(?:\.\d+)+)/.exec(String(r||""));return e?e[1]:null}var W_=/^[A-Za-z0-9_@%+=:,./-]+$/,V_=/'/g,G_="'\\''";function ui(r){let e=r==null?"":String(r);return e===""?"''":W_.test(e)?e:`'${e.replace(V_,G_)}'`}function xt(r){if(!Array.isArray(r))throw new TypeError("shellJoin expects an array of arguments");return r.filter(e=>e!=null&&e!=="").map(e=>ui(e)).join(" ")}function im(r){let e=String(r??"");if(/[\r\n\0]/.test(e))throw new wr("shell command must not contain newline or NUL characters");return e}function vr(r){let e=String(r??"").trim();if(!e)throw new wr("remote path is empty");if(!e.startsWith("/"))throw new wr(`remote path must be absolute: ${JSON.stringify(r)}`);if(/[\r\n\0]/.test(e))throw new wr("remote path must not contain newline or NUL characters");return e}function om(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new wr(`invalid pid: ${JSON.stringify(r)}`);return e}function Fl(r){let e=String(r??"").trim();if(!/^(localabstract|localfilesystem|tcp|jdwp):[A-Za-z0-9_.-]+$/.test(e))throw new wr(`invalid device endpoint: ${JSON.stringify(r)}`);return e}function $l(r){let e=Number(r);if(!Number.isInteger(e)||e<1||e>65535)throw new wr(`invalid host port: ${JSON.stringify(r)}`);return e}var wr=class extends Error{constructor(e){super(e),this.name="ShellSafetyError"}};import{stat as RM}from"fs/promises";var Y_="6.0.2.2";async function Zb(r,e={}){let t=e.minVersion||Y_,n=(await r.shellArgs(["file","/system/bin/uitest"])).trim(),i=/x86[ _-]64/.test(n)?"x86_64":"arm64",o=(await r.shellArgs(["/system/bin/uitest","--version"])).trim(),s=X_(o)||o,a=Jt(s,t)>=0;return{version:s,arch:i,isNewUiTest:a,endpointStyle:a&&i!=="x86_64"?"unix":"tcp",fileOutput:n}}function X_(r){let e=/(\d+(?:\.\d+)+)/.exec(String(r||""));return e?e[1]:null}import{fileURLToPath as nM}from"url";import{dirname as iM,join as tS}from"path";import{readdirSync as Z_}from"fs";import{join as Q_,basename as dZ}from"path";var eM=/^uitest_agent_v(\d+\.\d+\.\d+)(\.x86_64)?\.so$/,tM="/data/local/tmp/agent.so",sm="UITEST_AGENT_LIBRARY";function rM(r){let e;try{e=Z_(r)}catch{return[]}return e.filter(t=>t.endsWith(".so"))}function Qb({dir:r,arch:e,isNewUiTest:t}){let n=e==="x86_64",i=[];for(let s of rM(r)){let a=eM.exec(s);if(!a)continue;let c=!!a[2];if(n!==c)continue;if(n){i.push({fileName:s,version:a[1],x86_64:c});continue}let l=Jt(a[1],"1.2.2")>=0;t===l&&i.push({fileName:s,version:a[1],x86_64:c})}if(!i.length)return null;i.sort((s,a)=>Jt(a.version,s.version));let o=i[0];return{fileName:o.fileName,localPath:Q_(r,o.fileName),version:o.version,x86_64:o.x86_64,remotePath:tM,versionProbe:sm}}function eS(r){let e=String(r||""),t=e.indexOf("#"),n=t>=0?e.slice(t+1):e;return Eo(n)}var oM=tS(iM(nM(import.meta.url)),"..",".."),sM=tS(oM,"resources"),jl=class{device;config;logger;dfx;_agentState;constructor({device:e,config:t,logger:n,dfx:i}){this.device=e,this.config=t,this.logger=n?n.child("ResourceMgr"):null,this.dfx=i??null,this._agentState=null}get resourcesDir(){return this.config.get("device.resourcesDir")||sM}async getInfo(e=!1){return this.device.getUitestInfo(e)}async ensureAgent(e={}){if(this._agentState&&!e.force)return this._agentState;let t=await this.getInfo(),n=Qb({dir:this.resourcesDir,arch:t.arch,isNewUiTest:t.isNewUiTest});if(!n)throw new Dt(`no uitest agent found for arch=${t.arch} isNewUiTest=${t.isNewUiTest} in ${this.resourcesDir}`,{details:{resourcesDir:this.resourcesDir}});let i=await this.device.fileExists(n.remotePath),o=null,s=!i;return i&&(o=await this._probeAgentVersion(n.remotePath),(!o||Jt(n.version,o)>0)&&(s=!0)),s?(this.logger&&this.logger.info(`update agent.so: local=v${n.version} remote=${o||"none"} (arch=${n.x86_64?"x86_64":"arm64"})`),await this.stopUitestDaemons(),await this.device.rm(n.remotePath),await this._push(n.localPath,n.remotePath,"agent.so"),this.dfx&&this.dfx.counter("resource.agent.update",1,{arch:t.arch})):this.logger&&this.logger.debug(`agent.so up-to-date: v${o}`),this._agentState={candidate:n,updated:s,remoteVersion:o},this._agentState}async repushAgent(){let e=this._agentState?.candidate;e||(e=(await this.ensureAgent()).candidate),this.logger&&this.logger.info(`repush agent.so unconditionally (suspect corruption): ${e.fileName}`),await this.stopUitestDaemons(),await this.device.rm(e.remotePath),await this._push(e.localPath,e.remotePath,"agent.so"),this.dfx&&this.dfx.counter("resource.agent.repush",1,{file:e.fileName}),this._agentState={candidate:e,updated:!0,remoteVersion:e.version}}async _probeAgentVersion(e){try{let t=await this.device.shell(`cat ${ui(e)} | ${xt(["grep","-a",sm])}`);return eS(t)}catch{return null}}async _push(e,t,n){let i=this.dfx?this.dfx.timer("resource.push",{file:n}):null;await this.device.fileSend(e,t),i&&i({ok:1})}async stopUitestDaemons(){let t=(await this.device.findProcesses()).filter(n=>n.cmd.includes("uitest")&&n.cmd.includes("start-daemon")).map(n=>n.pid);for(let n of t)try{await this.device.killProcess(n)}catch(i){this.logger&&this.logger.debug(`kill daemon pid=${n} failed: ${i.message}`)}return t.length&&this.logger&&this.logger.info(`stopped uitest daemons before agent update: [${t.join(", ")}]`),t.length}};import{join as am}from"path";import{mkdir as aM,readFile as rS,writeFile as nS,unlink as cM,readdir as lM}from"fs/promises";function dM(r){return String(r||"unknown").replace(/[^A-Za-z0-9._-]/g,"_")}var uM=am(j(),"fast-mode"),Hl=class{config;logger;_explicitDir;constructor({config:e,dir:t,logger:n}={}){this.config=e,this.logger=n?n.child("FastModeStore"):null,this._explicitDir=t}get dir(){if(this._explicitDir)return this._explicitDir;if(this.config){let e=this.config.get("device.fastModeDir");if(e)return e}return uM}pathFor(e){return am(this.dir,`${dM(e)}.json`)}async _ensureDir(){await aM(this.dir,{recursive:!0,mode:448})}async save(e,t){await this._ensureDir();let n=await this.read(e)||{serial:e,createdAt:new Date(0).toISOString(),updatedAt:new Date(0).toISOString(),endpoints:{}};n.serial=e,n.updatedAt=new Date().toISOString(),(!n.createdAt||n.createdAt===new Date(0).toISOString())&&(n.createdAt=n.updatedAt),n.hdcServer=t.hdcServer||n.hdcServer||"",n.endpoints[t.endpoint]={hostPort:t.hostPort,deviceEndpoint:t.deviceEndpoint,style:t.style,agentVersion:t.agentVersion||null,uitestVersion:t.uitestVersion||null,savedAt:n.updatedAt};let i=this.pathFor(e);return await nS(i,JSON.stringify(n,null,2),{mode:384}),this.logger&&this.logger.debug(`saved fast-mode state for ${e}: ${t.endpoint} -> tcp:${t.hostPort}`),n}async read(e){try{let t=await rS(this.pathFor(e),"utf8"),n=JSON.parse(t);return!n||typeof n!="object"||!n.endpoints?null:n}catch{return null}}async get(e,t){let n=await this.read(e);return n&&n.endpoints&&n.endpoints[t]||null}async forget(e){try{return await cM(this.pathFor(e)),this.logger&&this.logger.debug(`removed fast-mode state for ${e}`),!0}catch{return!1}}async forgetEndpoint(e,t){let n=await this.read(e);return!n||!n.endpoints[t]?!1:(n.endpoints=Object.fromEntries(Object.entries(n.endpoints).filter(([i])=>i!==t)),Object.keys(n.endpoints).length?(await this._ensureDir(),await nS(this.pathFor(e),JSON.stringify(n,null,2),{mode:384}),!0):this.forget(e))}async list(){let e;try{e=await lM(this.dir)}catch{return[]}let t=[];for(let n of e)if(n.endsWith(".json"))try{t.push(JSON.parse(await rS(am(this.dir,n),"utf8")))}catch{}return t}};var br={AUTO:"auto",PIPELINED:"pipelined",SERIAL:"serial"},zs=class{host;port;name;codec;frameDelimited;concurrency;maxInFlight;strictPairing;timeoutKillsConnection;connectTimeoutMs;requestTimeoutMs;socketIdleTimeoutMs;logger;dfx;socket;buffer;pending;_sem;generation;_closed;_failure;onClose;_serverEchoesRequestId;_seq;stats;constructor(e){this.host=e.host||"127.0.0.1",this.port=e.port,this.name=e.name||"rpc",this.codec=Qf(e.framing||"auto"),this.frameDelimited=this.codec.frameDelimited===!0,this.concurrency=e.concurrency||br.AUTO,this.maxInFlight=Math.max(1,e.maxInFlight??16),this.strictPairing=e.strictPairing===!0,this.timeoutKillsConnection=e.timeoutKillsConnection===!0,this.connectTimeoutMs=e.connectTimeoutMs??5e3,this.requestTimeoutMs=e.requestTimeoutMs??3e4,this.socketIdleTimeoutMs=e.socketIdleTimeoutMs??3e4,this.logger=e.logger??null,this.dfx=e.dfx??null,this.socket=null,this.buffer=Buffer.alloc(0),this.pending=new Map,this._sem=new So(this._initialLimit()),this.generation=0,this._closed=!0,this._failure=null,this.onClose=null,this._serverEchoesRequestId=null,this._seq=0,this.stats={connectCount:0,requestCount:0,bytesIn:0,bytesOut:0,maxInFlight:0,timeouts:0,unmatchedResponses:0,queued:0}}get isConnected(){return!!this.socket&&!this.socket.destroyed&&!this._closed}get inFlight(){return this.pending.size}get concurrencyMode(){return this.concurrency===br.SERIAL?"serial":this.frameDelimited?this.concurrency===br.PIPELINED?"pipelined":this._serverEchoesRequestId===!0?"pipelined(auto)":"serial(auto)":"serial(raw)"}async connect(e={}){await this.destroy();let t=e.port??this.port,n=e.timeoutMs??this.connectTimeoutMs,i=this.dfx?this.dfx.timer("rpc.connect",{endpoint:this.name}):null;try{this.socket=await Ll({host:this.host,port:t,timeoutMs:n})}catch(a){let c=a;throw i&&i({ok:0}),this.dfx&&this.dfx.counter("rpc.connect.error",1,{endpoint:this.name}),new $e(`connect ${this.host}:${t} failed: ${c.message}`,{cause:c,details:{endpoint:this.name,host:this.host,port:t}})}let o=++this.generation;this._postConnectSetup(),i&&i({ok:1}),this.dfx&&this.dfx.counter("rpc.connect.ok",1,{endpoint:this.name});let s=this.socket;s.setTimeout(this.socketIdleTimeoutMs),this._attachSocketHandlers(s,o),this.logger&&this.logger.info(`connected to ${this.host}:${t} (${this.name}, gen=${o})`)}_postConnectSetup(){this._closed=!1,this._failure=null,this.buffer=Buffer.alloc(0),this.pending.clear(),this._serverEchoesRequestId=null,this._sem.resize(this._computeLimit()),this.stats.connectCount+=1}_attachSocketHandlers(e,t){e.on("data",n=>{t===this.generation&&this._onData(n)}),e.on("error",n=>{t===this.generation&&this._fail(new $e(`socket error: ${n.message}`,{cause:n}))}),e.on("timeout",()=>{t===this.generation&&this._fail(new wn(`socket idle timeout after ${this.socketIdleTimeoutMs}ms`))}),e.on("close",()=>{t===this.generation&&this._fail(new $e("connection closed by peer"))})}_onData(e){this.stats.bytesIn+=e.length,this.buffer=Buffer.concat([this.buffer,e]);try{for(;;){let t=this.codec.decode(this.buffer);if(!t)break;this.buffer=t.rest,this._dispatch(t.value)}}catch(t){let n=t;this._fail(n instanceof zt?n:new zt(`decode failed: ${n.message}`))}}_dispatch(e){let t=e,n=t&&typeof t=="object"?t.request_id:void 0,i=null;if(n!=null&&this.pending.has(n)?i=n:n==null&&(this.pending.size===1&&(i=[...this.pending.keys()][0]),this._noteNoRequestId()),i==null){this.stats.unmatchedResponses+=1,this.dfx&&this.dfx.counter("rpc.response.unmatched",1,{endpoint:this.name,hasId:String(n!=null)}),this.logger&&this.logger.warn(`drop unmatched response (request_id=${n}, pending=${this.pending.size})`),this.strictPairing&&this._fail(new zt(`unmatched response, request_id=${n}, pending=${this.pending.size}`));return}let o=this.pending.get(i);this.pending.delete(i),o.timer&&clearTimeout(o.timer),n!=null&&this._serverEchoesRequestId!==!0&&(this._serverEchoesRequestId=!0,this._applyLimit()),o.resolve(e)}_noteNoRequestId(){this._serverEchoesRequestId!==!1&&(this._serverEchoesRequestId=!1,this._applyLimit(),this.logger&&this.logger.warn("server does not echo request_id, degrade to serial mode for this connection"),this.dfx&&this.dfx.counter("rpc.concurrency.degrade",1,{endpoint:this.name}))}_computeLimit(){return this.concurrency===br.SERIAL||!this.frameDelimited?1:this.concurrency===br.PIPELINED?this.maxInFlight:this._serverEchoesRequestId===!0?this.maxInFlight:1}_initialLimit(){return this.concurrency===br.SERIAL||!this.frameDelimited?1:this.concurrency===br.PIPELINED?this.maxInFlight:1}_applyLimit(){this._sem.resize(this._computeLimit())}_nextRequestId(e){if(e!=null&&!this.pending.has(String(e)))return String(e);let t=yr();for(;this.pending.has(t);)t=yr();return t}async send(e,t={}){this._assertUsable();let n=await this._acquireSendSlot();try{this._assertUsable();let i=this.generation,o=t.timeoutMs??this.requestTimeoutMs,s=this._nextRequestId(e&&e.request_id),a={...e,request_id:s},c=++this._seq,l=this.dfx?this.dfx.timer("rpc.request",{endpoint:this.name}):null,d=await this._awaitResponse(s,a,i,c,o,l);return l&&l({ok:1}),this.dfx&&this.dfx.counter("rpc.request.ok",1,{endpoint:this.name}),d}finally{n&&n()}}async _acquireSendSlot(){let e=null;try{(this._sem.available<=0||this._sem.waiting>0)&&(this.stats.queued+=1),e=await this._sem.acquire()}catch(t){let n=t;throw new $e(`request rejected while queued: ${n.message}`,{cause:n,details:{endpoint:this.name}})}return e}_awaitResponse(e,t,n,i,o,s){return new Promise((a,c)=>{let l={resolve:a,reject:c,timer:null,t0:Date.now(),gen:n,seq:i},d=this._createSettleFn(e,l);l.timer=setTimeout(()=>this._onRequestTimeout(e,o,s,d,c),o),this._registerPending(e,l),this._writeFrame(t,i,d,c)})}_createSettleFn(e,t){return(n,i)=>{this.pending.get(e)===t&&(this.pending.delete(e),t.timer&&clearTimeout(t.timer),n(i))}}_onRequestTimeout(e,t,n,i,o){this.stats.timeouts+=1;let s=new wn(`rpc request ${e} timeout after ${t}ms`,{details:{endpoint:this.name,requestId:e}});n&&n({ok:0,reason:"timeout"}),this.dfx&&this.dfx.counter("rpc.request.error",1,{endpoint:this.name,reason:"timeout"}),i(o,s),this.timeoutKillsConnection&&this._fail(s)}_registerPending(e,t){this.pending.set(e,t),this.stats.requestCount+=1,this.stats.maxInFlight=Math.max(this.stats.maxInFlight,this.pending.size)}_writeFrame(e,t,n,i){let o=!1;try{let s=this.codec.encode(e);this.stats.bytesOut+=s.length,this.logger&&this.logger.debug(`-> ${this.name} #${t} ${JSON.stringify(e).slice(0,300)}`);let a=this.socket;if(!a)throw new $e("socket is null");o=a.write(s,c=>{c&&n(i,new $e(`write failed: ${c.message}`,{cause:c}))})}catch(s){let a=s;n(i,new $e(`write failed: ${a.message}`,{cause:a}));return}!o&&this.logger&&this.logger.debug(`socket backpressure on #${t}`)}_assertUsable(){if(!this.isConnected)throw new $e(this._failure?`connection broken: ${this._failure.message}`:"transport is not connected",{cause:this._failure||void 0,details:{endpoint:this.name}})}_fail(e){if(!(this._closed&&this.pending.size===0&&this._sem.waiting===0)&&(this._failure=e,this._rejectAll(e),this._closeSocket(),this.onClose))try{this.onClose(e)}catch{}}_rejectAll(e){let t=[...this.pending.values()];this.pending.clear();for(let n of t){n.timer&&clearTimeout(n.timer);try{n.reject(e)}catch{}}this._sem.abortAll(e)}_closeSocket(){this._closed=!0,this.generation+=1;let e=this.socket;if(this.socket=null,e){e.removeAllListeners();try{e.destroy()}catch{}}}async close(e="closed by client"){let t=new $e(`transport closed: ${e}`);this._failure=null,this._rejectAll(t),this._closeSocket(),this.logger&&this.logger.debug(`transport closed: ${e}`)}async destroy(){await this.close("destroy")}getSnapshot(){return{name:this.name,host:this.host,port:this.port,connected:this.isConnected,generation:this.generation,concurrency:this.concurrency,concurrencyMode:this.concurrencyMode,maxInFlight:this._sem.limit,inFlight:this.pending.size,queued:this._sem.waiting,serverEchoesRequestId:this._serverEchoesRequestId,stats:{...this.stats}}}};var Ul="com.ohos.devicetest.hypiumApiHelper",cm="callHypiumApi";function Bl({module:r,method:e,params:t={},requestId:n}){return{module:r,method:e,params:t,request_id:n||yr()}}function Wl(r){if(!r||typeof r!="object")return!1;let e=r.exception;return e!=null&&e!==""}function Vl(r){return r?r.result:void 0}var Re={IDLE:"IDLE",BOOTING:"BOOTING",RESOURCES_READY:"RESOURCES_READY",PROCESS_RUNNING:"PROCESS_RUNNING",FORWARDED:"FORWARDED",CONNECTING:"CONNECTING",CONNECTED:"CONNECTED",READY:"READY",WARM:"WARM",RESETTING:"RESETTING",ERROR:"ERROR",DISPOSED:"DISPOSED"},Js=class{device;endpoint;config;name;displayName;logger;dfx;mode;state;transport;_mutex;_epoch;_readyFlight;_resetFlight;_disposed;ctx;constructor({device:e,endpoint:t,config:n,logger:i,dfx:o,mode:s}){this.device=e,this.endpoint=t,this.config=n,this.name=t.name,this.displayName=t.displayName||t.name,this.logger=i?i.child(`Rpc:${this.displayName}`):null,this.dfx=o?o.child({endpoint:this.name}):null,this.mode=s||n.get("rpc.mode","stable"),this.state=Re.IDLE,this.transport=null,this._mutex=new bo,this._epoch=0,this._readyFlight=new di,this._resetFlight=new di,this._disposed=!1,this.ctx=this._freshContext()}_bumpEpoch(){return this._epoch+=1,this._epoch}_freshContext(){return{hostPort:null,deviceEndpoint:null,pids:[],owned:!1,resourcesPushed:!1,style:null,startedAt:0,startCount:0,resetCount:0}}get endpointConfig(){return this.config.get(`rpc.${this.name}`,{})}get resources(){return this.endpointConfig.resources||[]}get isReady(){return this.state===Re.READY&&!!this.transport&&this.transport.isConnected}async ensureReady(){if(this._disposed)throw new Ur(`${this.name} rpc is disposed`,{details:{endpoint:this.name}});if(this.isReady)return this.ctx;let e=this._resetFlight.pending("reset");if(e){if(await e.catch(()=>{}),this._disposed)throw new Ur(`${this.name} rpc is disposed`,{details:{endpoint:this.name}});if(this.isReady)return this.ctx}return this._readyFlight.run("ready",()=>this._ensureReadyOnce())}async _ensureReadyOnce(){if(this._disposed)throw new Ur(`${this.name} rpc is disposed`,{details:{endpoint:this.name}});return this.isReady?this.ctx:this.mode==="fast"&&await this._tryFastConnect()?this.ctx:(await this._stableFlow(),this.ctx)}async _stableFlow(){let e=this.dfx?this.dfx.timer("rpc.lifecycle.prepare",{mode:"stable"}):null;try{let t=await this.device.getEndpointStyle(),n=this.endpoint.buildDeviceEndpoint(t);this.ctx.style=t,this.ctx.deviceEndpoint=n,await this._ensureResources(),this.state=Re.RESOURCES_READY,await this._ensureProcess(t),this.state=Re.PROCESS_RUNNING;let i=await this._selectStableHostPort(t);return await this._tryForward(i,n)||(i=await this.device.getFreeHostPort({exclude:[i]}),await this._ensureForward(i,n)),this.ctx.hostPort=i,this.state=Re.FORWARDED,await this._connectAndProbe(i,{probe:!0}),this.state=Re.READY,await this._onStableReady(i,n,t,e),this.ctx}catch(t){return this._onStableFlowError(t,e)}}async _onStableReady(e,t,n,i){this.mode==="fast"&&await this._persistFastState({hostPort:e,deviceEndpoint:t,style:n}),i&&i({ok:1}),this.dfx&&this.dfx.counter("rpc.lifecycle.ready",1,{mode:this.mode}),this.logger&&this.logger.info(`ready: tcp:${e} -> ${t} (mode=${this.mode}, owned=${this.ctx.owned})`)}_onStableFlowError(e,t){this.state=Re.ERROR,t&&t({ok:0}),this.dfx&&this.dfx.counter("rpc.lifecycle.error",1,{code:e?.code||e?.name});let n=e instanceof hr?e:new gr(`${this.name} rpc prepare failed: ${e.message}`,{cause:e,details:{endpoint:this.name}});throw this.logger&&this.logger.error(`prepare failed: ${n.message}`),n}async _tryFastConnect(){let e=await this._readFastStateUnchecked(),t=e?.style||await this.device.getEndpointStyle(),n=this.endpoint.buildDeviceEndpoint(t),i=this.config.get("rpc.fast",{}),o=i.connectTimeoutMs??1500,s=i.probeOnReuse!==!1,a=await this._fastPortCandidates(t);for(let c of a)try{return await this._connectAndProbe(c,{probe:s,timeoutMs:o}),await this._onFastConnectSuccess(c,n,t)}catch(l){await this._onFastConnectMiss(l,c)}return await this._cleanupStaleFports(a,e,n),await this._clearFastState(),i.forceRestartOnProbeFailure!==!1&&await this._killEndpointProcesses(),!1}async _onFastConnectSuccess(e,t,n){return this.ctx.hostPort=e,this.ctx.deviceEndpoint=t,this.ctx.style=n,this.ctx.owned=!1,this.state=Re.READY,await this._persistFastState({hostPort:e,deviceEndpoint:t,style:n}),this.dfx&&this.dfx.counter("rpc.fast.hit",1,{hostPort:e}),this.logger&&this.logger.info(`fast mode hit: reused tcp:${e}`),!0}async _onFastConnectMiss(e,t){this.dfx&&this.dfx.counter("rpc.fast.miss",1,{reason:e?.code||e.name,hostPort:t}),this.logger&&this.logger.info(`fast mode miss on tcp:${t} (${e.message}), try next/fallback`),await this._safeCloseTransport("fast miss")}async _cleanupStaleFports(e,t,n){let i=new Set(e);t&&Number.isInteger(t.hostPort)&&i.add(t.hostPort);for(let o of i)await this._removeStaleFport(o,t,n)}async _removeStaleFport(e,t,n){try{let i=t?.deviceEndpoint||n,o=await this.device.fportRemove(e,i);this._logFportRemoval(e,i,o)}catch(i){this.logger&&this.logger.debug(`fast mode fallback: remove stale fport tcp:${e} failed: ${i.message}`)}}_logFportRemoval(e,t,n){this.logger&&(n?this.logger.info(`fast mode fallback: removed stale fport tcp:${e} -> ${t}`):this.logger.debug(`fast mode fallback: fport rm tcp:${e} -> ${t} returned false (may not exist or different endpoint)`))}async _fastPortCandidates(e){let t=[],n=await this._readFastState(e);n&&Number.isInteger(n.hostPort)&&t.push(n.hostPort);let i=this.endpointConfig.fastHostPort;return Number.isInteger(i)&&t.push(i),[...new Set(t)]}async _readFastStateUnchecked(){try{let e=this.device.fastStore;if(!e)return null;let t=await e.get(this.device.serial,this.name);return t||null}catch{return null}}async _readFastState(e){try{let t=this.device.fastStore;if(!t)return null;let n=await t.get(this.device.serial,this.name);if(!n)return null;let i=n;return i.style&&i.style!==e?null:i}catch{return null}}async _persistFastState({hostPort:e,deviceEndpoint:t,style:n}){try{let i=this.device.fastStore;if(!i)return;let o=this.device._uitestInfo||null,s=this.ctx.agentVersion||null;if(!s){let a=await i.get(this.device.serial,this.name).catch(()=>null);a&&a.agentVersion&&(s=a.agentVersion)}await i.save(this.device.serial,{endpoint:this.name,hostPort:e,deviceEndpoint:t,style:n,agentVersion:s,uitestVersion:o?o.version:null,hdcServer:this.device.hdcServer})}catch(i){this.logger&&this.logger.debug(`persist fast state failed: ${i.message}`)}}async _clearFastState(){try{let e=this.device.fastStore;e&&await e.forgetEndpoint(this.device.serial,this.name)}catch{}}async _ensureResources(){await this._ensureManagedResources();let e=this.resources;for(let t of e){if(!await this.device.fileExists(t.remotePath)){await this._pushResource(t,"missing");continue}if(!t.version||!t.versionProbe)continue;let i=await this._probeRemoteVersion(t);(!i||Jt(t.version,i)>0)&&(await this._killEndpointProcesses(),await this.device.rm(t.remotePath),await this._pushResource(t,"version"))}this.ctx.resourcesPushed=!0}async _ensureManagedResources(){}async _pushResource(e,t){let n=this.dfx?this.dfx.timer("rpc.lifecycle.push",{reason:t}):null;await this.device.fileSend(e.localPath,e.remotePath),n&&n({ok:1}),this.dfx&&this.dfx.counter("rpc.lifecycle.push",1,{reason:t}),this.logger&&this.logger.info(`push resource ${e.name||e.remotePath} (${t})`)}async _probeRemoteVersion(e){try{let t=await this.device.shell(`cat ${ui(e.remotePath)} | ${xt(["grep","-a",e.versionProbe])}`);if(!t)return null;let n=t.split("#"),i=n.length>1?n[n.length-1]:t;return Eo(i)}catch{return null}}async _detectProcesses(e){let n=(await this.device.findProcesses()).filter(i=>this.endpoint.matchProcess(i));return n.length?this.endpointConfig.checkListening&&!await this.endpoint.isListening(this.device,e)?[]:n:[]}async _ensureProcess(e){let t=await this._detectProcesses(e);if(t.length){this.ctx.pids=t.map(i=>i.pid),this.ctx.owned=!1;return}await this._killStaleProcesses();let n;try{n=await this._launchAndWaitReady(e)}catch(i){let o=i;this.logger&&this.logger.warn(`${this.name} launch failed, try re-push managed resources: ${o.message}`);try{await this._onLaunchFailure()}catch(s){this.logger&&this.logger.warn(`${this.name} onLaunchFailure hook error: ${s.message}`)}await this._killStaleProcesses(),n=await this._launchAndWaitReady(e)}this.ctx.pids=n.map(i=>i.pid),this.ctx.owned=!0,this.ctx.startedAt=Date.now()}async _killStaleProcesses(){let e=(await this.device.findProcesses()).filter(t=>this.endpoint.matchProcess(t));for(let t of e)await this.device.killProcess(t.pid)}async _onLaunchFailure(){}async _launchAndWaitReady(e){let t=this.endpoint.buildStartCommand({style:e});this.logger&&this.logger.info(`start device process: ${t}`),await this.device.shell(t),this.ctx.startCount+=1,this.dfx&&this.dfx.counter("rpc.lifecycle.start",1);let n=this.endpointConfig;try{return await Ml(async()=>{let i=await this._detectProcesses(e);return i.length?i:null},{timeoutMs:n.processWaitTimeoutMs??15e3,intervalMs:n.processCheckIntervalMs??200,firstDelayMs:n.startWaitMs??500,description:`${this.name} process ready`})}catch(i){throw new gr(`${this.name} process did not become ready: ${i.message}`,{cause:i,details:{endpoint:this.name,startCmd:t}})}}async _ensureForward(e,t){if(!await this._tryForward(e,t))throw new gr(`create fport failed: tcp:${e} -> ${t}`,{details:{endpoint:this.name,hostPort:e,deviceEndpoint:t}})}async _tryForward(e,t){return await this.device.fportAdd(e,t)?!0:!!(await this.device.fportListAll()).find(s=>s.hostPort===e&&s.deviceEndpoint===t)}async _selectStableHostPort(e){if(this.mode==="fast"){let t=await this._readFastState(e),n=this.endpointConfig.fastHostPort,i=t&&Number.isInteger(t.hostPort)&&t.hostPort||n;if(i!=null&&Number.isInteger(i)&&!this.device.fportList.some(s=>s.hostPort===i))return i}return this.device.getFreeHostPort()}async _connectAndProbe(e,{probe:t=!0,timeoutMs:n}={}){let i=new zs({host:this.device.hdcHost,port:e,name:this.name,framing:this.config.get("rpc.framing","auto"),concurrency:this.config.get("rpc.concurrency",br.AUTO),maxInFlight:this.config.get("rpc.maxInFlight",16),strictPairing:this.config.get("rpc.strictPairing",!1),timeoutKillsConnection:this.config.get("rpc.timeoutKillsConnection",!1),connectTimeoutMs:n??this.config.get("rpc.connectTimeoutMs",5e3),requestTimeoutMs:this.config.get("rpc.requestTimeoutMs",3e4),socketIdleTimeoutMs:this.config.get("rpc.socketIdleTimeoutMs",3e4),logger:this.logger,dfx:this.dfx});await this._safeCloseTransport("reconnect"),await i.connect(),this._bumpEpoch(),i.onClose=o=>{this._onTransportClose(i,o)},this.transport=i,this.state=Re.CONNECTED,t&&await this._probe()}_onTransportClose(e,t){this.transport===e&&(this._bumpEpoch(),(this.state===Re.READY||this.state===Re.CONNECTED)&&(this.state=this.mode==="fast"?Re.WARM:Re.IDLE,this.logger&&this.logger.warn(`connection lost: ${t?t.message:"closed"}`),this.dfx&&this.dfx.counter("rpc.connection.lost",1,{reason:t?.code||"close"})))}async _probe(){let e=this.config.get("rpc.connectTimeoutMs",5e3),t=this.buildProbePayload(),n=await this.transport.send(t,{timeoutMs:e});if(Wl(n)&&this.logger){let i=n.exception;this.logger.debug(`probe got business exception (link is healthy): ${typeof i=="string"?i:JSON.stringify(i)}`)}return Vl(n)}async request(e,t={}){let{timeoutMs:n}=t,i=this.config.get("rpc.recovery",{}),o=i.enabled!==!1,s=Math.max(0,i.maxAttempts??1),a=null,c=0,l=0;for(let d=0;d<=s+1;d++){if(this._disposed)throw new Ur(`${this.name} rpc is disposed, request rejected`,{details:{endpoint:this.name}});let h=this._epoch;try{await this.ensureReady(),h=this._epoch;let y=await this._sendOnce(e,{timeoutMs:n});return this._logRecovered(c+l),y}catch(y){a=y;let D=await this._handleRequestError(y,o,s,h,c,l,i.delayMs);c=D.ownRecoveries,l=D.borrowedRecoveries}}throw a||new gr(`${this.name} rpc request failed`)}_logRecovered(e){e>0&&this.dfx&&this.dfx.counter("rpc.request.recovered",1,{endpoint:this.name})}async _handleRequestError(e,t,n,i,o,s,a){if(this._disposed||!t||!Jf(e))throw e;return this._epoch===i?o=await this._attemptOwnRecovery(e,n,o):s=this._attemptBorrowedRecovery(e,n,s),a&&await vo(a),{ownRecoveries:o,borrowedRecoveries:s}}async _attemptOwnRecovery(e,t,n){if(n>=t)throw e;let i=n+1;return this.dfx&&this.dfx.counter("rpc.request.retry",1,{code:e.code,attempt:i}),this.logger&&this.logger.warn(`recover from ${e.code||e.name}: ${e.message} (retry ${i}/${t})`),await this.reset({reason:e.message,code:e.code}),i}_attemptBorrowedRecovery(e,t,n){let i=n+1;if(i>t)throw e;return this.dfx&&this.dfx.counter("rpc.request.retry.borrowed",1,{code:e.code}),this.logger&&this.logger.debug(`retry after another caller reset (${e.code||e.name})`),i}async _sendOnce(e,{timeoutMs:t}={}){if(!this.transport||!this.transport.isConnected)throw new $e("rpc transport is not connected",{details:{endpoint:this.name}});let n=await this.transport.send(e,{timeoutMs:t??this.config.get("rpc.requestTimeoutMs",3e4)});return this.interpret(n)}interpret(e){if(Wl(e)){let t=e.exception,n;if(t instanceof Error)n=t.message;else if(typeof t=="string")n=t;else if(t&&typeof t=="object")try{n=JSON.stringify(t)}catch{n=String(t)}else n=String(t);let i=new Bs(`remote exception: ${n}`,{details:{endpoint:this.name,remote:t}});throw this.dfx&&this.dfx.counter("rpc.request.remoteError",1,{endpoint:this.name}),i}return Vl(e)}reset({reason:e="manual",code:t="MANUAL"}={}){return this._resetFlight.run("reset",()=>this._resetOnce({reason:e,code:t}))}async _resetOnce({reason:e="manual",code:t="MANUAL"}={}){if(this._disposed)return;let n=this._readyFlight.pending("ready");if(n&&await n.catch(()=>{}),this._disposed)return;this._bumpEpoch(),this.dfx&&this.dfx.counter("rpc.lifecycle.reset",1,{reason:t}),this.logger&&this.logger.warn(`reset: ${e}`);try{await this._killEndpointProcesses()}catch(s){this.logger&&this.logger.warn(`kill process failed during reset: ${s.message}`)}await this._safeCloseTransport("reset");try{this.ctx.hostPort&&this.ctx.deviceEndpoint&&await this.device.fportRemove(this.ctx.hostPort,this.ctx.deviceEndpoint)}catch(s){this.logger&&this.logger.warn(`remove fport failed during reset: ${s.message}`)}let i=this.ctx.resetCount+1,o=this.ctx.startCount;this.ctx=this._freshContext(),this.ctx.resetCount=i,this.ctx.startCount=o,this.state=Re.IDLE}async release(){if(await this._safeCloseTransport("release"),this.mode==="fast"&&this.config.get("rpc.fast.keepOnRelease",!0)){this.state=Re.WARM,this.dfx&&this.dfx.counter("rpc.release",1,{keep:1}),this.logger&&this.logger.info(`released (keep process & fport on tcp:${this.ctx.hostPort})`);return}await this._removeForward(),await this._killEndpointProcesses(),this.dfx&&this.dfx.counter("rpc.release",1,{keep:0}),this.logger&&this.logger.info("released (process & fport cleaned)"),this.ctx=this._freshContext(),this.state=Re.IDLE}async dispose(){this._disposed=!0,this._bumpEpoch();let e=this._readyFlight.pending("ready");e&&await e.catch(()=>{});let t=this._resetFlight.pending("reset");t&&await t.catch(()=>{}),await this._safeCloseTransport("dispose"),await this._removeForward(),await this._killEndpointProcesses(),this.ctx=this._freshContext(),this.state=Re.DISPOSED}async _removeForward(){let e=new Set;this.ctx.hostPort&&e.add(this.ctx.hostPort),this.mode==="fast"&&this.endpointConfig.fastHostPort&&e.add(this.endpointConfig.fastHostPort);let t=this.ctx.deviceEndpoint||void 0;for(let n of e)try{let i=await this.device.fportRemove(n,t);this.logger&&!i&&this.logger.warn(`remove fport tcp:${n} -> ${t} returned false`)}catch(i){this.logger&&this.logger.debug(`remove fport tcp:${n} failed: ${i.message}`)}}async _killEndpointProcesses(){let t=(await this.device.findProcesses()).filter(n=>this.endpoint.matchProcess(n));for(let n of t)await this.device.killProcess(n.pid);return t.length&&this.logger&&this.logger.info(`killed ${this.name} processes: [${t.map(n=>n.pid).join(", ")}]`),t.length}async _safeCloseTransport(e){if(this.transport){try{await this.transport.close(e)}catch{}this.transport=null}}buildProbePayload(){return{module:"debug",method:"ping",params:{},request_id:void 0}}getSnapshot(){return{name:this.name,mode:this.mode,state:this.state,epoch:this._epoch,disposed:this._disposed,ctx:{...this.ctx},transport:this.transport?this.transport.getSnapshot():null}}};var lm={name:"operate",displayName:"uitest",socketName:"uitest_socket",devicePort:8012,buildDeviceEndpoint(r){return r==="unix"?`localabstract:${this.socketName}`:`tcp:${this.devicePort}`},buildStartCommand(){return"/system/bin/uitest start-daemon singleness &"},buildStopCommands(r){return r.map(e=>xt(["kill","-9",e]))},matchProcess(r){return r.cmd.includes("uitest start-daemon singleness")&&!r.cmd.includes("--extension-name")},async isListening(r,e){return e==="unix"?(await r.shell(`cat /proc/net/unix | ${xt(["grep",this.socketName])}`)).includes(this.socketName):(await r.shell(`netstat -anp | ${xt(["grep",String(this.devicePort)])}`)).includes("LISTEN")}};var Ks=class extends Js{constructor(e){super({...e,endpoint:lm})}async _ensureManagedResources(){if(this.config.get("device.autoPushResources",!0)===!1||!this.device.resources||typeof this.device.resources.ensureAgent!="function")return;let e=await this.device.resources.ensureAgent();this.ctx.agentVersion=e.candidate.version}async _onLaunchFailure(){this.config.get("device.autoPushResources",!0)!==!1&&(!this.device.resources||typeof this.device.resources.repushAgent!="function"||await this.device.resources.repushAgent())}buildProbePayload(){return Bl({module:Ul,method:"ping",params:{},requestId:yr()})}async call(e,t="",n=[],i={}){let o=Bl({module:Ul,method:cm,params:{api:e,this:t,args:n,message_type:"hypium"},requestId:yr()});return this.dfx&&this.dfx.counter("rpc.call",1,{api:e}),this.request(o,i)}async ping(e={}){return this.request(this.buildProbePayload(),e)}};function pM(r){if(r!==void 0)return Array.isArray(r)?{value:String(r[0]),pattern:r[1]}:{value:String(r)}}function dm(r){return iS(r)}function iS(r){let e={};return r.text!==void 0&&(e.text=pM(r.text)),r.key!==void 0&&(e.key=String(r.key)),r.id!==void 0&&(e.id=String(r.id)),r.type!==void 0&&(e.type=String(r.type)),r.clickable!==void 0&&(e.clickable=!!r.clickable),r.scrollable!==void 0&&(e.scrollable=!!r.scrollable),r.enabled!==void 0&&(e.enabled=!!r.enabled),r.focused!==void 0&&(e.focused=!!r.focused),r.selected!==void 0&&(e.selected=!!r.selected),e}function oS(r){let e=iS(r);return r.isBefore&&(e.isBefore=dm(r.isBefore)),r.isAfter&&(e.isAfter=dm(r.isAfter)),r.within&&(e.within=dm(r.within)),e}function fM(r){let e=[];return r.text&&e.push(["On.text",[r.text.value,r.text.pattern??0]]),r.key!==void 0&&e.push(["On.key",[r.key]]),r.id!==void 0&&e.push(["On.id",[r.id]]),r.type!==void 0&&e.push(["On.type",[r.type]]),r.clickable!==void 0&&e.push(["On.clickable",[r.clickable]]),r.scrollable!==void 0&&e.push(["On.scrollable",[r.scrollable]]),r.enabled!==void 0&&e.push(["On.enabled",[r.enabled]]),r.focused!==void 0&&e.push(["On.focused",[r.focused]]),r.selected!==void 0&&e.push(["On.selected",[r.selected]]),e}var Ge=class r{spec;constructor(e={}){this.spec=e}static from(e){return new r(oS(e))}text(e,t){return this.spec.text={value:e,pattern:t},this}key(e){return this.spec.key=e,this}id(e){return this.spec.id=e,this}type(e){return this.spec.type=e,this}clickable(e=!0){return this.spec.clickable=e,this}scrollable(e=!0){return this.spec.scrollable=e,this}enabled(e=!0){return this.spec.enabled=e,this}focused(e=!0){return this.spec.focused=e,this}selected(e=!0){return this.spec.selected=e,this}isBefore(e){return this.spec.isBefore=e.spec,this}isAfter(e){return this.spec.isAfter=e.spec,this}within(e){return this.spec.within=e.spec,this}async buildOn(e){let t=this.spec,n=fM(t);if(n.length===0)throw new Error("Empty selector: at least one lookup condition required");let i=await e.create(n[0][0],n[0][1]);for(let o=1;o<n.length;o++)await e.call(n[o][0],i,n[o][1]);if(t.isBefore){let o=await new r(t.isBefore).buildOn(e);await e.call("On.isBefore",i,[o])}if(t.isAfter){let o=await new r(t.isAfter).buildOn(e);await e.call("On.isAfter",i,[o])}if(t.within){let o=await new r(t.within).buildOn(e);await e.call("On.within",i,[o])}return i}};var Ys=class r{constructor(e,t,n=0){this.host=e;this.selector=t;this.index=n}use(e){return this.host.withComponentRef(this.selector,this.index,t=>e(t))}async click(){await this.use(e=>this.host.rpc.call("Component.click",e,[]))}async doubleClick(){await this.use(e=>this.host.rpc.call("Component.doubleClick",e,[]))}async longClick(){await this.use(e=>this.host.rpc.call("Component.longClick",e,[]))}async inputText(e){await this.use(t=>this.host.rpc.call("Component.inputText",t,[e]))}async clearText(){await this.use(e=>this.host.rpc.call("Component.clearText",e,[]))}async getId(){return String(await this.use(e=>this.host.rpc.call("Component.getId",e,[])))}async getText(){return String(await this.use(e=>this.host.rpc.call("Component.getText",e,[])))}async getType(){return String(await this.use(e=>this.host.rpc.call("Component.getType",e,[])))}async getHint(){return String(await this.use(e=>this.host.rpc.call("Component.getHint",e,[])))}async isClickable(){return!!await this.use(e=>this.host.rpc.call("Component.isClickable",e,[]))}async isScrollable(){return!!await this.use(e=>this.host.rpc.call("Component.isScrollable",e,[]))}async isEnabled(){return!!await this.use(e=>this.host.rpc.call("Component.isEnabled",e,[]))}async isFocused(){return!!await this.use(e=>this.host.rpc.call("Component.isFocused",e,[]))}async isSelected(){return!!await this.use(e=>this.host.rpc.call("Component.isSelected",e,[]))}async getBounds(){return await this.use(t=>this.host.rpc.call("Component.getBounds",t,[]))}async getBoundsCenter(){return await this.use(t=>this.host.rpc.call("Component.getBoundsCenter",t,[]))}async scrollSearch(e){let t=e instanceof Ge?e:Ge.from(e);return await this.host.withComponentRef(this.selector,this.index,async(i,o)=>{let s=await t.buildOn(o),a=await o.call("Component.scrollSearch",i,[s]);return a?(o.track(String(a)),!0):!1})?new r(this.host,t):null}async dragTo(e){let t=e instanceof r?e.selector:e instanceof Ge?e:Ge.from(e);await this.host.withComponentRef(this.selector,this.index,async(n,i,o)=>{let s=await t.buildOn(i),c=(await i.call("Driver.findComponents",o,[s])??[]).map(String);if(i.trackAll(c),c.length===0)throw new Error("dragTo target component not found (0 returned)");await i.call("Component.dragTo",n,[c[0]])})}async pinchOut(e){await this.use(t=>this.host.rpc.call("Component.pinchOut",t,[e]))}async pinchIn(e){await this.use(t=>this.host.rpc.call("Component.pinchIn",t,[e]))}async scrollToTop(e=600){await this.use(t=>this.host.rpc.call("Component.scrollToTop",t,[e]))}async scrollToBottom(e=600){await this.use(t=>this.host.rpc.call("Component.scrollToBottom",t,[e]))}};var mM=600,um=1,Gl=16;function hM(r,e){return Math.hypot(e.x-r.x,e.y-r.y)}function sS(r,e,t,n){if(n!==void 0&&n>0)return Math.max(um,Math.round(n/Gl));let i=hM(r,e);if(i<=0||t<=0)return um;let o=i/t*1e3;return Math.max(um,Math.round(o/Gl))}function ql(r,e,t){return Math.round(r+(e-r)*t)}function aS(r,e,t,n){if(e===null)throw new Error("wait/pressHold before first down, missing start coordinate");for(let i=0;i<n;i++)r.push({pressed:t,x:e.x,y:e.y})}function gM(r,e,t){if(t.pressed)throw new Error("Duplicate down: finger already pressed");let n={x:e.x,y:e.y};t.cur=n,t.pressed=!0,r.push({pressed:t.pressed,x:n.x,y:n.y})}function yM(r,e,t,n){if(n.cur===null)throw new Error("moveTo before down");let i=n.cur,o={x:e.x,y:e.y},s=sS(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;r.push({pressed:n.pressed,x:ql(i.x,o.x,c),y:ql(i.y,o.y,c)})}n.cur=o}function wM(r,e,t,n){if(n.cur===null)throw new Error("move before down");let i=n.cur,o={x:i.x+e.dx,y:i.y+e.dy},s=sS(i,o,t,e.durationMs);for(let a=1;a<=s;a++){let c=a/s;r.push({pressed:n.pressed,x:ql(i.x,o.x,c),y:ql(i.y,o.y,c)})}n.cur=o}function vM(r,e,t){aS(r,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/Gl)))}function bM(r,e,t){if(!t.pressed)throw new Error("pressHold before down");aS(r,t.cur,t.pressed,Math.max(1,Math.round(e.durationMs/Gl)))}function SM(r,e){if(!e.pressed)throw new Error("up before down");e.pressed=!1;let t=e.cur;t!==null&&r.push({pressed:e.pressed,x:t.x,y:t.y})}function EM(r,e){let t=[],n={cur:null,pressed:!1};for(let i of r.actions)switch(i.type){case"down":{gM(t,i,n);break}case"moveTo":{yM(t,i,e,n);break}case"move":{wM(t,i,e,n);break}case"wait":{vM(t,i,n);break}case"pressHold":{bM(t,i,n);break}case"up":{SM(t,n);break}default:{let o=i;throw new Error(`Unknown gesture action: ${JSON.stringify(o)}`)}}return t}function pm(r){if(!r.fingers.length)throw new Error("Gesture requires at least one finger");let e=r.speed??mM,t=r.fingers.map(o=>EM(o,e)),n=Math.max(...t.map(o=>o.length));return{fingers:t.map(o=>{if(o.length===0)return[];let s=o[o.length-1],a=[...o];for(;a.length<n;)a.push({...s});return a}),speed:e}}var PM="PointerMatrix#seed";async function fm(r,e){let{fingers:t,speed:n}=pm(e);if(t.length===0)throw new Error("Empty gesture");let i=t[0].length,o=await r.create("PointerMatrix.create",[t.length,i],PM);for(let s=0;s<t.length;s++)for(let a=0;a<i;a++){let c=t[s][a];await r.call("PointerMatrix.setPoint",o,[s,a,{x:c.x,y:c.y}])}return{ref:o,speed:n}}var cS="Driver.create",CM="BackendObjectsCleaner";var mm="On#seed";async function zl(r,e){let t=e.filter(n=>n&&n!==mm);if(t.length!==0)try{for(let n=0;n<t.length;n+=10)await r.call(CM,"",[t.slice(n,n+10)])}catch{}}var vn=class{constructor(e){this.rpc=e}refs=[];async create(e,t=[],n=mm){let i=String(await this.rpc.call(e,n,t));return this.refs.push(i),i}async call(e,t,n=[]){return this.rpc.call(e,t,n)}track(e){return e&&e!==mm&&this.refs.push(e),e}trackAll(e){for(let t of e)this.track(t);return e}async dispose(){await zl(this.rpc,this.refs),this.refs.length=0}async run(e){try{return await e(this)}finally{await this.dispose()}}};var Xs=class{constructor(e,t,n=0){this.host=e;this.filter=t;this.index=n}use(e){return this.host.withWindowRef(this.filter,this.index,t=>e(t))}async getBundleName(){return String(await this.use(e=>this.host.rpc.call("UiWindow.getBundleName",e,[])))}async isActive(){return!!await this.use(e=>this.host.rpc.call("UiWindow.isActive",e,[]))}async isFocused(){return!!await this.use(e=>this.host.rpc.call("UiWindow.isFocused",e,[]))}async getBounds(){return await this.use(t=>this.host.rpc.call("UiWindow.getBounds",t,[]))}};var Zs=class{constructor(e,t){this.shell=t;this.rpc=e}driverRef=null;rpc;async ensureDriver(){return this.driverRef?this.driverRef:(this.driverRef=String(await this.rpc.call(cS,"",[])),this.driverRef)}selector(e){return e?Ge.from(e):new Ge}findComponent(e,t=0){let n=e instanceof Ge?e:Ge.from(e);return new Ys(this,n,t)}async withComponentRef(e,t,n){let i=await this.ensureDriver();return new vn(this.rpc).run(async s=>{let a=await e.buildOn(s),c=[];for(let l=0;l<8&&(c=(await s.call("Driver.findComponents",i,[a])??[]).map(String),!(c.length>0));l++)await new Promise(h=>setTimeout(h,1e3));if(s.trackAll(c),t>=c.length)throw new Error(`findComponents: no component matched (returned ${c.length}), index ${t} out of range`);return n(c[t],s,i)})}findWindow(e,t=0){return new Xs(this,e,t)}async withWindowRef(e,t,n){let i=await this.ensureDriver();return new vn(this.rpc).run(async s=>{let a;if(t===0){let c=await s.call("Driver.findWindow",i,[kM(e)]);if(!c||c==="null")throw new Error("findWindow: no window matched");a=s.track(String(c))}else throw new Error(`findWindow: only returns a single window, index=${t} not supported`);return n(a,s)})}async gesture(e){await this.swipe(e)}async swipe(e){let t=await this.ensureDriver();await this.withPointerRef(e,async(n,i)=>{await this.rpc.call("Driver.injectMultiPointerAction",t,[n,i])})}async withPointerRef(e,t){return new vn(this.rpc).run(async i=>{let{ref:o,speed:s}=await fm(i,e);return t(o,s,i)})}async screenCapture(e){if(!this.shell)throw new Error("screenCapture requires shell capability (provided via device.uitest)");let t=e.toLowerCase().endsWith(".png")?".png":".jpeg",n=`/data/local/tmp/hypium${t}`;if(await this.shell.shell(`rm -f ${n}`),t===".png"?await this.shell.shell(`uitest screenCap -p ${n}`):await this.shell.shell(`snapshot_display -f ${n}`),!await this.shell.fileRecv(n,e))throw new Error(`screenCapture pull failed: ${n} -> ${e}`)}async setDisplayRotation(e){let t={0:0,90:1,180:2,270:3};if(!(e in t))throw new Error(`rotation must be 0, 90, 180, or 270, got ${e}`);let n=await this.ensureDriver();await this.rpc.call("Driver.setDisplayRotation",n,[t[e]])}async getDisplayRotation(){let e=await this.ensureDriver(),t=await this.rpc.call("Driver.getDisplayRotation",e,[]),n={0:0,1:90,2:180,3:270},i=typeof t=="number"?t:Number(t);return n[i]??i}async setDisplayRotationEnabled(e){let t=await this.ensureDriver();await this.rpc.call("Driver.setDisplayRotationEnabled",t,[e])}async delay(e){await new Promise(t=>setTimeout(t,e))}async pressBack(){let e=await this.ensureDriver();await this.rpc.call("Driver.pressBack",e,[])}async pressHome(){let e=await this.ensureDriver();await this.rpc.call("Driver.pressHome",e,[])}async clickXY(e,t){let n=await this.ensureDriver();await this.rpc.call("Driver.click",n,[e,t])}async doubleClick(e,t){let n=await this.ensureDriver();await this.rpc.call("Driver.doubleClick",n,[e,t])}async inputText(e,t){let n=await this.ensureDriver();await this.rpc.call("Driver.inputText",n,[e,t])}async getDisplaySize(){let e=await this.ensureDriver(),n=await this.rpc.call("Driver.getDisplaySize",e,[]);return{width:n.width??n.x??0,height:n.height??n.y??0}}async assertComponentExist(e,t=!0){let n=e instanceof Ge?e:Ge.from(e),i=await this.ensureDriver();return new vn(this.rpc).run(async s=>{let a=await n.buildOn(s),l=(await s.call("Driver.findComponents",i,[a])??[]).length>0;return t?l:!l})}async release(){this.driverRef&&(await zl(this.rpc,[this.driverRef]),this.driverRef=null)}};function kM(r){let e={};return r.title!==void 0&&(e.title=typeof r.title=="string"?r.title:r.title.value),r.bundleName!==void 0&&(e.bundleName=r.bundleName),r.active!==void 0&&(e.active=r.active),e}function lS({config:r,logger:e,dfx:t,executor:n}){if(n)return n;let i={bin:r.get("hdc.bin","hdc"),host:r.get("hdc.host","127.0.0.1"),port:r.get("hdc.port",8710),execTimeoutMs:r.get("hdc.execTimeoutMs",1e4),logger:e,dfx:t};return new li(i)}var Qs=class r{executor;config;logger;dfx;rpcMode;devices;_rpcFactories;constructor({executor:e,config:t,logger:n,dfx:i,rpcMode:o}){this.executor=e,this.config=t,this.logger=n??null,this.dfx=i??null,this.rpcMode=o||t.get("rpc.mode","stable"),this.devices=new Map,this._rpcFactories=new Map}static async create(e={}){let t=e.config&&typeof e.config.get=="function"?e.config:Gs(e.config||{});e.mode&&t.set("rpc.mode",e.mode);let n=e.logger||Hs("HMDeviceManager"),i=e.dfx||qs({logger:n,tags:{mode:t.get("rpc.mode")}}),o=lS({config:t,logger:n,dfx:i,executor:e.executor});return new r({executor:o,config:t,logger:n,dfx:i,rpcMode:t.get("rpc.mode","stable")})}static _default=null;static async getDefault(e={}){return r._default||(r._default=await r.create(e)),r._default}static resetDefault(){r._default=null}async listTargets(){let e=this.dfx?this.dfx.timer("device.listTargets"):null,t=await this.executor.listTargets();return e&&e({count:t.length}),this.logger&&this.logger.info(`list targets -> [${t.join(", ")}]`),t}async listDevices({detail:e=!1}={}){let n=(await this.listTargets()).map(i=>({serial:i,cached:this.devices.has(i)}));if(!e)return n;for(let i of n)try{let s=await(await this.getDevice(i.serial)).getInfo();Object.assign(i,{model:s.model,abi:s.abi,uitestVersion:s.version,endpointStyle:s.endpointStyle})}catch(o){i.error=o.message}return n}async getDevice(e,t={}){let n=this.dfx?this.dfx.timer("device.create"):null,i=await this.listTargets();if(!i.length)throw new gn("no device connected");let o=e;if(o){if(!i.includes(o))throw new gn(`device ${o} is not found, connected: [${i.join(", ")}]`)}else if(this.config.get("device.autoSelectFirst",!0))o=i[0];else throw new gn("serial is required when autoSelectFirst is disabled");let s=this.devices.get(o);if(s)return n&&n({sn:o,reused:1}),s;let a=new pi({serial:o,executor:this.executor,config:this.config,logger:this.logger,dfx:this.dfx,rpcMode:t.rpcMode||this.rpcMode});for(let[l,d]of this._rpcFactories)a.attachRpc(l,d);return(t.queryVersion??this.config.get("device.queryVersion",!0))&&await a.getUitestInfo(),this.devices.set(o,a),n&&n({sn:o,ok:1}),this.dfx&&this.dfx.counter("device.create",1,{sn:o}),this.logger&&this.logger.info(`device created: ${o}`),a}async createDevice(e,t={}){return this.getDevice(e,t)}async connect(e,t={}){return this.getDevice(e,t)}attachRpc(e,t){if(typeof t!="function")throw new gn(`attachRpc(${e}) expects a factory function`);this._rpcFactories.set(e,t);for(let n of this.devices.values())n.attachRpc(e,t);return this}async removeDevice(e){let t=this.devices.get(e);return t?(await t.release(),this.devices.delete(e),!0):!1}async release({disposeRpc:e=!1}={}){for(let t of this.devices.values())e?await t.dispose():await t.release();this.devices.clear()}async dispose(){for(let e of this.devices.values())await e.dispose();this.devices.clear()}};var DM="6.0.2.2",xM={uitest:r=>new Ks({device:r,config:r.config,logger:r.logger,dfx:r.dfx,mode:r.rpcMode})},pi=class{serial;executor;config;logger;dfx;hdcHost;hdcPort;execTimeoutMs;rpcMode;_uitestInfo;fportList;resources;fastStore;_rpcs;_rpcFactories;_uitestDriver=null;file;fport;proc;constructor({serial:e,executor:t,config:n,logger:i,dfx:o,rpcMode:s}){this.serial=e,this.executor=t,this.config=n,this.logger=i??null,this.dfx=o?o.child({sn:e}):null,this.hdcHost=n.get("hdc.host","127.0.0.1"),this.hdcPort=n.get("hdc.port",8710),this.execTimeoutMs=n.get("hdc.execTimeoutMs",1e4),this.rpcMode=s||n.get("rpc.mode","stable"),this._uitestInfo=null,this.fportList=[],this.resources=new jl({device:this,config:n,logger:this.logger,dfx:this.dfx}),this.fastStore=new Hl({config:n,logger:this.logger}),this._rpcs=new Map,this._rpcFactories=new Map(Object.entries(xM)),this.file=new hm(this),this.fport=new gm(this),this.proc=new ym(this)}get isRemoteHdcServer(){return!!this.hdcHost&&this.hdcHost!=="127.0.0.1"&&this.hdcHost!=="localhost"}get hdcServer(){return`${this.hdcHost||"127.0.0.1"}:${this.hdcPort??8710}`}async exec(e,t={}){let n=["-t",this.serial,...e],i=await this.executor.exec(n,{timeoutMs:t.timeoutMs??this.execTimeoutMs});return this.logger&&this.logger.debug(`hdc ${n.join(" ")} -> ${i.code}`),i}async shell(e,t={}){return im(e),(await this.exec(["shell",e],t)).stdout}async shellArgs(e,t={}){return this.shell(xt(e),t)}async fileSend(e,t,n={}){vr(t),await IM(e);let i=await this.exec(["file","send",e,t],n);if(!(i.ok&&i.stdout.includes("FileTransfer finish")))throw new yn(`push ${e} -> ${t} failed: ${i.stderr||i.stdout}`,{details:{localPath:e,remotePath:t}});return this.dfx&&this.dfx.counter("device.file.send",1),!0}async fileRecv(e,t,n={}){if(vr(e),!await this.fileExists(e))throw new yn(`remote file does not exist: ${e}`);let i=await this.exec(["file","recv",e,t],n);if(!(i.ok&&i.stdout.includes("FileTransfer finish")))throw new yn(`pull ${e} -> ${t} failed: ${i.stderr||i.stdout}`,{details:{localPath:t,remotePath:e}});return this.dfx&&this.dfx.counter("device.file.recv",1),!0}async fileExists(e){vr(e);let t=await this.shellArgs(["ls","-ld",e]);return!!t&&!t.includes("No such file or directory")}async isDirectory(e){vr(e);let t=await this.shellArgs(["ls","-ld",e]);return!!t&&t.startsWith("d")&&!t.includes("No such file or directory")}async rm(e,{force:t=!0}={}){return vr(e),await this.shellArgs(t?["rm","-f",e]:["rm",e]),!0}async mkdir(e){return vr(e),await this.shellArgs(["mkdir","-p",e]),!0}async readRemoteText(e){vr(e);let t=await this.shellArgs(["cat",e]);if(t.includes("No such file or directory"))throw new yn(`remote file does not exist: ${e}`);return t}async listDir(e="/data/local/tmp"){vr(e);let t=await this.shellArgs(["ls",e]);return t.includes("No such file or directory")?[]:t.split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}async fportAdd(e,t){$l(e),Fl(t);let n=await this.exec(["fport",`tcp:${e}`,t]),i=n.ok&&(n.stdout.includes("result:OK")||n.stdout.toLowerCase().includes("success"));if(i){let o={hostPort:e,deviceEndpoint:t,taskString:`tcp:${e} ${t}`};this.fportList.some(s=>s.hostPort===e)||this.fportList.push(o),this.dfx&&this.dfx.counter("device.fport.add",1)}return i}async fportRemove(e,t){$l(e),t&&Fl(t);let n=await this.exec(t?["fport","rm",`tcp:${e}`,t]:["fport","rm",`tcp:${e}`]),i=n.ok&&(n.stdout.includes("result:OK")||n.stdout.toLowerCase().includes("success"));return i&&(this.fportList=this.fportList.filter(o=>o.hostPort!==e),this.dfx&&this.dfx.counter("device.fport.remove",1)),i}async fportListAll(){let e=await this.exec(["fport","ls"]);return Kf(e.stdout)}async getFreeHostPort(e={}){let t=this.config.get("rpc.portRange",{start:1e4,end:19999}),n=new Set([...this.fportList.map(o=>o.hostPort),...e.exclude||[]]),{port:i}=await Yb({hdcHost:this.hdcHost,start:e.start??t.start,end:e.end??t.end,exclude:n});return i}async getFreeDevicePort({start:e=4e4,end:t=49999,exclude:n}={}){let i=await this.shell("cat /proc/net/tcp /proc/net/tcp6 2>/dev/null"),o=new Set(n||[]);for(let s of String(i).split(/\r?\n/)){let c=s.trim().split(/\s+/)[1];if(!c||!c.includes(":"))continue;let l=c.split(":")[1],d=parseInt(l,16);Number.isInteger(d)&&o.add(d)}for(let s=e;s<=t;s++)if(!o.has(s))return s;throw new Dt(`no free device port in range ${e}-${t}`)}async findProcesses(){let e=await this.shellArgs(["ps","-ef"]);return Yf(e)}async killProcess(e){let t=om(e);return await this.shellArgs(["kill","-9",t]),this.dfx&&this.dfx.counter("device.process.kill",1),!0}async getUitestInfo(e=!1){if(this._uitestInfo&&!e)return this._uitestInfo;let t=await Zb(this,{minVersion:this.config.get("device.newUiTestMinVersion",DM)});return this._uitestInfo={version:t.version,arch:t.arch,isNewUiTest:t.isNewUiTest,endpointStyle:t.endpointStyle},this.logger&&this.logger.info(`uitest info: version=${t.version} arch=${t.arch} endpointStyle=${t.endpointStyle}`),this._uitestInfo}async getEndpointStyle(){return this._uitestInfo||await this.getUitestInfo(),this._uitestInfo.endpointStyle}async getSystemProp(e){let t=e.map(n=>({bin:"getprop",key:n}));for(let n of e){let i=n.startsWith("ro.")?`const.${n.slice(3)}`:n;t.push({bin:"param",key:i})}for(let{bin:n,key:i}of t)try{let o=(await this.shellArgs([n,"get",i])).trim();if(!o||/fail|inaccessible|not found|Get parameter/i.test(o))continue;return o}catch{}return""}async getInfo(){let[e,t,n]=await Promise.all([this.getSystemProp(["ro.product.model","const.product.model"]),this.getSystemProp(["ro.product.cpu.abi","const.product.cpu.abilist"]),this.getUitestInfo()]);return{serial:this.serial,model:e,abi:t,...n}}attachRpc(e,t){if(typeof t!="function")throw new Dt(`attachRpc(${e}) expects a factory function`);return this._rpcFactories.set(e,t),this._rpcs.delete(e),this}rpc(e){let t=this._rpcs.get(e);if(t)return t;let n=this._rpcFactories.get(e);if(!n)throw new Dt(`rpc module "${e}" is not attached, available: [${[...this._rpcFactories.keys()].join(", ")}]`);let i=n(this);return this._rpcs.set(e,i),this.logger&&this.logger.debug(`rpc attached: ${e} -> ${i.name}`),i}get uitestRpc(){return this.rpc("uitest")}get uitest(){return this._uitestDriver||(this._uitestDriver=new Zs(this.uitestRpc,{shell:e=>this.shell(e),fileRecv:(e,t)=>this.fileRecv(e,t)})),this._uitestDriver}static async create(e={}){let t=await Qs.getDefault({config:e.config,mode:e.mode});return e.mode&&t.config.set("rpc.mode",e.mode),t.getDevice(e.serial,{queryVersion:e.queryVersion,rpcMode:e.mode})}get operate(){return this.uitestRpc}async call(e,t="",n=[],i={}){return this.uitestRpc.call(e,t,n,i)}getSnapshot(){return{serial:this.serial,mode:this.rpcMode,rpcs:this.listRpcs(),uitest:this.listRpcs().includes("uitest")?this.uitestRpc.getSnapshot():null}}listRpcs(){return[...this._rpcs.keys()]}async releaseRpc(e){let t=e?[e]:[...this._rpcs.keys()];for(let n of t){let i=this._rpcs.get(n);i&&(await i.release(),this._rpcs.delete(n))}!e&&this._uitestDriver&&(await this._uitestDriver.release(),this._uitestDriver=null)}async disposeRpc(e){let t=e?[e]:[...this._rpcFactories.keys()];for(let n of t){let i=this._rpcs.get(n)||this.rpc(n);i&&await i.dispose(),this._rpcs.delete(n)}!e&&this._uitestDriver&&(await this._uitestDriver.release(),this._uitestDriver=null)}async release(){await this.releaseRpc()}async dispose(){await this.disposeRpc(),await this._clearFports()}async _clearFports(){for(let e of[...this.fportList])try{await this.fportRemove(e.hostPort,e.deviceEndpoint)}catch{}this.fportList=[]}toString(){return`HMDevice(${this.serial})`}},hm=class{device;constructor(e){this.device=e}push(e,t,n){return this.device.fileSend(e,t,n)}pull(e,t,n){return this.device.fileRecv(e,t,n)}exists(e){return this.device.fileExists(e)}isDir(e){return this.device.isDirectory(e)}remove(e,t){return this.device.rm(e,t)}mkdir(e){return this.device.mkdir(e)}readText(e){return this.device.readRemoteText(e)}list(e){return this.device.listDir(e)}},gm=class{device;constructor(e){this.device=e}add(e,t){return this.device.fportAdd(e,t)}remove(e,t){return this.device.fportRemove(e,t)}list(){return this.device.fportListAll()}freeHostPort(){return this.device.getFreeHostPort()}},ym=class{device;constructor(e){this.device=e}list(){return this.device.findProcesses()}kill(e){return this.device.killProcess(e)}async find(e){return(await this.device.findProcesses()).filter(n=>n.cmd.includes(e))}};async function IM(r){try{if(!(await RM(r)).isFile())throw new Error("not a file")}catch(e){throw new Dt(`local file does not exist: ${r}`,{cause:e})}}import{fileURLToPath as TM}from"url";import{dirname as NM,join as wm}from"path";import{existsSync as _M}from"fs";var AM={write:(r,e)=>f(e)};zf({name:"uitest",level:"trace",transports:[AM]});function MM(){let r=NM(TM(import.meta.url)),e=[wm(r,"../../resources/uitest"),wm(r,"../src/resources/uitest")];return e.find(t=>_M(wm(t,"uitest_agent_v1.1.9.so")))||e[1]}async function Jl(r,e){let t=Hs("HMDevice"),n=qs({logger:t,tags:{mode:"fast"}}),i=new li({bin:r,logger:t,dfx:n}),o=Gs({device:{resourcesDir:MM()}}),s=new pi({serial:e,executor:i,config:o,logger:t,dfx:n,rpcMode:o.get("rpc.mode","fast")});return await s.getUitestInfo(),{driver:s.uitest,async dispose(){await s.uitest.release(),await s.release()}}}async function $M(r,e,t="default"){let n=await T(r,e),i=new yo(r),o=ea({text:"Querying screen size...",color:"cyan"}).start();try{let s=await i.getDisplayInfo(n);o.stop();let a=ai(s);console.log(a?t==="json"?JSON.stringify({width:a.width,height:a.height},null,2):`${a.width}x${a.height}`:FM("No display info found in output."))}catch(s){throw o.stop(),new w(`Failed to get screen size: ${s.message}`,"Failed to get screen size.")}}async function jM(r,e,t){let n=await T(r,t),i=new yo(r),o=e===-1;if(!o&&(e<5e3||e>36e5))throw new w(`Invalid timeout ${e}ms. Use -1 for never sleep, or a value between 5000 and 3600000ms.`,"Invalid screen-off timeout value.");let s=ea({text:o?"Disabling screen-off...":`Setting screen-off timeout to ${e}ms...`,color:"cyan"}).start();try{o?await i.setScreenNeverSleep(n):await i.setScreenTimeout(n,e),s.stop(),console.log(o?"Screen-off disabled (always on).":`Screen-off timeout set to ${e}ms.`)}catch(a){throw s.stop(),new w(`Failed to set screen-off timeout: ${a.message}`,"Failed to set screen-off timeout.")}}async function HM(r,e,t){let n=await T(r,t),i=ea({text:`Setting screen rotation to ROTATION_${e}...`,color:"cyan"}).start();try{let{driver:o,dispose:s}=await Jl(r.hdcPath,n);try{await o.setDisplayRotation(e)}finally{await s()}i.stop(),console.log(`Screen rotation set to ROTATION_${e}.`)}catch(o){throw i.stop(),new w(`Failed to set screen rotation: ${o.message}`,"Failed to set screen rotation.")}}async function UM(r,e){let t=await T(r,e),n=ea({text:"Querying screen rotation...",color:"cyan"}).start();try{let{driver:i,dispose:o}=await Jl(r.hdcPath,t);try{let s=await i.getDisplayRotation();n.stop(),console.log(`Screen rotation: ROTATION_${s}`)}finally{await o()}}catch(i){throw n.stop(),new w(`Failed to get screen rotation: ${i.message}`,"Failed to get screen rotation.")}}async function BM(r,e,t){let n=await T(r,t),i=ea({text:`${e?"Locking":"Unlocking"} screen rotation...`,color:"cyan"}).start();try{let{driver:o,dispose:s}=await Jl(r.hdcPath,n);try{await o.setDisplayRotationEnabled(!e)}finally{await s()}i.stop(),console.log(e?"Screen rotation locked (auto-rotation disabled).":"Screen rotation unlocked (auto-rotation enabled).")}catch(o){throw i.stop(),new w(`Failed to set rotation lock: ${o.message}`,"Failed to set rotation lock.")}}var fi=new OM("screen").description("Query and manage screen properties");fi.command("size").description("Query screen resolution").option("--device <name|serial>","Target device (name or serial)").addOption(new LM("--format <format>","Output format").choices(["default","json"]).default("default")).action(async r=>{let{device:e,format:t}=r,n={event:v.CommandExecuted,args:["device","screen","size",...t==="json"?["--format","json"]:[],...e?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await $M(i,e,t)})});fi.command("rotation").description("Query current screen rotation").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","screen","rotation",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await UM(n,e)})});fi.command("sleeptime").description("Set screen-off timeout in milliseconds; use -1 for never").allowUnknownOption().option("--device <name|serial>","Target device (name or serial)").argument("<ms>","Screen-off timeout in milliseconds; -1 for never").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","screen","sleeptime","<ms>",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await jM(i,Number(r),t)})});fi.command("rotate").description("Set screen rotation (clockwise)").argument("<rotation>","Rotation angle: 0, 90, 180, or 270").option("--device <name|serial>","Target device (name or serial)").action(async(r,e)=>{let{device:t}=e,n=Number(r);if(![0,90,180,270].includes(n))throw new w(`Invalid rotation "${r}". Valid values: 0, 90, 180, 270`,"Invalid rotation value.");let o={event:v.CommandExecuted,args:["device","screen","rotate","<rotation>",...t?["--device"]:[]]};await N(o,async()=>{let{toolProvider:s}=await _();await HM(s,n,t)})});fi.command("rotation-lock").description("Lock or unlock screen rotation (on=lock/disable auto-rotation, off=unlock/enable auto-rotation)").argument("<state>","on or off").option("--device <name|serial>","Target device (name or serial)").action(async(r,e)=>{let{device:t}=e;if(r!=="on"&&r!=="off")throw new w(`Invalid state "${r}". Valid values: on, off`,"Invalid rotation-lock state.");let n={event:v.CommandExecuted,args:["device","screen","rotation-lock","<state>",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await BM(i,r==="on",t)})});import{Command as WM}from"commander";import{gray as VM}from"colorette";import GM from"ora";var ta=class{constructor(e){this.toolProvider=e}async readClipboard(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-pastedata"]);if(Ve(t),t.exitCode!==0)throw new Error(t.stderr||t.stdout||"read clipboard failed");return t.stdout}async writeClipboard(e,t){let n=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-pastedata",t]);if(Ve(n),n.exitCode!==0)throw new Error(n.stderr||n.stdout||"write clipboard failed");return n.stdout}async clearClipboard(e){let t=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","clear-pastedata"]);if(Ve(t),t.exitCode!==0)throw new Error(t.stderr||t.stdout||"clear clipboard failed");return t.stdout}};async function vm(r,e,t,n){let i=await T(r,n),o=new ta(r),s=GM({text:`Clipboard ${e}...`,color:"cyan"}).start();try{let a;if(e==="read"?a=await o.readClipboard(i):e==="write"?a=await o.writeClipboard(i,t??""):a=await o.clearClipboard(i),s.stop(),e==="read"){let c=a.trim().replace(/^Pasteboard text:\s*/,"");console.log(c||VM("(clipboard is empty)"))}else console.log(`Clipboard ${e==="write"?"written":"cleared"}.`)}catch(a){throw s.stop(),new w(`Clipboard ${e} failed: ${a.message}`,`Clipboard ${e} failed.`)}}var ra=new WM("clipboard").description("Read, write, or clear the device clipboard");ra.command("read").description("Read current clipboard text from the device").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","clipboard","read",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await vm(n,"read",void 0,e)})});ra.command("write").description("Write text to the device clipboard").option("--device <name|serial>","Target device (name or serial)").argument("<text>","Text to write to the clipboard").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","clipboard","write",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await vm(i,"write",r,t)})});ra.command("clear").description("Clear the device clipboard").option("--device <name|serial>","Target device (name or serial)").action(async r=>{let{device:e}=r,t={event:v.CommandExecuted,args:["device","clipboard","clear",...e?["--device"]:[]]};await N(t,async()=>{let{toolProvider:n}=await _();await vm(n,"clear",void 0,e)})});import{Command as qM}from"commander";import{yellow as zM}from"colorette";import{existsSync as JM}from"fs";import bm from"ora";import{execa as Kl}from"execa";var Po=class{constructor(e){this.toolProvider=e}async fileExists(e,t){let n=this.toolProvider.hdcPath,i=["-t",e,"shell","ls","-l",t];f(`Executing: ${n} ${i.join(" ")}`);let o;try{let{stdout:s,stderr:a}=await Kl(n,i,{env:{...process.env}});o=`${s}
|
|
106
|
+
${a}`}catch(s){let a=s;if(o=`${a.stdout??""}
|
|
107
|
+
${a.stderr??""}
|
|
108
|
+
${a.message??""}`,/no such file or directory/i.test(o))return!1;throw s}return!/no such file or directory/i.test(o)}async deleteFile(e,t){let n=this.toolProvider.hdcPath,i=["-t",e,"shell","rm","-f",t];f(`Executing: ${n} ${i.join(" ")}`);try{let{stdout:o}=await Kl(n,i,{env:{...process.env}});return o}catch(o){return o.stdout??""}}async sendFile(e,t,n){let i=this.toolProvider.hdcPath,o=["-t",e,"file","send",t,n];f(`Executing: ${i} ${o.join(" ")}`);let{stdout:s}=await Kl(i,o,{env:{...process.env}});if(!s.includes("FileTransfer finish"))throw new Error(`File send failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}async recvFile(e,t,n){let i=this.toolProvider.hdcPath,o=["-t",e,"file","recv",t,n];f(`Executing: ${i} ${o.join(" ")}`);let{stdout:s}=await Kl(i,o,{env:{...process.env}});if(!s.includes("FileTransfer finish"))throw new Error(`File recv failed: ${s.trim()||"hdc returned no output"}`);return s.trim()}};async function dS(r,e,t,n,i){let o=await T(r,i),s=e==="send";if(s&&!JM(t))throw new w(`File not found: ${t}`,"File not found.");let a=new le(r),c=bm({text:s?`Sending ${t} to ${n}...`:`Receiving ${t} to ${n}...`,color:"cyan"}).start();try{await a.transferFile(o,e,t,n),c.stop(),console.log(`${s?"Sent to device":"Received from device"}: ${t} -> ${n}`)}catch(l){c.stop();let d=s?"Send":"Recv";throw new w(l.message,`File ${d} failed.`)}}async function KM(r,e,t){let n=await T(r,t),i=new Po(r),o=bm({text:`Checking ${e}...`,color:"cyan"}).start();try{let s=await i.fileExists(n,e);o.stop(),s?console.log(`exists: ${e}`):(console.log(zM(`not found: ${e}`)),process.exitCode=1)}catch(s){throw o.stop(),new w(`Existence check failed: ${s.message}`,"Existence check failed.")}}async function YM(r,e,t){let n=await T(r,t),i=new Po(r),o=bm({text:`Deleting ${e}...`,color:"cyan"}).start();try{if(!await i.fileExists(n,e))throw o.stop(),new w(`File not found: ${e}`,"File not found.");let a=await i.deleteFile(n,e);o.stop();let c=a.trim();if(c&&/error|no such file/i.test(c))throw new Error(c);console.log(`Deleted ${e}.`)}catch(s){throw o.stop(),new w(`Delete failed: ${s.message}`,"Delete failed.")}}var Co=new qM("file").description("Transfer files between the host and a connected device");Co.command("send").description("Send a local file to a device").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Local file path to upload").argument("<dst>","Remote path on the device").action(async(r,e,t)=>{let{device:n}=t,i={event:v.CommandExecuted,args:["device","file","send",...n?["--device"]:[]]};await N(i,async()=>{let{toolProvider:o}=await _();await dS(o,"send",r,e,n)})});Co.command("recv").description("Receive a file from a device to the host").option("--device <name|serial>","Target device (name or serial)").argument("<src>","Remote path on the device").argument("<dst>","Local file path to save").action(async(r,e,t)=>{let{device:n}=t,i={event:v.CommandExecuted,args:["device","file","recv",...n?["--device"]:[]]};await N(i,async()=>{let{toolProvider:o}=await _();await dS(o,"recv",r,e,n)})});Co.command("exist").description("Check if a file exists on the device").option("--device <name|serial>","Target device (name or serial)").argument("<path>","Remote path on the device to check").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","file","exist",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await KM(i,r,t)})});Co.command("delete").description("Delete a file on the device").option("--device <name|serial>","Target device (name or serial)").argument("<path>","Remote path on the device to delete").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","file","delete",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await YM(i,r,t)})});import{Command as ZM}from"commander";import{red as QM}from"colorette";import{existsSync as eO}from"fs";import tO from"ora";import{basename as XM}from"path";var na=class{constructor(e){this.toolProvider=e;this.hdc=new le(e)}hdc;async pushFontToDevice(e,t){let n=`/data/local/tmp/${XM(t)}`;return await this.hdc.transferFile(e,"send",t,n),n}async installFont(e,t){let n=await this.pushFontToDevice(e,t),i=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","install-font",n]);return Ve(i),i.stdout}async getFontInfo(e,t){let n=await this.pushFontToDevice(e,t),i=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","get-fontname",n]);return Ve(i),i.stdout}async uninstallFont(e,t){let n=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","uninstall-font",t]);return Ve(n),n.stdout}};async function Sm(r,e,t,n){let i=await T(r,n);if(e!=="uninstall"&&!eO(t))throw new w(`Font file not found: ${t}`,"Font file not found.");let o=new na(r),s=tO({text:`Font ${e} ${t}...`,color:"cyan"}).start();try{let a;e==="install"?a=await o.installFont(i,t):e==="info"?a=await o.getFontInfo(i,t):a=await o.uninstallFont(i,t),s.stop();let c=a.trim();/^error/i.test(c)?(console.error(QM(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new w(a.message,`Font ${e} failed.`)}}var ia=new ZM("font").description("Manage device fonts");ia.command("install").description("Install a font on the device").option("--device <name|serial>","Target device (name or serial)").argument("<fontpath>","Local font file path to install").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","font","install","<fontpath>",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await Sm(i,"install",r,t)})});ia.command("info").description("Get font name from a font file").option("--device <name|serial>","Target device (name or serial)").argument("<fontpath>","Local font file path to query").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","font","info","<fontpath>",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await Sm(i,"info",r,t)})});ia.command("uninstall").description("Uninstall a font from the device").option("--device <name|serial>","Target device (name or serial)").argument("<name>","Font name to uninstall").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","font","uninstall","<name>",...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await Sm(i,"uninstall",r,t)})});import{Command as rO}from"commander";import{red as nO}from"colorette";import iO from"ora";var oa=class{constructor(e){this.toolProvider=e}async getViewmode(e){return(await C(this.toolProvider.hdcPath,["-t",e,"shell","param","get","persist.ace.darkmode"])).stdout}async setViewmode(e,t){let n=await C(this.toolProvider.hdcPath,["-t",e,"shell","testhelper","set-viewmode",t]);return Ve(n),/already set to/i.test(n.stdout)?n.stdout.replace(/^Error:\s*/i,"").trim():n.stdout}};async function oO(r,e,t){let n=await T(r,t),i=new oa(r),o=e!==void 0;if(o&&e!=="dark"&&e!=="light")throw new w(`Invalid viewmode "${e}". Valid values: dark, light`,"Invalid viewmode value.");let s=iO({text:o?`Setting viewmode to ${e}...`:"Getting viewmode...",color:"cyan"}).start();try{let a=o?await i.setViewmode(n,e):await i.getViewmode(n);s.stop();let c=a.trim();/fail/i.test(c)?(console.error(nO(c)),process.exitCode=1):console.log(c)}catch(a){throw s.stop(),new w(`Viewmode ${o?"set":"get"} failed: ${a.message}`,`Viewmode ${o?"set":"get"} failed.`)}}var uS=new rO("viewmode").description("Get or set the device view mode").option("--device <name|serial>","Target device (name or serial)").argument("[mode]","View mode to set (dark|light); omit to get current").action(async(r,e)=>{let{device:t}=e,n={event:v.CommandExecuted,args:["device","viewmode",...r?[r]:[],...t?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await oO(i,r,t)})});function dO(r,e){if(e.size!==0)for(let t of r){if(!t.isEmulator||!t.name)continue;let n=e.get(Fe(t.name));n&&(t.deviceType=n)}}var uO=["Name","Serial","Kind","Device Type"];function pO(r){return{cells:[r.name??r.serial,r.serial,r.isEmulator?"emulator":"device",r.deviceType??"-"],highlight:!0}}function mS(r,e){return r.isEmulator!==e.isEmulator?r.isEmulator?1:-1:(r.name??r.serial).localeCompare(e.name??e.serial)}function fO(){console.log(aO(" No active devices.")),console.log(cO(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function mO(r){let t=[...r].sort(mS).map(pO);console.log(jr(uO,t))}function hO(r){return{name:r.name??r.serial,serial:r.serial,kind:r.isEmulator?"emulator":"device",deviceType:r.deviceType}}function gO(r){let e=[...r].sort(mS);console.log(JSON.stringify(e.map(hO),null,2))}async function yO(r,e){if(!r.some(i=>i.isEmulator)||!e.emulatorPath)return;let n=await go.from(e).getDeviceTypeByName();dO(r,n)}async function pS(r,e,t,n="table"){try{let i=await r.getConnectedEntries();if(await yO(i,e),t?.stop(),n==="json"){gO(i);return}i.length===0?fO():mO(i)}catch(i){throw new w(`Failed to list devices: ${i.message}`,"Failed to list devices.")}finally{t?.stop()}}async function wO(r,e){let t=await r.listDevices();if(t.length<2)return;let n=["Multiple devices connected. Specify a device with:"];for(let i of t){let o=await r.getDeviceName(i.serial);n.push(` ${e} -t ${i.serial} # ${o}`)}throw new w(n.join(`
|
|
109
|
+
`),"Multiple devices connected.")}async function vO(r,e,t="table"){e||await wO(r,"devecocli device view");let n=await r.listDevices(),i=await r.getDeviceInfo(n,e);if(!i){if(t==="json"){console.error("No connected device found."),process.exitCode=1;return}throw new w("No connected device found.")}let o=await r.getDeviceDetail(i.serial),s=await r.getDeviceName(i.serial);if(t==="json"){let a={name:s,serial:i.serial,kind:ur(i.serial)?"emulator":"device",deviceType:o.deviceType,osVersion:o.osVersion};console.log(JSON.stringify(a,null,2));return}console.log(` Serial: ${i.serial}`),console.log(` Device Name: ${s}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`)}async function bO(r,e,t,n){let i=await T(r,n),o=new le(r);try{await o.runSqlite3(i,e,t)}catch(s){throw new w(`sqlite3 failed: ${s.message}`,"sqlite3 failed.")}}var Kt=new sO("device").description("Manage connected devices");Kt.command("list").description("List all connected devices").addOption(new fS("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:v.CommandExecuted,args:["device","list",...r.format==="json"?["--format","json"]:[]]};await N(e,async()=>{let{manager:t,toolProvider:n}=await _();if(r.format==="json"){await pS(t,n,void 0,"json");return}let i=lO({text:"Querying connected devices\u2026",color:"cyan"}).start();await pS(t,n,i,"table")})});Kt.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new fS("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:v.CommandExecuted,args:["device","view",...r.target?["--target"]:[],...r.format==="json"?["--format","json"]:[]]};await N(e,async()=>{let{manager:t}=await _();await vO(t,r.target,r.format)})});Kt.addCommand(Gt);Kt.addCommand(Co);Kt.addCommand(ra);Kt.addCommand(fi);Kt.addCommand(ia);Kt.addCommand(uS);for(let r of Bb)Kt.addCommand(r);Kt.command("sqlite3").description("Run sqlite3 on a connected device").allowUnknownOption().option("--device <name|serial>","Target device (name or serial)").argument("<db-path>","SQLite database path on the device").argument("[args...]","Arguments forwarded to sqlite3 as-is").action(async(r,e,t)=>{let n={event:v.CommandExecuted,args:["device","sqlite3",r,...t.device?["--device"]:[]]};await N(n,async()=>{let{toolProvider:i}=await _();await bO(i,r,e,t.device)})});var hS=Kt;import{Argument as Am,Command as Tm,InvalidArgumentError as xm,Option as qe}from"commander";import{green as ca,cyan as Ro,red as Nm,yellow as Sn,gray as Im}from"colorette";import LO from"ora";import SO from"readline/promises";import{execa as yS}from"execa";import*as bn from"fs/promises";import*as Pm from"os";import*as mi from"path";var Em=`1/4:\r
|
|
101
110
|
---------------------------------------\r
|
|
102
111
|
Statement About HarmonyOS and Privacy\r
|
|
103
112
|
\r
|
|
@@ -1267,13 +1276,13 @@ Part I: Chinese mainland.\r
|
|
|
1267
1276
|
Part II: Aland Islands, Albania, Andorra, Australia, Austria, Belgium, Bonaire, Bosnia and Herzegovina, Bulgaria, Canada, Croatia, Curacao, Cyprus, Czech Republic, Denmark, Dutch Caribbean, Estonia, Faroe Islands, Finland, France, Germany, Gibraltar, Greece, Greenland, Guernsey, Hungary, Iceland, Israel, Italy, Jersey, Latvia, Liechtenstein, Lithuania, Luxembourg, Malta, Moldova, Monaco, Montenegro, Netherlands, New Zealand, North Macedonia, Norway, Poland, Portugal, Ireland, Romania, Saba, Saint Vincent and the Grenadines, San Marino, Serbia, Sint Eustatius, Sint Maarten, Slovakia, Slovenia, Spain, St. Martin, St. Pierre and Miquelon (France), Sweden, Switzerland, Turkey, Ukraine, United Kingdom, United States, Vatican City.\r
|
|
1268
1277
|
\r
|
|
1269
1278
|
Part III: Other countries and regions.\r
|
|
1270
|
-
---------------------------------------\r`;var
|
|
1271
|
-
`),
|
|
1272
|
-
`)}function
|
|
1273
|
-
${t}.`);return
|
|
1274
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1279
|
+
---------------------------------------\r`;var EO=new Set,Yl=new Map,Cm="HarmonyOS_Software_Service_Agreement",wS=["Emulator license agreements are not accepted yet.","","Accept the agreements interactively (shows full text + y/N prompt):"," devecocli emulator license","","Or accept non-interactively (no prompt, for CI/scripts):"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
|
|
1280
|
+
`),vS=wS,km="HarmonyOS_SDK_Agreement";function bS(r,e){return`${r}\0${e}`}function SS(){EO.clear(),Yl.clear()}var PO=wS,Br=class extends Error{constructor(e=PO){super(e),this.name="EmulatorLicenseBlockedError"}};function ES(r,e){return[r??"",e??""].join(`
|
|
1281
|
+
`)}function PS(r){let e=r.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let n=e.match(/(\d+)\.(\d+)\b/);return n?`${n[1]}.${n[2]}`:null}function CO(r){return`Emulator${r.trim()}`}function CS(r){let e=CO(r);if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;if(!n)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return mi.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return mi.join(Pm.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||mi.join(Pm.homedir(),".cache");return mi.join(t,"Huawei",e,".emu_config")}async function kO(r,e,t){let n=bS(r,e),i=Yl.get(n);if(i!==void 0)return i;let o=await yS(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ES(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Br(t);return Yl.set(n,s),s}function RO(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function DO(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,i]of Object.entries(e))t[n]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function xO(r){let e=r.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let n=e.indexOf(t);if(n<=0)continue;let i=e.slice(0,n).trim();if(!i||t===":"&&i.includes("//"))continue;let o=RO(e.slice(n+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function IO(r){let e={};for(let t of r.split(/\r?\n/)){let n=xO(t);n&&(e[n.key]=n.entry)}return e}function AO(r){let e=r.trim();if(!e)return{};let t=DO(e);return t||IO(r)}function TO(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function kS(r,e,t,n){let i=await kO(r,e,n),o=PS(i);if(!o)throw new Br(n);let s=CS(o),a;try{a=await bn.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Br(n):d}let l=AO(a)[t];if(!l)throw new Br(n);if(l.delimiter==="=")throw new Br(n);if(!TO(l.value))throw new Br(n)}async function Rm(r,e){await kS(r,e,Cm,vS)}async function Dm(r,e){await kS(r,e,km,vS)}async function NO(r,e){let t=await yS(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=ES(t.stdout,t.stderr).trim();if(t.exitCode!==0||!n)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=bS(r,e);return Yl.set(i,n),n}async function RS(r,e){let t=await NO(r,e),n=PS(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1282
|
+
${t}.`);return CS(n)}function gS(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function _O(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[Cm]="agree",n[km]="agree",await bn.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
1283
|
+
`,"utf8"),!0}catch{}return!1}async function MO(r,e){let t=Cm,n=km,i=[{k:t,re:new RegExp(`^\\s*${gS(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${gS(n)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:h}of i)if(h.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(n)||s.push(`${n}:agree`),await bn.writeFile(r,s.join(`
|
|
1275
1284
|
`)+(s.length>0?`
|
|
1276
|
-
`:""),"utf8")}async function
|
|
1285
|
+
`:""),"utf8")}async function DS(r){await bn.mkdir(mi.dirname(r),{recursive:!0});let e="";try{e=await bn.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await _O(r,e,t)||await MO(r,e)}async function xS(r,e){return console.log(Em),0}var OO="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function IS(r,e){try{return await Rm(r,e),await Dm(r,e),!0}catch(t){if(t instanceof Br)return!1;throw t}}async function AS(r,e){if(await IS(r,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Em),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license` requires an interactive terminal.\nFor non-interactive environments, use: devecocli emulator license accept"),1;let n=SO.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(OO)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await RS(r,e);await DS(s),SS()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function TS(r,e){if(await IS(r,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await RS(r,e);await DS(t),SS()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function It(r,e){let t=Date.now(),n=!0,i=null;try{await e()}catch(o){n=!1,i=Z(o),console.error(Nm(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(r,o)}}var FO=["ohos.qemu.hvd.name","const.product.name","const.product.model"],NS=["open","half-open","close","vertical-open","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"],$O=`
|
|
1277
1286
|
Folded state scene mappings:
|
|
1278
1287
|
foldableFold (3):
|
|
1279
1288
|
open Fully expanded state
|
|
@@ -1296,92 +1305,133 @@ Folded state scene mappings:
|
|
|
1296
1305
|
left-half-folded-right-folded
|
|
1297
1306
|
left-expanded-right-half-folded
|
|
1298
1307
|
left-half-folded-right-half-folded
|
|
1299
|
-
`,
|
|
1300
|
-
${
|
|
1301
|
-
${
|
|
1302
|
-
${
|
|
1303
|
-
`)}});
|
|
1304
|
-
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function hg(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function gg(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=lo(Zn(i,["osVersion","OsVersion","OSVersion","os_version"])),s=lo(Zn(i,["deviceType","DeviceType","device_type"])),a=lg(Zn(i,["downloaded","Downloaded","isDownloaded"])),c=lo(Zn(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=lo(Zn(i,["releaseType","ReleaseType","release_type"])),d=lg(Zn(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function nA(n){let e=n.trim();if(!e)return!0;let t=hg(e);return t===null?!1:t.length===0?!0:gg(t,!0).length===0}function iA(n,e){let t=n.trim();if(!t)return"";let r=hg(t);if(!r)return n.trimEnd();let i=gg(r,e);return Xt(eA,i)}var ia=new bd("image").description("HarmonyOS emulator system images (download, list, remove)");ia.command("download").description("Download system image").addOption(Pd(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","download",...n.deviceType?["--device-type"]:[],...n.osVersion?["--os-version"]:[],...n.force?["--force"]:[]]};await ft(e,async()=>{let{manager:t,toolProvider:r}=await ht();await yd(r.emulatorPath,r.sdkPath);let i=n.deviceType?.trim(),o=n.osVersion?.trim();if(!i)throw new S("Error: missing required option '--device-type <type>'","Missing required device type.");if(!o)throw new S("Error: misssing required option '--os-version <version>'","Missing required OS version.");await rA(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:n.force===!0})})});ia.command("remove").description("Remove a downloaded system image").addOption(Pd(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await ft(e,async()=>{let{manager:t}=await ht();await t.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})})});ia.command("list").description("List system images").addOption(Pd(!1)).option("--all","List all images (local and remote)").addOption(new Oe("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","image","list",...n.deviceType?["--device-type"]:[],...n.all?["--all"]:[],...n.format!=="table"?["--format"]:[]]};await ft(e,async()=>{let{manager:t}=await ht(),r;n.all?r=void 0:r=!0;let i=await t.listEmulatorImages({deviceType:n.deviceType,downloaded:r});if(nA(i)){console.log(Er(tA));return}if(n.format==="json"){console.log(i.trimEnd());return}let o=iA(i,n.all===!0);console.log(o)})});ye.addCommand(ia);var oa=new bd("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");oa.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","view"]};await ft(n,async()=>{let{toolProvider:e}=await ht(),t=await ig(e.emulatorPath,e.sdkPath);process.exitCode=t})});oa.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license","accept"]};await ft(n,async()=>{let{toolProvider:e}=await ht(),t=await ag(e.emulatorPath,e.sdkPath);process.exitCode=t})});oa.action(async()=>{let n={event:b.CommandExecuted,args:["emulator","license"]};await ft(n,async()=>{let{toolProvider:e}=await ht(),t=await sg(e.emulatorPath,e.sdkPath);process.exitCode=t})});ye.addCommand(oa);ye.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Qt(n,()=>({type:"shake"}),"shake"));ye.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Qt(n,()=>({type:"power"}),"power"));ye.command("rotate").description("Rotate emulator").addOption(new Oe("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Sd("<direction>").choices(["left","right"])).action((n,e)=>Qt(e,()=>({type:"rotation",direction:n}),"rotate"));ye.command("volume").description("Change volume").addOption(new Oe("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Sd("<direction>").choices(["up","down"])).action((n,e)=>Qt(e,()=>({type:"volume",direction:n}),"volume"));ye.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",II).action((n,e)=>Qt(e,()=>({type:"folded-state",state:RI(n)}),"fold"));ye.command("battery").description("Set battery level and/or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new Oe("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Qt(n,()=>YI(n),"battery"));ye.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Qt(n,()=>zI(n),"geolocation"));ye.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Sd("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Qt(e,()=>t[n],"scene")});ye.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Qt(n,()=>JI(n),"sensor"));ye.command("list").description("List all emulator instances").addOption(new Oe("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new Oe("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let e={event:b.CommandExecuted,args:["emulator","list",...n.details?["--details"]:[],...n.format!=="table"?["--format"]:[]]};await ft(e,async()=>{let{manager:t,toolProvider:r}=await ht();if(n.details){let o=await t.listEmulatorDetails();console.log(o.trimEnd());return}let i=n.format==="table"?CI({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await $I(t,r.hdcPath,n.format,i)})});function oA(n){let e=n.trim();if(!/^\d+$/.test(e))throw new vd("--hdcport must be an integer in [10000, 16555].");let t=Number(e);if(t<1e4||t>16555)throw new vd("--hdcport must be in [10000, 16555].");return t}function sA(n){return{hdcPort:n.hdcport,bootMode:n.bootMode,noWindow:n.window===!1}}function aA(n){return[...n.hdcport!==void 0?["--hdcport"]:[],...n.bootMode!==void 0?["--boot-mode"]:[],...n.window===!1?["--no-window"]:[]]}ye.command("start [names...]").description("Start one or more emulator instances").addOption(new Oe("--hdcport <port>","hdc port of the emulator, 10000-16555 (Emulator -hdcport)").argParser(oA)).addOption(new Oe("--boot-mode <mode>","Boot mode (Emulator -bootMode): coldboot = cold start keeping user data, snapshot = hot start restoring the last snapshot (needs Quick Boot), reset = wipe data then cold start; overrides the mode chosen when the instance was created").choices(["coldboot","snapshot","reset"])).addOption(new Oe("--no-window","Start the emulator without a window (Emulator -noWindow); required on Linux hosts without a GUI")).action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","start",...aA(e)],emulatorMemory:"unknown",hotBoot:null};await ft(t,async()=>{let{manager:r,toolProvider:i}=await ht();if(await gd(i.emulatorPath,i.sdkPath),!n?.length)throw new S("Error: missing required argument 'names'","Missing required emulator name.");if(n.length>1&&e.hdcport!==void 0)throw new S(`Error: --hdcport cannot target ${n.length} emulators.`,"--hdcport sets the hdc port of a single emulator; pass one name, or omit --hdcport.");let o=await VI(r,i.hdcPath,n,sA(e));t.emulatorMemory=o.emulatorMemory,t.hotBoot=o.hotBoot})});ye.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let e={event:b.CommandExecuted,args:["emulator","stop"]};await ft(e,async()=>{let{manager:t,toolProvider:r}=await ht();if(!n?.length){console.error(Ed("Error: missing required argument 'names'")),process.exitCode=1;return}await qI(t,r.hdcPath,n)})});var cA=ye.command("create <name>").description("Create a local emulator instance.").addOption(XI()).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').addOption(new Oe("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new Oe("--screen <config...>",'Screen: "width(px) height(px) DPI screen-diagonal-length(inch)" (720-3500, 720-3500, 240-640, 3.5-9); pass two values for a foldable device')).option("--storage <size>","Storage size in GB (2-1023)").option("--memory <size>","Memory size in GB (2-32)").addOption(new Oe("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");cA.action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","create",...QI(e)]};await ft(t,async()=>{if(!e.osVersion.trim())throw new Error("--os-version must not be empty.");let r={name:n,deviceType:e.deviceType,osVersion:e.osVersion,instancePath:e.instancePath,imageRoot:e.imageRoot,screenProfile:e.screenProfile,screen:ZI(e.screen),storage:e.storage===void 0?void 0:cn("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:cn("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:i}=await ht();console.log(Qn(`Creating emulator "${n}"...`)),await i.createVirtualDevice(r),console.log(uo(`Emulator "${n}" created successfully.`))})});ye.command("delete <name>").description("Delete a local emulator instance").addOption(new Oe("--path, --instance-path <path>","Emulator instance path")).action(async(n,e)=>{let t={event:b.CommandExecuted,args:["emulator","delete",...e.instancePath!==void 0?["--instance-path"]:[]]};await ft(t,async()=>{let{manager:r}=await ht();console.log(Qn(`Deleting emulator "${n}"...`));let i=await r.deleteVirtualDevice(n,e.instancePath);console.log(uo(`Emulator "${i}" deleted successfully.`))})});var yg=ye;import{Command as $A}from"commander";import{red as Ld,cyan as kt}from"colorette";import*as qg from"readline";import*as Vg from"crypto";import*as vg from"http";import*as wg from"crypto";import{URL as lA}from"url";var sa=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=vg.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new lA(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let i="",o=0,s=65536;e.on("data",a=>{if(o+=a.length,o>s){e.destroy(new Error("Request body too large"));return}i+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,i)})}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&wg.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as ze from"fs";import*as Pr from"path";import{homedir as mA}from"os";var er={};bS(er,{LocalCrypto:()=>er,decryptForLocalStorage:()=>Ad,decryptForLocalStorageFromDirectory:()=>pA,encryptForLocalStorage:()=>Id,isEncryptedBlob:()=>Dd});import*as ae from"fs";import*as Fe from"path";import*as qe from"crypto";import*as bg from"os";import{homedir as Eg}from"os";var _e=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var po=Vr.ALGORITHM,Pg=Vr.IV_LENGTH,mo=Vr.KEY_LENGTH,fo=Vr.KEY_LENGTH,ln=Vr.KEK_VERSIONS,aa=process.env.DEVECO_CLI_DATA_DIR?W():Fe.join(Eg(),ge.CONFIG_DIR_NAME,ge.APP_NAME),ca=Fe.join(Eg(),".local","share",ge.APP_NAME,"keys"),ei=Fe.join(aa,ge.KEY_FILE_NAME);function Sg(n){return bg.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${n}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${n}`}function Cd(n){return Fe.join(ca,`${n}.bin`)}function Cg(){if(!ae.existsSync(aa))try{ae.mkdirSync(aa,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new _e(Sg(aa)):n}if(!ae.existsSync(ca))try{ae.mkdirSync(ca,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new _e(Sg(Fe.dirname(ca))):n}}function kg(){Cg();for(let n of ln){let e=Cd(n);ae.existsSync(e)||ae.writeFileSync(e,qe.randomBytes(mo),{mode:384})}}function Ig(n){if(!ln.includes(n))throw new Error(`Invalid kekId: ${n}`);kg();let e=Cd(n),t=ae.readFileSync(e);if(t.length===mo)return t;let r=qe.randomBytes(mo);return ae.writeFileSync(e,r,{mode:384}),r}function kd(n,e){let t=qe.randomBytes(Pg),r=Ig(e),i=qe.createCipheriv(po,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:po,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Ag(n,e){return Dg(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Dg(n,e,t,r){let i=qe.createDecipheriv(po,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function Rg(n,e){return Dg(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function dA(){if(kg(),ae.existsSync(ei))return;let n=qe.randomBytes(fo),e=kd(n,ln[0]);ae.writeFileSync(ei,JSON.stringify(e,null,2),{mode:384})}function Tg(){dA();let n=JSON.parse(ae.readFileSync(ei,"utf8")),e=Ag(n,Ig(n.kekId));if(e.length===fo)return e;let t=qe.randomBytes(fo),r=kd(t,ln[0]);return ae.writeFileSync(ei,JSON.stringify(r,null,2),{mode:384}),t}function uA(){Cg();for(let t of ln){let r=Cd(t);ae.existsSync(r)||ae.writeFileSync(r,qe.randomBytes(mo),{mode:384})}if(ae.existsSync(ei))return;let n=qe.randomBytes(fo),e=kd(n,ln[0]);ae.writeFileSync(ei,JSON.stringify(e,null,2),{mode:384})}function Id(n){let e=Tg(),t=qe.randomBytes(Pg),r=qe.createCipheriv(po,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:po,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function Ad(n){try{return Rg(n,Tg())}catch{throw uA(),new Error("Failed to decrypt local ciphertext")}}function pA(n,e){let t=Fe.join(e,ge.KEY_FILE_NAME),r=JSON.parse(ae.readFileSync(t,"utf8"));if(!ln.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=Fe.join(e,"keys",`${r.kekId}.bin`),o=Fe.resolve(i),s=Fe.resolve(Fe.join(e,"keys"));if(!o.startsWith(s+Fe.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=ae.readFileSync(o);if(a.length!==mo)throw new Error("Invalid external root key");let c=Ag(r,a);if(c.length!==fo)throw new Error("Invalid external data encryption key");return Rg(n,c)}function Dd(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function Je(){return process.env.DEVECO_CLI_AUTH_SOURCE===ge.AUTH_SOURCE_DEVECO_CODE}var la=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR?W():Pr.join(mA(),ge.CONFIG_DIR_NAME,ge.APP_NAME);return Pr.join(e,ge.TOKEN_FILE_NAME)}ensureConfigDir(){let e=Pr.dirname(this.getLocalTokenFilePath());ze.existsSync(e)||ze.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=er.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();ze.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return Je()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!Je())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=Pr.resolve(e);try{let r=Pr.join(t,ge.TOKEN_FILE_NAME);if(!ze.existsSync(r))return null;let i=JSON.parse(ze.readFileSync(r,"utf8"));return er.isEncryptedBlob(i)?er.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!ze.existsSync(e))return null;let t=JSON.parse(ze.readFileSync(e,"utf8"));return er.isEncryptedBlob(t)?er.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(Je()){p("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{ze.existsSync(e)&&ze.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},tr=new la;import{spawn as fA}from"child_process";function hA(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function gA(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function xg(n){if(!hA(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',gA(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=fA(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((i,o)=>{r.on("error",s=>{o(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?i():o(new Error(`Browser process exited with code ${s}`))})})}import AA from"axios";var yA={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function vA(n){try{return new URL(n)}catch{return null}}function Ng(n){var e=(typeof n=="string"?vA(n):n)||{},t=e.protocol,r=e.host,i=e.port;if(typeof r!="string"||!r||typeof t!="string"||(t=t.split(":",1)[0],r=r.replace(/:\d*$/,""),i=parseInt(i)||yA[t]||0,!wA(r,i)))return"";var o=Rd(t+"_proxy")||Rd("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function wA(n,e){var t=Rd("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(r){if(!r)return!0;var i=r.match(/^(.+):(\d+)$/),o=i?i[1]:r,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!n.endsWith(o)):n!==o}):!0}function Rd(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}import{spawn as Og}from"child_process";import*as dn from"fs";import*as _g from"os";import*as da from"path";var Fg=6e4;async function SA(){if(process.platform!=="win32")return null;let n="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Lg(n,"ProxyServer");if(!e)return null;let t=await Lg(n,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Lg(n,e){return new Promise(t=>{let r=Og("reg.exe",["query",n,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";r.stdout.on("data",o=>{i+=o.toString()}),r.on("error",()=>t(null)),r.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function bA(){let n=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!n)return null;try{return new URL(n).host}catch{return n}}function EA(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Mg(n){let e={},t=0,r="";for(let i of n.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),r=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:r,headers:e}}function PA(n,e,t,r){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((n.timeoutMs??Fg)/1e3)))];return n.method&&n.method!=="GET"&&i.push("-X",n.method),n.data!==void 0&&i.push("--data-binary",n.data),i.push(...CA(n.headers,n.data!==void 0)),r?(i.push("--dump-header",t),i.push("--output",r)):i.push("--include"),i.push(n.url),i}function CA(n,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),r=[],i=!1;for(let[o,s]of Object.entries(n??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||r.push("-H",`${o}: ${s}`)}return e&&!i&&r.push("-H","Content-Type: application/json"),r}function kA(n,e,t){if(t){let l=dn.readFileSync(e,"utf8"),d=dn.readFileSync(t),g=Mg(l);return{statusCode:g.statusCode,statusText:g.statusText,body:d.toString("base64"),headers:g.headers,bodyBuffer:d}}let r=n.lastIndexOf("HTTP/");if(r===-1)return null;let i=n.slice(r),o=i.indexOf(`\r
|
|
1305
|
-
\r
|
|
1306
|
-
`)
|
|
1307
|
-
${r}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"GET",t)}}async post(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw r}}async postAllowFailure(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}async deleteAllowFailure(e,t){try{let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw r}}async withCurlFallback(e,t,r,i){let o=await this.tryCurlFallback(e,t,r,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,r,i,o=!1){if(process.platform!=="win32"||!(e instanceof Error)||!RA(e))return null;let s,a=t;return r==="GET"?i?.params&&(a=TA(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),$g({url:a,method:r,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},L=new Td;function RA(n){if(n.response?.status===407)return!0;let e=n.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:n.code==="SELF_SIGNED_CERT_IN_CHAIN"||n.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||n.code==="CERT_HAS_EXPIRED"||n.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function TA(n,e){if(!e||typeof e!="object")return n;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let r=t.toString();if(!r)return n;let i=n.includes("?")?"&":"?";return`${n}${i}${r}`}function jg(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var rr={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},un={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},ua={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},xA={[rr.CHINA]:un.CHINA,[rr.RUSSIA]:un.RUSSIA,[rr.EUROPE]:un.EUROPE,[rr.SINGAPORE]:un.CHINA},NA={[ua.CHINA]:rr.CHINA,[ua.SINGAPORE]:rr.SINGAPORE,[ua.EUROPE]:rr.EUROPE,[ua.RUSSIA]:rr.RUSSIA};function Hg(n){return xA[n]??un.CHINA}function Ug(n){return NA[n]??rr.CHINA}var xd=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=Ug(t),c={tempToken:s,site:a,version:ge.API_VERSION,appid:o},l=`${r}/${i}`,d=await L.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!jg(g))throw new Error("Invalid jwtToken format");return g}},Bg=new xd;var Nd=class{async checkJwtToken(e,t,r=!1){let i={refresh:String(r),jwtToken:e},o=`${t}/${Q.JWT_TOKEN_CHECK_PATH}`,s=await L.get(o,{headers:i});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return L.parseJson(s)}async refreshToken(e){let t=await tr.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},i=`${t}/${Q.JWT_TOKEN_CHECK_PATH}`,o=await L.get(i,{headers:r});if(o.statusCode!==200)return null;let s=L.parseJson(o);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(r){let i=r;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}async getUserInfoFromJwt(e,t,r=!1){let i=await this.checkJwtToken(e,t,r);return!i.status||!i.userInfo||!i.userInfo.accessToken?(p("jwtToken invalid."),await tr.clearToken(),null):{userId:i.userInfo.userId??"",userName:i.userInfo.name??"",accessToken:i.userInfo.accessToken,refreshToken:i.userInfo.refreshToken??"",jwtToken:e,countryCode:i.userInfo.nationalCode,language:Hg(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await tr.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},ti=new Nd;import LA from"querystring";import{spawn as MA}from"child_process";function Wg(n){try{let e=JSON.stringify({signInfo:[{agrType:Di.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=LA.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=MA("curl",["-s","-X","POST",Di.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});r.unref(),r.stdout?.on("data",i=>{let o=i.toString().trim();o==="200"?p("Agreement sign reported successfully"):p(`Agreement sign failed: HTTP ${o}`)}).on("error",()=>{})}catch(e){p(`Agreement sign error: ${e.message}`)}}var pa=class{config;server=null;constructor(e){this.config={...Ri,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{p(`Login started, isDevecoCodeAuth: ${Je()}`);let e=this.generateClientSecret();this.server=new sa(e,Q.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),p(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),p("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(p(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new _e("Non-China accounts are not supported.");let r=await Bg.getJwtToken(t.tempToken,t.siteId,Q.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);p("JWT token received");let i=await ti.getUserInfoFromJwt(r,Q.CN_LOGIN_URL);if(!i)throw new _e("Login failed: failed to get user info");return p(`User info received: ${i.userName}`),await tr.saveJwtToken(r),p("JWT token saved"),Wg(i.accessToken),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await tr.loadJwtToken();if(!e)return!1;let r=`${Q.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(r,{timeout:5e3})}catch{p("Logout: server notification failed, local token cleared")}finally{await tr.clearToken()}return!0}async getUserInfo(e=!0){return ti.fetchUserInfo(Q.CN_LOGIN_URL,e)}generateClientSecret(){return Vg.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${Q.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await xg(i)}async refreshToken(){return ti.refreshToken(Q.CN_LOGIN_URL)}},$e=new pa;function _A(){return Je()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function FA(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var ma=class{config;constructor(e){this.config={...Ri,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await ti.fetchUserInfo(Q.CN_LOGIN_URL,!0);if(!e)throw new _e(_A());let t=await this.fetchTeamList(e.accessToken,e.userId),r=FA(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,i;try{i=await L.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:un.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new _e("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:o})}if(i.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${i.statusCode}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}},Gg=new ma;async function Cr(){return Gg.listTeams()}async function fa(n,e,t){let r=Date.now(),i=!0,o=null;try{await e()}catch(s){i=!1,o=V(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:i,error_code:o};await k.track(n,s)}}function jA(n){if(n.length===0)return kt("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
|
|
1308
|
-
`)}function HA(){return new Promise(n=>{let e=qg.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var ho=new $A("auth").description("Authentication commands (login, logout, status, team)");async function UA(n){if(n||!process.stdin.isTTY){console.log(kt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(kt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await HA()}async function BA(n){if(Je()){console.log(Ld("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:b.CommandExecuted,args:["auth","login"]};await fa(e,async()=>{let t=await $e.getUserInfo();if(t){console.log(kt(`Already logged in, User Name:${t.userName}`));return}console.log(kt("Starting login process...")),await UA(n.prompt===!1);let r=await $e.login();console.log(kt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof _e||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})}ho.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async n=>{await BA(n)});ho.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(Je()){console.log(Ld("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:b.CommandExecuted,args:["auth","logout"]};await fa(n,async()=>{let e=await $e.logout();console.log(e?kt("Logout successful"):kt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});ho.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:b.CommandExecuted,args:["auth","status"]};await fa(n,async()=>{let e=await $e.getUserInfo();if(!e){console.log(kt("Not logged in"));return}console.log(kt(`Current user: ${e.userName}`))},()=>{console.log(kt("Not logged in"))})});var WA=ho.command("team").description("Team-related commands");WA.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:b.CommandExecuted,args:["auth","team","list"]};await fa(n,async()=>{let e=await Cr();console.log(jA(e.teamList))},e=>{if(e instanceof _e){console.log(Ld(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var zg=ho;import{Command as aD}from"commander";import{green as cD,red as So,cyan as my,yellow as fy,dim as hy}from"colorette";import lD from"p-limit";import VA from"ora";var it=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=VA(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as Yg from"fs";import*as Md from"path";import{homedir as Jg}from"os";function kr(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var Kg=["DevEco"];async function ha(){let n=await L.get(lt.TAGS_API_URL),t=ga(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function GA(n){let e=[],t=lt.DEFAULT_PAGE_SIZE,r=lt.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await L.post(lt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=ga(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function Od(n){let e=new Map,t=n.map(i=>GA(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Kg.includes(o.name)))}async function qA(n,e){let t=await L.post(lt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:lt.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return ga(t,"Skills API").data.list}async function _d(n,e){let t=new Map,r=e.map(o=>qA(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Kg.includes(s.name)))}function Xg(n){kr(n);let e=[];for(let[,t]of Object.entries(wt)){let r=E.ensurePathWithinRoot(Md.join(Jg(),t.path),Md.join(Jg(),t.path,n));Yg.existsSync(r)&&e.push(t.displayName)}return e.sort()}function ga(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==lt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Zg(n){kr(n);let e=`${lt.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return ga(t,"Checksum API").data}import zA from"adm-zip";import JA from"crypto";import{timingSafeEqual as YA}from"crypto";import Fd from"fs";import pe from"path";import{fileURLToPath as KA}from"url";import{homedir as ey}from"os";import{red as XA}from"colorette";var Ee=Fd.promises;function Qg(n,e){let t=pe.resolve(e),r=pe.resolve(n),i=pe.relative(r,t);if(i.startsWith("..")||pe.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function $d(n){return pe.isAbsolute(n)?n:pe.resolve(process.cwd(),n)}function ZA(n){return JA.createHash("sha256").update(n).digest("hex")}async function QA(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=ZA(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!YA(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function ty(n){kr(n);let e=`${lt.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await Zg(n);return await QA(t,r),t}async function eD(n,e,t){kr(t);let r=new zA(n),i=r.getEntries();try{await Ee.stat(e)}catch{await Ee.mkdir(e,{recursive:!0})}let o=pe.join(e,t);Qg(e,o);for(let s of i){let a=pe.join(o,s.entryName);Qg(o,a)}r.extractAllTo(o,!0)}async function jd(n){let e=wt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(wt).join(", ")}`);let t=pe.join(ey(),e.path.replace("/skills",""));try{return await Ee.access(t),!0}catch{return!1}}function go(n){let e=wt[n];return pe.join(ey(),e.path)}function tD(n){let e=wt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(wt).join(", ")}`);return e}function Hd(n,e){let t=tD(e),r="projectPath"in t?t.projectPath:pe.join("."+e,"skills");return pe.join(n,r)}async function rD(n,e,t){kr(e);let r=pe.join(n,e);try{if(await Ee.access(r),t)await Ee.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function Ud(n,e,t){await eD(n,e,t),console.log(`Skill ${t} installed to ${pe.join(e,t)}.`)}function nD(n,e){let t=o=>{let s=pe.resolve(o);return s.startsWith("\\\\?\\")&&(s=s.slice(4)),s.replace(/[\\/]+$/,"")},r=t(n),i=t(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Bd(n,e){let t=process.platform==="win32"?"junction":"dir",r;try{r=await Ee.lstat(e)}catch{return await Ee.mkdir(pe.dirname(e),{recursive:!0}),await Ee.symlink(n,e,t),!0}if(r.isSymbolicLink()){let i;try{i=await Ee.realpath(e)}catch{return await Ee.rm(e,{force:!0}),await Ee.symlink(n,e,t),!0}return nD(i,n)?!1:(await Ee.rm(e,{force:!0}),await Ee.symlink(n,e,t),!0)}return await Ee.rm(e,{recursive:!0,force:!0}),await Ee.symlink(n,e,t),!0}async function Wd(n,e,t){let r=pe.join(e,t),i=await Bd(n,r);return i&&console.log(`Skill ${t} linked to ${n}.`),i}function ry(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(XA(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function ri(n,e,t,r,i=!1){try{let o=await e();if(i)return await t(o)===!1?{success:!0,skipped:!0}:{success:!0};let{shouldSkip:s}=await rD(o,n,r);return s?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return ry(n,o,"Installation failed")}}async function Vd(n,e){try{kr(n);let t=await e(),r=pe.join(t,n);try{await Ee.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Ee.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return ry(n,t,"Removal failed")}}async function ny(n,e,t,r=!1){return ri(n,()=>go(e),i=>Ud(t,i,n),r)}async function iy(n,e,t,r=!1){return ri(n,()=>t,i=>Ud(e,i,n),r)}async function oy(n,e,t,r,i=!1){return ri(n,()=>Hd(t,r),o=>Ud(e,o,n),i)}async function sy(n,e,t,r=!1){return ri(n,()=>go(t),i=>Wd(e,i,n),r,!0)}async function ay(n,e,t,r,i=!1){return ri(n,()=>Hd(t,r),o=>Wd(e,o,n),i,!0)}async function cy(n,e,t,r=!1){return ri(n,()=>t,i=>Wd(e,i,n),r,!0)}async function Gd(n,e){return Vd(n,()=>go(e))}async function ly(n,e){return Vd(n,()=>e)}async function dy(n,e,t){return Vd(n,()=>Hd(e,t))}function ya(){let e=pe.dirname(KA(import.meta.url));for(;;){let t=pe.join(e,"skills","deveco-cli");if(Fd.existsSync(t)&&Fd.statSync(t).isDirectory())return t;let r=pe.dirname(e);if(r===e)break;e=r}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}import qd from"fs";import zd from"path";import{cyan as iD}from"colorette";var va=qd.promises,oD="deveco-cli";async function yo(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await jd(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function ni(){let n=[];for(let e of Object.keys(wt))await jd(e)&&n.push(e);return n}async function sD(){let n=ya(),e=0,t=0,r=0,i=await ni();for(let o of i){let s=go(o),a=zd.join(s,oD);try{let c=!0;try{await va.lstat(a)}catch{c=!1}if(!c){t++;continue}await Bd(n,a)?(console.error(`Converted ${o}/deveco-cli to symlink.`),e++):t++}catch(c){r++,console.error(`Skill link migration failed for ${o}: ${c.message}`)}}if(r>0)throw new Error(`${r} agent(s) failed skill-link migration; will retry next command`);return{updated:e,skipped:t}}async function uy(){let n;try{n=zd.join(W(),"skills","migration-version")}catch{return}let e="";try{e=(await va.readFile(n,"utf-8")).trim()}catch{}let t=mt();if(e!==t)try{await sD(),await va.mkdir(zd.dirname(n),{recursive:!0}),await va.writeFile(n,t,"utf-8")}catch{}}function vo(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(iD("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Ir(n,e,t){if(!qd.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!qd.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function wo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?$d(n):void 0,resolvedProject:e?$d(e):void 0}}async function wa(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await yo(n.agent)).map(a=>({project:t,agent:a})):t?i=(await ni()).map(a=>({project:t,agent:a})):n.agent?r=await yo(n.agent):r=await ni(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}var gy="deveco";async function dD(n){let e=await ha();if(n.all)return(await Od(e)).map(r=>r.enName);{let r=(await _d(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new pn("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function uD(n,e,t,r){let i=[];if(t.customPath){let o=await iy(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await ny(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await oy(n,e,o,s,r);i.push(a)}return i}function pD(n){if(n.all&&n.skill)throw new pn("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new pn("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=wo(n.path,n.project,n.agent);return t&&Ir(t,"Project directory",n.force),e&&Ir(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function mD(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function fD(){return{agents:[gy],projectAgents:[],customPath:void 0}}async function hD(n,e,t){let r=Je()&&!mD(n,e,t)?fD():await wa(n,e,t);return{skillNames:await dD(n),targets:r}}async function gD(n,e,t,r){let i=[],o=0,s=n.length,a=lD(5),c=n.map(l=>a(()=>yD(l)));for(let l=0;l<n.length;l++){let d=n[l],g=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${g}...`);let y=await c[l];if(!y.success){r.fail(),console.log(So(`${d}: Download failed - ${y.error}`)),i.push({success:!1});continue}o+=y.buffer.length,r.stop();let I=await uD(d,y.buffer,e,t);i.push(...I)}return{results:i,diskBytes:o}}async function yD(n){try{let e=await ty(n);return{name:n,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:n,error:t,success:!1}}}async function vD(n){let e=new it;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=pD(n),{skillNames:i,targets:o}=await hD(n,t,r),{results:s,diskBytes:a}=await gD(i,o,n.force||!1,e);return e.stop(),vo(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function yy(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,i=n.filter(s=>!s.success).length,o=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>wD(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function wD(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var pn=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function SD(n){let e=n;return n instanceof pn?n.code:e.code??e.name??"UnknownError"}function ba(n,e={}){return["skills",n,...e.all?["--all"]:[],...e.long?["--long"]:[],...e.skill?["--skill"]:[],...e.force?["--force"]:[],...e.agent?["--agent",e.agent]:[],...e.project?["--project"]:[],...e.path?["--path"]:[]]}async function Ea(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=SD(a),a}finally{let a={event:b.SkillOperation,subAction:n,args:t,...s};await k.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function bD(n){return Ea("add",async()=>{let{diskBytes:e,results:t}=await vD(n);return{diskUsage:ne(e),...n.skill?{skillName:n.skill}:{},...yy(t)}},ba("add",n))}function ED(n){let{resolvedPath:e,resolvedProject:t}=wo(n.path,n.project,n.agent);return t&&Ir(t,"Project directory"),e&&Ir(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function PD(n,e){let t=new it;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=ED(e);t.stop();let o=await CD(e,n,r,i);return t.stop(),vo(o),o}catch(r){throw t.stop(),r}}function py(n,e=""){if(n.length===0)throw new pn("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Sa(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Gd(n,r.agent):await dy(n,r.project,r.agent);t.push(i)}return t}async function CD(n,e,t,r){if(t)return[await ly(e,t)];if(r&&n.agent){let a=(await yo(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Sa(e,a)}if(r){let s=await ni();py(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Sa(e,a)}if(n.agent){let a=(await yo(n.agent)).map(c=>({type:"agent",agent:c}));return Sa(e,a)}if(Je())return[await Gd(e,gy)];let i=await ni();py(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Sa(e,o)}var bo=new aD("skills").description("Manage HarmonyOS skills");bo.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await Ea("list",async()=>{let e=new it;try{e.start("Fetching skills...");let t=await ha(),r=await Od(t);if(r.length===0)return e.stop(),console.log(fy("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(my(i.enName)),console.log(hy(i.description));let o=Xg(i.enName);o.length>0&&console.log(cD(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName);return{resultTotal:r.length}}finally{e.stop()}},ba("list",n))}catch(e){console.error(So(e.message)),process.exit(1)}});bo.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await Ea("find",async()=>{let e=new it;try{e.start("Searching skills...");let t=await ha(),r=await _d(n,t);if(r.length===0)return console.log(fy(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(my(i.enName)),console.log(hy(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},ba("find"))}catch(e){console.error(So(e.message)),process.exit(1)}});bo.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async n=>{try{await bD(n)}catch(e){console.error(So(e.message)),process.exit(1)}});bo.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async n=>{try{await Ea("remove",async()=>{let e=await PD(n.skill,n);return{skillName:n.skill,...yy(e)}},ba("remove",n))}catch(e){console.error(So(e.message)),process.exit(1)}});var vy=bo;import{Command as kD,InvalidArgumentError as Pa}from"commander";import{cyan as Jd,red as Sy}from"colorette";import ID from"ora";function AD(n){return["log",...n.device?["--device"]:[],...n.crash?["--crash"]:[],...n.level?["--level"]:[],...n.bundleName?["--bundle-name"]:[],...n.keyword?["--keyword"]:[],...n.tail!==void 0?["--tail"]:[],...n.from!==void 0?["--from"]:[],...n.to!==void 0?["--to"]:[],...n.follow?["--follow"]:[]]}function DD(n){return{event:b.CommandExecuted,args:AD(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function RD(n){return n instanceof S?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function TD(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=RD(o),console.error(Sy(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(n,o).catch(()=>{})}}function xD(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new Pa("`tail` must be a positive integer.")}}function wy(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new Pa(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function ND(n){try{return E.assertHilogLevel(n),n}catch{throw new Pa("`level` must be one of: D, I, W, E, F.")}}function LD(n){try{return E.assertBundleNameStrict(n),n}catch(e){throw new Pa(e.message)}}function MD(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function OD(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function _D(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var FD=new kD("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Sy(n))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F",ND).option("--bundle-name <bundle-name>","Filter by application bundle name",LD).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",xD).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>wy(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>wy(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await TD(DD(n),()=>$D(n))});async function $D(n){let e=ID({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{MD(n);let r=n.from,i=n.to,o=await P.new(),s=new yr(o),a=await s.selectDevice(n.device);if(!a)throw new S("No active devices found.","No active devices found.");p(Jd(`deviceId: ${a}`)),p(Jd(`type: ${n.crash?"Crash logs":"Common logs"}`)),p(Jd("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await OD(s,a,n,r,i);t(),n.crash&&c&&(c=_D(c,n,r,i)),c&&console.log(c)}finally{t()}}var by=FD;import Po from"path";import nr from"fs";import Xd from"process";import xy from"os";import{Command as ZD}from"commander";import{green as Ay,red as Yd,cyan as QD,yellow as Dy}from"colorette";import fe from"fs-extra";import j from"path";import*as Cy from"os";import{fileURLToPath as jD}from"url";var Ey={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},HD=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"],ii=["phone","tablet","2in1","car","wearable","tv"],Py=["entry","src","main","module.json5"];function UD(){let n=import.meta.url,e=jD(n);if(e.includes("dist")){let o=j.dirname(e),s=j.dirname(o);return j.join(s,"templates","application")}let t=j.dirname(e),r=j.dirname(t),i=j.dirname(r);return j.join(i,"templates","application")}function ky(n,e){fe.mkdirSync(e,{recursive:!0});for(let t of fe.readdirSync(n,{withFileTypes:!0})){let r=j.join(n,t.name),i=j.join(e,t.name);if(t.isDirectory()){ky(r,i);continue}fe.existsSync(i)||(fe.mkdirSync(j.dirname(i),{recursive:!0}),fe.copyFileSync(r,i))}}function Eo(n,e){let t=fe.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&fe.writeFileSync(n,r,"utf-8")}function BD(n){if(Ey[n])return Ey[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function WD(n,e){if(e===22)return;let t=BD(e);t&&(Eo(j.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Eo(j.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Eo(j.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function VD(n){return HD.filter(t=>!fe.existsSync(j.join(n,t))).length===0}function GD(n,e){let t=Py.join("/"),r=j.join(n,...Py),i=fe.readFileSync(r,"utf-8"),o=/^([ \t]*)"deviceTypes"\s*:\s*\[[\s\S]*?\]/m.exec(i);if(!o)throw new Error(`"deviceTypes" not found in ${t}.`);let s=i.includes(`\r
|
|
1308
|
+
`,jO="6.1.0";function HO(r){let e=r.trim();if(!e)throw new Error("--target must not be empty.");return e}function UO(r){let e=r.trim();if(!NS.includes(e))throw new Error(`Invalid fold state "${r}". Available values: ${NS.join(", ")}`);return e}function MS(r,e,t,n){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${r} must be an integer in [${t}, ${n}].`);let o=Number(i);if(o<t||o>n)throw new Error(`${r} must be in [${t}, ${n}].`);return o}function OS(r,e,t,n,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${r} must be a number in [${t}, ${n}].`);if(i!==void 0&&!BO(o,i))throw new Error(`${r} supports at most ${i} decimal place(s).`);if(s<t||s>n)throw new Error(`${r} must be in [${t}, ${n}].`);return o}function BO(r,e){let t=r.split(".")[1];return t===void 0||t.length<=e}function hi(r,e,t,n,i){return Number(OS(r,e,t,n,i))}var WO=["Name","Status","Serial","Device Type","OS Version"];function VO(r){return{cells:[r.name,r.status,r.serial??"-",r.deviceType??"-",r.osVersion??"-"],highlight:r.status==="running"}}async function GO(r,e){let t=await Promise.all(e.map(async n=>{let i=await Qi(r,n,FO);return[n,i]}));return new Map(t)}async function qO(r){let e=await Nf(r),t=await GO(r,e);return{serials:e,params:t}}function zO(r,e,t,n,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function JO(r,e,t){let n=new Map,i=new Map,o=[...r],s=[...t];for(let a of r){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&zO(a,c,s,o,n)}for(let a=0;a<s.length&&a<o.length;a++)n.set(s[a],o[a]);return{productSerialMap:n,hvdSerialMap:i}}function KO(r,e,t){let n=r.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return n.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),n.map(({emu:i,serial:o,effectiveRunning:s})=>({name:i.name,status:s?"running":"stopped",serial:o??null,deviceType:i.deviceType??null,osVersion:i.osVersion??null}))}async function YO(r,e,t,n){try{let[i,o]=await Promise.all([r.listEmulators(),qO(e)]);if(i.length===0){n?.stop(),console.log(t==="json"?"[]":Sn(" No emulator instances found."));return}let s=i.filter(h=>h.isRunning).map(h=>h.name),{productSerialMap:a,hvdSerialMap:c}=JO(o.serials,o.params,s);n?.stop();let l=KO(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(VO);console.log(jr(WO,d))}catch(i){throw n?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function LS(r,e,t){let n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(o.status!=="rejected")continue;n=!0;let s=o.reason;console.error(Nm(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Im(s.stdout)),s.stderr&&console.error(Im(s.stderr))}return n}var XO=2e3,ZO=6e4;async function QO(r,e){let t=Fe(e);return(await _f(r)).some(i=>Fe(i)===t)}async function FS(r,e,t,n=ZO,i=XO){let o=Date.now()+n;for(;Date.now()<o;){if(await QO(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}function eL(r){if(!r)return null;let e=r.indexOf("-bootmode");return e>=0&&e+1<r.length&&r[e+1]==="snapshot"}async function tL(r,e,t,n){let i=await r.startEmulator(t,n);if(i.status==="already-running")return console.log(Sn(`Emulator "${t}" is already running.`)),{started:!1,memoryBytes:0,hotBoot:null};console.log(Ro(`Starting emulator "${t}"...`));let o=i.tracker,s=0,a=eL(i.args);try{let c=await FS(e,t,!0);console.log(c?ca(`Emulator "${t}" started successfully.`):Sn(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}finally{if(o)try{s=await o.stop()}catch{}}return{started:!0,memoryBytes:s,hotBoot:a}}async function rL(r,e,t,n){let i=await Promise.allSettled(t.map(a=>tL(r,e,a,n)));if(LS(i,t,"start"))throw new w("One or more emulators failed to start.");let o=i.filter(a=>a.status==="fulfilled").map(a=>a.value).filter(a=>a.started);return{emulatorMemory:o.length===0||o.some(a=>a.memoryBytes===0)?"unknown":ae(o.reduce((a,c)=>a+c.memoryBytes,0)),hotBoot:o.length===0?null:o.every(a=>a.hotBoot===!0)}}async function $S(r,e){let t=e.trim();if(!ur(t))return t;let n=await ce.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function nL(r,e,t){let n=await $S(e,t);if(console.log(Ro(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(Sn(`Emulator "${n}" is already stopped.`));return}let o=await FS(e,n,!1);console.log(o?ca(`Emulator "${n}" stopped successfully.`):Sn(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function iL(r,e,t){let n=await Promise.allSettled(t.map(i=>nL(r,e,i)));LS(n,t,"stop")}async function At(){let r=await P.new();return{manager:go.from(r),toolProvider:r}}async function Wr(r,e,t){let n={event:v.CommandExecuted,args:["emulator",t,"--target"]};await It(n,async()=>{let i=HO(r.target),o=e(),s=Array.isArray(o)?o:[o],{manager:a,toolProvider:c}=await At(),l=await $S(c.hdcPath,i);for(let d of s)await a.controlEmulator(l,d);console.log(ca(`Emulator "${i}" operation completed.`))})}function oL(r){let e=[];if(Xl(e,"longitude",r.longitude,-180,180,8),Xl(e,"latitude",r.latitude,-90,90,8),Xl(e,"altitude",r.altitude,-1e4,1e4,2),Xl(e,"bearing",r.direction,0,359.99,2,"--direction"),e.length===0)throw new Error("Specify at least one geolocation option.");return(r.longitude===void 0||r.latitude===void 0)&&console.warn(Sn("Warning: --longitude and --latitude should be specified together to form a valid location.")),e}function sL(r){let e=[];if(sa(e,"light",r.lightIntensity,0,1e5,!1,"--light-intensity"),sa(e,"humidity",r.humidity,0,100,!1),sa(e,"temperature",r.temperature,-273.1,100,!1),sa(e,"steps",r.steps,0,1e4,!0),sa(e,"heartrate",r.heartrate,0,255,!0),e.length===0)throw new Error("Specify at least one sensor option.");return e}function Xl(r,e,t,n,i,o,s=`--${e}`){t!==void 0&&r.push({type:"gps",key:e,value:OS(s,t,n,i,o)})}function sa(r,e,t,n,i,o,s=`--${e}`){if(t===void 0)return;let a=o?MS(s,t,n,i):hi(s,t,n,i,1);r.push({type:"sensor",key:e,value:a})}function aL(r){let e=[];if(r.status!==void 0){let i=r.status==="charging"?1:0;e.push({type:"battery-status",status:i})}if(r.level!==void 0&&e.push({type:"battery",level:MS("--level",r.level,0,100),assumedCharging:r.status==="charging"}),e.length===0)throw new Error("Specify --level or --status.");let t=e.some(i=>i.type==="battery"&&i.level===0),n=e.some(i=>i.type==="battery-status"&&i.status===0);if(t&&n)throw new Error("Battery level 0 is only allowed while charging; --level 0 cannot be combined with --status discharging.");return e}var Ee=new Tm("emulator").description("Manage emulator instances");Ee.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1309
|
+
${Sn("Tip: ")}${Im("An option value containing spaces/parentheses must be quoted. Use:")}
|
|
1310
|
+
${Ro('devecocli emulator <subcommand> --<option> "value with spaces"')}
|
|
1311
|
+
${Ro('devecocli emulator <subcommand> --<option>="value with spaces"')}
|
|
1312
|
+
`)}});Ee.hook("preAction",async()=>{(await P.new()).require({studio:jO})});var cL=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function _m(r){let e=new qe("--device-type <type>","Emulator device type").choices([...cL]);return r?e.makeOptionMandatory():e}function lL(){return new qe("--device-type <type>","Emulator device type (case-insensitive)").argParser(r=>{if(!r.trim())throw new xm("--device-type must not be empty.");return r}).makeOptionMandatory()}function dL(r){if(r!==void 0){if(r.length>=4&&r.length%4===0&&r.every(e=>/^\d+(?:\.\d+)?$/.test(e)))throw new Error('--screen value must be quoted: --screen "1316 2832 560 6.9".');if(r.length>2)throw new Error("--screen accepts one or two configurations.");for(let[e,t]of r.entries()){let n=t.trim().split(/\s+/),i=r.length===1?"--screen":`--screen configuration ${e+1}`;if(n.length!==4||n.some(o=>o.length===0))throw new Error(`${i} must contain four values: width(px), height(px), DPI, and screen diagonal length(inch).`);hi(`${i} width`,n[0],720,3500),hi(`${i} height`,n[1],720,3500),hi(`${i} DPI`,n[2],240,640),hi(`${i} screen diagonal length`,n[3],3.5,9)}return r}}function uL(r){return["--device-type","--os-version",...r.instancePath!==void 0?["--instance-path"]:[],...r.imageRoot!==void 0?["--image-root"]:[],...r.screenProfile!==void 0?["--screen-profile"]:[],...r.screen!==void 0?["--screen"]:[],...r.storage!==void 0?["--storage"]:[],...r.memory!==void 0?["--memory"]:[],...r.hotBoot!==void 0?["--hot-boot"]:[],...r.force?["--force"]:[]]}function ko(r,e){for(let t of e)if(t in r)return r[t]}function aa(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function _S(r){let e=aa(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var pL=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],fL="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function mL(r,e,t){if(!await r.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
|
|
1313
|
+
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function jS(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function HS(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=aa(ko(i,["osVersion","OsVersion","OSVersion","os_version"])),s=aa(ko(i,["deviceType","DeviceType","device_type"])),a=_S(ko(i,["downloaded","Downloaded","isDownloaded"])),c=aa(ko(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=aa(ko(i,["releaseType","ReleaseType","release_type"])),d=_S(ko(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function hL(r){let e=r.trim();if(!e)return!0;let t=jS(e);return t===null?!1:t.length===0?!0:HS(t,!0).length===0}function gL(r,e){let t=r.trim();if(!t)return"";let n=jS(t);if(!n)return r.trimEnd();let i=HS(n,e);return jr(pL,i)}var Zl=new Tm("image").description("HarmonyOS emulator system images (download, list, remove)");Zl.command("download").description("Download system image").addOption(_m(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let e={event:v.CommandExecuted,args:["emulator","image","download",...r.deviceType?["--device-type"]:[],...r.osVersion?["--os-version"]:[],...r.force?["--force"]:[]]};await It(e,async()=>{let{manager:t,toolProvider:n}=await At();await Dm(n.emulatorPath,n.sdkPath);let i=r.deviceType?.trim(),o=r.osVersion?.trim();if(!i)throw new w("Error: missing required option '--device-type <type>'","Missing required device type.");if(!o)throw new w("Error: misssing required option '--os-version <version>'","Missing required OS version.");await mL(t,i,o),await t.installEmulatorImage({deviceType:i,osVersion:o,force:r.force===!0})})});Zl.command("remove").description("Remove a downloaded system image").addOption(_m(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let e={event:v.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await It(e,async()=>{let{manager:t}=await At();await t.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})})});Zl.command("list").description("List system images").addOption(_m(!1)).option("--all","List all images (local and remote)").addOption(new qe("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:v.CommandExecuted,args:["emulator","image","list",...r.deviceType?["--device-type"]:[],...r.all?["--all"]:[],...r.format!=="table"?["--format"]:[]]};await It(e,async()=>{let{manager:t}=await At(),n;r.all?n=void 0:n=!0;let i=await t.listEmulatorImages({deviceType:r.deviceType,downloaded:n});if(hL(i)){console.log(Sn(fL));return}if(r.format==="json"){console.log(i.trimEnd());return}let o=gL(i,r.all===!0);console.log(o)})});Ee.addCommand(Zl);var Ql=new Tm("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Ql.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let r={event:v.CommandExecuted,args:["emulator","license","view"]};await It(r,async()=>{let{toolProvider:e}=await At(),t=await xS(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ql.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let r={event:v.CommandExecuted,args:["emulator","license","accept"]};await It(r,async()=>{let{toolProvider:e}=await At(),t=await TS(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ql.action(async()=>{let r={event:v.CommandExecuted,args:["emulator","license"]};await It(r,async()=>{let{toolProvider:e}=await At(),t=await AS(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ee.addCommand(Ql);Ee.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(r=>Wr(r,()=>({type:"shake"}),"shake"));Ee.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(r=>Wr(r,()=>({type:"power"}),"power"));Ee.command("rotate").description("Rotate emulator").addOption(new qe("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Am("<direction>").choices(["left","right"])).action((r,e)=>Wr(e,()=>({type:"rotation",direction:r}),"rotate"));Ee.command("volume").description("Change volume").addOption(new qe("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Am("<direction>").choices(["up","down"])).action((r,e)=>Wr(e,()=>({type:"volume",direction:r}),"volume"));Ee.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",$O).action((r,e)=>Wr(e,()=>({type:"folded-state",state:UO(r)}),"fold"));Ee.command("battery").description("Set battery level and/or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new qe("--status <status>","Charging status").choices(["charging","discharging"])).action(r=>Wr(r,()=>aL(r),"battery"));Ee.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(r=>Wr(r,()=>oL(r),"geolocation"));Ee.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Am("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((r,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Wr(e,()=>t[r],"scene")});Ee.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(r=>Wr(r,()=>sL(r),"sensor"));Ee.command("list").description("List all emulator instances").addOption(new qe("--details","Output the raw JSON of `Emulator -list -details` without transformation").conflicts("format")).addOption(new qe("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:v.CommandExecuted,args:["emulator","list",...r.details?["--details"]:[],...r.format!=="table"?["--format"]:[]]};await It(e,async()=>{let{manager:t,toolProvider:n}=await At();if(r.details){let o=await t.listEmulatorDetails();console.log(o.trimEnd());return}let i=r.format==="table"?LO({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await YO(t,n.hdcPath,r.format,i)})});function yL(r){let e=r.trim();if(!/^\d+$/.test(e))throw new xm("--hdcport must be an integer in [10000, 16555].");let t=Number(e);if(t<1e4||t>16555)throw new xm("--hdcport must be in [10000, 16555].");return t}function wL(r){return{hdcPort:r.hdcport,bootMode:r.bootMode,noWindow:r.window===!1}}function vL(r){return[...r.hdcport!==void 0?["--hdcport"]:[],...r.bootMode!==void 0?["--boot-mode"]:[],...r.window===!1?["--no-window"]:[]]}Ee.command("start [names...]").description("Start one or more emulator instances").addOption(new qe("--hdcport <port>","hdc port of the emulator, 10000-16555 (Emulator -hdcport)").argParser(yL)).addOption(new qe("--boot-mode <mode>","Boot mode (Emulator -bootMode): coldboot = cold start keeping user data, snapshot = hot start restoring the last snapshot (needs Quick Boot), reset = wipe data then cold start; overrides the mode chosen when the instance was created").choices(["coldboot","snapshot","reset"])).addOption(new qe("--no-window","Start the emulator without a window (Emulator -noWindow); required on Linux hosts without a GUI")).action(async(r,e)=>{let t={event:v.CommandExecuted,args:["emulator","start",...vL(e)],emulatorMemory:"unknown",hotBoot:null};await It(t,async()=>{let{manager:n,toolProvider:i}=await At();if(await Rm(i.emulatorPath,i.sdkPath),!r?.length)throw new w("Error: missing required argument 'names'","Missing required emulator name.");if(r.length>1&&e.hdcport!==void 0)throw new w(`Error: --hdcport cannot target ${r.length} emulators.`,"--hdcport sets the hdc port of a single emulator; pass one name, or omit --hdcport.");let o=await rL(n,i.hdcPath,r,wL(e));t.emulatorMemory=o.emulatorMemory,t.hotBoot=o.hotBoot})});Ee.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async r=>{let e={event:v.CommandExecuted,args:["emulator","stop"]};await It(e,async()=>{let{manager:t,toolProvider:n}=await At();if(!r?.length){console.error(Nm("Error: missing required argument 'names'")),process.exitCode=1;return}await iL(t,n.hdcPath,r)})});var bL=Ee.command("create <name>").description("Create a local emulator instance.").addOption(lL()).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').addOption(new qe("--path, --instance-path <path>","Emulator instance path")).option("--image-root <path>","Emulator image path").option("--screen-profile <model>","Emulator screen profile").addOption(new qe("--screen <config...>",'Screen: "width(px) height(px) DPI screen-diagonal-length(inch)" (720-3500, 720-3500, 240-640, 3.5-9); pass two values for a foldable device')).option("--storage <size>","Storage size in GB (2-1023)").option("--memory <size>","Memory size in GB (2-32)").addOption(new qe("--hot-boot <boolean>","Enable or disable hot boot").choices(["true","false"])).option("--force","Overwrite an existing emulator instance");bL.action(async(r,e)=>{let t={event:v.CommandExecuted,args:["emulator","create",...uL(e)]};await It(t,async()=>{if(!e.osVersion.trim())throw new Error("--os-version must not be empty.");let n={name:r,deviceType:e.deviceType,osVersion:e.osVersion,instancePath:e.instancePath,imageRoot:e.imageRoot,screenProfile:e.screenProfile,screen:dL(e.screen),storage:e.storage===void 0?void 0:hi("--storage",e.storage,2,1023),memory:e.memory===void 0?void 0:hi("--memory",e.memory,2,32),hotBoot:e.hotBoot===void 0?void 0:e.hotBoot==="true",force:e.force===!0},{manager:i}=await At();console.log(Ro(`Creating emulator "${r}"...`)),await i.createVirtualDevice(n),console.log(ca(`Emulator "${r}" created successfully.`))})});Ee.command("delete <name>").description("Delete a local emulator instance").addOption(new qe("--path, --instance-path <path>","Emulator instance path")).action(async(r,e)=>{let t={event:v.CommandExecuted,args:["emulator","delete",...e.instancePath!==void 0?["--instance-path"]:[]]};await It(t,async()=>{let{manager:n}=await At();console.log(Ro(`Deleting emulator "${r}"...`));let i=await n.deleteVirtualDevice(r,e.instancePath);console.log(ca(`Emulator "${i}" deleted successfully.`))})});var US=Ee;import{Command as FL}from"commander";import{red as Um,cyan as Yt}from"colorette";import*as lE from"readline";import*as aE from"crypto";import*as BS from"http";import*as WS from"crypto";import{URL as SL}from"url";var ed=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,n,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=n,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let n=BS.createServer((i,o)=>{this.handleRequest(i,o)});n.keepAliveTimeout=1,n.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),n.listen(0,"127.0.0.1",()=>{this.server=n;let i=n.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,n)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),n(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let n=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(n),e()})}):Promise.resolve()}handleRequest(e,t){let n=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(n.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new SL(e.url??"",`http://${n}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,n){let i="",o=0,s=65536;e.on("data",a=>{if(o+=a.length,o>s){e.destroy(new Error("Request body too large"));return}i+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,n,i)})}handleCallbackRequest(e,t,n,i){try{let o=this.parseParams(n,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),n=Buffer.from(this.clientSecret,"utf8");return t.length===n.length&&WS.timingSafeEqual(t,n)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as at from"fs";import*as En from"path";import{homedir as kL}from"os";var Vr={};aR(Vr,{LocalCrypto:()=>Vr,decryptForLocalStorage:()=>Fm,decryptForLocalStorageFromDirectory:()=>CL,encryptForLocalStorage:()=>Lm,isEncryptedBlob:()=>$m});import*as ue from"fs";import*as Je from"path";import*as st from"crypto";import*as GS from"os";import{homedir as qS}from"os";var ze=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var la=Vn.ALGORITHM,zS=Vn.IV_LENGTH,da=Vn.KEY_LENGTH,ua=Vn.KEY_LENGTH,gi=Vn.KEK_VERSIONS,td=process.env.DEVECO_CLI_DATA_DIR?j():Je.join(qS(),Se.CONFIG_DIR_NAME,Se.APP_NAME),rd=Je.join(qS(),".local","share",Se.APP_NAME,"keys"),Do=Je.join(td,Se.KEY_FILE_NAME);function VS(r){return GS.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${r}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${r}`}function Mm(r){return Je.join(rd,`${r}.bin`)}function JS(){if(!ue.existsSync(td))try{ue.mkdirSync(td,{recursive:!0,mode:448})}catch(r){throw r.code==="EACCES"?new ze(VS(td)):r}if(!ue.existsSync(rd))try{ue.mkdirSync(rd,{recursive:!0,mode:448})}catch(r){throw r.code==="EACCES"?new ze(VS(Je.dirname(rd))):r}}function KS(){JS();for(let r of gi){let e=Mm(r);ue.existsSync(e)||ue.writeFileSync(e,st.randomBytes(da),{mode:384})}}function YS(r){if(!gi.includes(r))throw new Error(`Invalid kekId: ${r}`);KS();let e=Mm(r),t=ue.readFileSync(e);if(t.length===da)return t;let n=st.randomBytes(da);return ue.writeFileSync(e,n,{mode:384}),n}function Om(r,e){let t=st.randomBytes(zS),n=YS(e),i=st.createCipheriv(la,n,t),o=Buffer.concat([i.update(r),i.final()]),s=i.getAuthTag();return{version:1,algorithm:la,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function XS(r,e){return ZS(Buffer.from(r.encryptedDek,"base64"),e,r.iv,r.authTag)}function ZS(r,e,t,n){let i=st.createDecipheriv(la,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(n,"base64")),Buffer.concat([i.update(r),i.final()])}function QS(r,e){return ZS(Buffer.from(r.ciphertext,"base64"),e,r.iv,r.authTag).toString("utf8")}function EL(){if(KS(),ue.existsSync(Do))return;let r=st.randomBytes(ua),e=Om(r,gi[0]);ue.writeFileSync(Do,JSON.stringify(e,null,2),{mode:384})}function eE(){EL();let r=JSON.parse(ue.readFileSync(Do,"utf8")),e=XS(r,YS(r.kekId));if(e.length===ua)return e;let t=st.randomBytes(ua),n=Om(t,gi[0]);return ue.writeFileSync(Do,JSON.stringify(n,null,2),{mode:384}),t}function PL(){JS();for(let t of gi){let n=Mm(t);ue.existsSync(n)||ue.writeFileSync(n,st.randomBytes(da),{mode:384})}if(ue.existsSync(Do))return;let r=st.randomBytes(ua),e=Om(r,gi[0]);ue.writeFileSync(Do,JSON.stringify(e,null,2),{mode:384})}function Lm(r){let e=eE(),t=st.randomBytes(zS),n=st.createCipheriv(la,e,t),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o=n.getAuthTag();return{version:1,algorithm:la,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function Fm(r){try{return QS(r,eE())}catch{throw PL(),new Error("Failed to decrypt local ciphertext")}}function CL(r,e){let t=Je.join(e,Se.KEY_FILE_NAME),n=JSON.parse(ue.readFileSync(t,"utf8"));if(!gi.includes(n.kekId))throw new Error(`Invalid kekId: ${n.kekId}`);let i=Je.join(e,"keys",`${n.kekId}.bin`),o=Je.resolve(i),s=Je.resolve(Je.join(e,"keys"));if(!o.startsWith(s+Je.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=ue.readFileSync(o);if(a.length!==da)throw new Error("Invalid external root key");let c=XS(n,a);if(c.length!==ua)throw new Error("Invalid external data encryption key");return QS(r,c)}function $m(r){if(!r||typeof r!="object")return!1;let e=r;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function wt(){return process.env.DEVECO_CLI_AUTH_SOURCE===Se.AUTH_SOURCE_DEVECO_CODE}var nd=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR?j():En.join(kL(),Se.CONFIG_DIR_NAME,Se.APP_NAME);return En.join(e,Se.TOKEN_FILE_NAME)}ensureConfigDir(){let e=En.dirname(this.getLocalTokenFilePath());at.existsSync(e)||at.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Vr.encryptForLocalStorage(e);this.ensureConfigDir();let n=this.getLocalTokenFilePath();at.writeFileSync(n,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return wt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!wt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=En.resolve(e);try{let n=En.join(t,Se.TOKEN_FILE_NAME);if(!at.existsSync(n))return null;let i=JSON.parse(at.readFileSync(n,"utf8"));return Vr.isEncryptedBlob(i)?Vr.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!at.existsSync(e))return null;let t=JSON.parse(at.readFileSync(e,"utf8"));return Vr.isEncryptedBlob(t)?Vr.decryptForLocalStorage(t):null}catch(t){let n=t.code;return n==="EACCES"||n==="EPERM"||n==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(wt()){f("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{at.existsSync(e)&&at.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Gr=new nd;import{spawn as RL}from"child_process";function DL(r){try{let e=new URL(r);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||r.includes('"'))}catch{return!1}}function xL(r){return r.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function tE(r){if(!DL(r))throw new Error(`Invalid URL: ${JSON.stringify(r)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',xL(r)];break;case"darwin":e="open",t=[r];break;default:e="xdg-open",t=[r];break}let n=RL(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((i,o)=>{n.on("error",s=>{o(new Error("Failed to open browser",{cause:s}))}),n.on("close",s=>{s===0?i():o(new Error(`Browser process exited with code ${s}`))})})}function rE(r){let e=r.split(".");return e.length===3&&e.every(t=>t.length>0)}var qr={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},yi={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},id={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},IL={[qr.CHINA]:yi.CHINA,[qr.RUSSIA]:yi.RUSSIA,[qr.EUROPE]:yi.EUROPE,[qr.SINGAPORE]:yi.CHINA},AL={[id.CHINA]:qr.CHINA,[id.SINGAPORE]:qr.SINGAPORE,[id.EUROPE]:qr.EUROPE,[id.RUSSIA]:qr.RUSSIA};function nE(r){return IL[r]??yi.CHINA}function iE(r){return AL[r]??qr.CHINA}var jm=class{async getJwtToken(e,t,n,i,o){let s=e.split("&")[0],a=iE(t),c={tempToken:s,site:a,version:Se.API_VERSION,appid:o},l=`${n}/${i}`,d=await $.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let h=d.data.trim();if(!rE(h))throw new Error("Invalid jwtToken format");return h}},oE=new jm;var Hm=class{async checkJwtToken(e,t,n=!1){let i={refresh:String(n),jwtToken:e},o=`${t}/${oe.JWT_TOKEN_CHECK_PATH}`,s=await $.get(o,{headers:i});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return $.parseJson(s)}async refreshToken(e){let t=await Gr.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let n={refresh:"true",jwtToken:e},i=`${t}/${oe.JWT_TOKEN_CHECK_PATH}`,o=await $.get(i,{headers:n});if(o.statusCode!==200)return null;let s=$.parseJson(o);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(n){let i=n;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}async getUserInfoFromJwt(e,t,n=!1){let i=await this.checkJwtToken(e,t,n);return!i.status||!i.userInfo||!i.userInfo.accessToken?(f("jwtToken invalid."),await Gr.clearToken(),null):{userId:i.userInfo.userId??"",userName:i.userInfo.name??"",accessToken:i.userInfo.accessToken,refreshToken:i.userInfo.refreshToken??"",jwtToken:e,countryCode:i.userInfo.nationalCode,language:nE(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let n=await Gr.loadJwtToken();return n?this.getUserInfoFromJwt(n,e,t):null}},xo=new Hm;import TL from"querystring";import{spawn as NL}from"child_process";function sE(r){try{let e=JSON.stringify({signInfo:[{agrType:rs.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=TL.stringify({nsp_svc:"as.user.sign",access_token:r,request:e}),n=NL("curl",["-s","-X","POST",rs.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});n.unref(),n.stdout?.on("data",i=>{let o=i.toString().trim();o==="200"?f("Agreement sign reported successfully"):f(`Agreement sign failed: HTTP ${o}`)}).on("error",()=>{})}catch(e){f(`Agreement sign error: ${e.message}`)}}var od=class{config;server=null;constructor(e){this.config={...ns,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{f(`Login started, isDevecoCodeAuth: ${wt()}`);let e=this.generateClientSecret();this.server=new ed(e,oe.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),f(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),f("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(f(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new ze("Non-China accounts are not supported.");let n=await oE.getJwtToken(t.tempToken,t.siteId,oe.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);f("JWT token received");let i=await xo.getUserInfoFromJwt(n,oe.CN_LOGIN_URL);if(!i)throw new ze("Login failed: failed to get user info");return f(`User info received: ${i.userName}`),await Gr.saveJwtToken(n),f("JWT token saved"),sE(i.accessToken),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await Gr.loadJwtToken();if(!e)return!1;let n=`${oe.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await $.post(n,{timeout:5e3})}catch{f("Logout: server notification failed, local token cleared")}finally{await Gr.clearToken()}return!0}async getUserInfo(e=!0){return xo.fetchUserInfo(oe.CN_LOGIN_URL,e)}generateClientSecret(){return aE.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${oe.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await tE(i)}async refreshToken(){return xo.refreshToken(oe.CN_LOGIN_URL)}},Ke=new od;function ML(){return wt()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function OL(r){if(r.length===0)return"";let e=Math.max(1,Math.floor(r.length/2));return`${r.slice(0,e)}****`}function LL(r){if(r==null||typeof r!="object")return[];let e=r;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:OL(String(t.name??"")),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var sd=class{config;constructor(e){this.config={...ns,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await xo.fetchUserInfo(oe.CN_LOGIN_URL,!0);if(!e)throw new ze(ML());let t=await this.fetchTeamList(e.accessToken,e.userId),n=LL(t);return{userId:e.userId,teamList:n}}async fetchTeamList(e,t){let n=this.config.agcTeamListUrl,i;try{i=await $.get(n,{headers:{oauth2Token:e,uid:t,source:"cli",lang:yi.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new ze("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:o})}if(i.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${i.statusCode}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}},cE=new sd;async function Pn(){return cE.listTeams()}async function ad(r,e,t){let n=Date.now(),i=!0,o=null;try{await e()}catch(s){i=!1,o=Z(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-n,success:i,error_code:o};await R.track(r,s)}}function $L(r){if(r.length===0)return Yt("No teams found for the current user.");let e=["Id","Name"],t=r.map(s=>[s.id,s.name]),n=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(n[c])).join(" "),o=n.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
|
|
1314
|
+
`)}function jL(){return new Promise(r=>{let e=lE.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),r()})})}var pa=new FL("auth").description("Authentication commands (login, logout, status, team)");async function HL(r){if(r||!process.stdin.isTTY){console.log(Yt(r?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(Yt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await jL()}async function UL(r){if(wt()){console.log(Um("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:v.CommandExecuted,args:["auth","login"]};await ad(e,async()=>{let t=await Ke.getUserInfo();if(t){console.log(Yt(`Already logged in, User Name:${t.userName}`));return}console.log(Yt("Starting login process...")),await HL(r.prompt===!1);let n=await Ke.login();console.log(Yt(`Login successful. Logged in as ${n.userName}.`))},t=>{throw t instanceof ze||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})}pa.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async r=>{await UL(r)});pa.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(wt()){console.log(Um("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let r={event:v.CommandExecuted,args:["auth","logout"]};await ad(r,async()=>{let e=await Ke.logout();console.log(e?Yt("Logout successful"):Yt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});pa.command("status").description("Show the currently logged-in user").action(async()=>{let r={event:v.CommandExecuted,args:["auth","status"]};await ad(r,async()=>{let e=await Ke.getUserInfo();if(!e){console.log(Yt("Not logged in"));return}console.log(Yt(`Current user: ${e.userName}`))},()=>{console.log(Yt("Not logged in"))})});var BL=pa.command("team").description("Team-related commands");BL.command("list").description("List team accounts the current user has joined").action(async()=>{let r={event:v.CommandExecuted,args:["auth","team","list"]};await ad(r,async()=>{let e=await Pn();console.log($L(e.teamList))},e=>{if(e instanceof ze){console.log(Um(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var dE=pa;import{Command as VL}from"commander";import{green as GL,red as fa,cyan as uE,yellow as pE,dim as fE}from"colorette";import qL from"p-limit";import WL from"ora";var vt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=WL(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};var zL="deveco";async function JL(r){let e=await us();if(r.all)return(await wc(e)).map(n=>n.enName);{let n=(await vc(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Io("errorCode",`Skill "${r.skill}" not found`);return[n.enName]}}function KL(r){if(r.all&&r.skill)throw new Io("errorCode","`--all` and `--skill` cannot be specified together.");if(!r.all&&!r.skill)throw new Io("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Vi(r.path,r.project,r.agent);return t&&Dr(t,"Project directory",r.force),e&&Dr(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}function YL(r,e,t){return!!(e||t||r.path||r.project||r.agent)}function XL(){return{agents:[zL],projectAgents:[],customPath:void 0}}async function ZL(r,e,t){let n=wt()&&!YL(r,e,t)?XL():await Gi(r,e,t);return{skillNames:await JL(r),targets:n}}async function QL(r,e,t,n){let i=[],o=0,s=r.length,a=qL(5),c=r.map(l=>a(()=>e0(l)));for(let l=0;l<r.length;l++){let d=r[l],h=s>1?` (${l+1}/${s})`:"";t.start(`Installing ${d}${h}...`);let y=await c[l];if(!y.success){t.fail(),console.log(fa(`${d}: Download failed - ${y.error}`)),i.push({success:!1});continue}o+=y.buffer.length,t.stop();let D=await new ar().installArchiveSkill(d,y.buffer,e,n);i.push(...D)}return{results:i,diskBytes:o}}async function e0(r){try{return{buffer:await Pp(r),success:!0}}catch(e){return{error:e instanceof Error?e.message:"unknown error",success:!1}}}async function t0(r){let e=new vt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=KL(r),{skillNames:i,targets:o}=await ZL(r,t,n),{results:s,diskBytes:a}=await QL(i,o,e,r.force??!1);return e.stop(),Wi(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function mE(r){let e=r.length,t=r.filter(s=>s.success&&!s.skipped).length,n=r.filter(s=>s.skipped).length,i=r.filter(s=>!s.success).length,o=[...new Set(r.filter(s=>!s.success&&typeof s.error=="string").map(s=>r0(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:n,...o.length>0?{failedErrors:o}:{}}}function r0(r){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(r.trim());return e?e[1].slice(0,32):"error"}var Io=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function n0(r){let e=r;return r instanceof Io?r.code:e.code??e.name??"UnknownError"}function cd(r,e={}){return["skills",r,...e.all?["--all"]:[],...e.long?["--long"]:[],...e.skill?["--skill"]:[],...e.force?["--force"]:[],...e.agent?["--agent",e.agent]:[],...e.project?["--project"]:[],...e.path?["--path"]:[]]}async function ld(r,e,t){let n=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=n0(a),a}finally{let a={event:v.SkillOperation,subAction:r,args:t,...s};await R.track(a,{duration_ms:Date.now()-n,success:i,error_code:o})}}function i0(r){return ld("add",async()=>{let{diskBytes:e,results:t}=await t0(r);return{diskUsage:ae(e),...r.skill?{skillName:r.skill}:{},...mE(t)}},cd("add",r))}function o0(r){let{resolvedPath:e,resolvedProject:t}=Vi(r.path,r.project,r.agent);return t&&Dr(t,"Project directory"),e&&Dr(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function s0(r,e){let t=new vt;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=o0(e);t.stop();let o=await a0(e,r,n,i);return t.stop(),Wi(o),o}catch(n){throw t.stop(),n}}async function a0(r,e,t,n){let i=r.agent||t?await Gi(r,t,n):n?{agents:[],explicitAgents:!1,projectAgents:Qe().map(o=>({project:n,agent:o}))}:{agents:Qe(),projectAgents:[]};return new ar().removeSkill(e,i)}var ma=new VL("skills").description("Manage HarmonyOS skills");ma.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{try{await ld("list",async()=>{let e=new vt;try{e.start("Fetching skills...");let t=await us(),n=await wc(t);if(n.length===0)return e.stop(),console.log(pE("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${n.length} skills`);for(let i of n){if(!r.long){console.log(i.enName);continue}console.log(uE(i.enName)),console.log(fE(i.description));let o=bp(i.enName);o.length>0&&console.log(GL(`Installed for: ${o.join(", ")}`)),console.log()}return{resultTotal:n.length}}finally{e.stop()}},cd("list",r))}catch(e){console.error(fa(e.message)),process.exitCode=1}});ma.command("find <keyword>").description("Search skills by keyword").action(async r=>{try{await ld("find",async()=>{let e=new vt;try{e.start("Searching skills...");let t=await us(),n=await vc(r,t);if(n.length===0)return console.log(pE(`No skills found matching '${r}'.`)),e.stop(),{resultTotal:0,queryLen:r.length,keyword:r};e.succeed(`Found ${n.length} skills.`);for(let i of n)console.log(uE(i.enName)),console.log(fE(i.description)),console.log();return{resultTotal:n.length,queryLen:r.length,keyword:r}}finally{e.stop()}},cd("find"))}catch(e){console.error(fa(e.message)),process.exitCode=1}});ma.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Replace existing Skill content; create missing project or custom target directories").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await i0(r)}catch(e){console.error(fa(e.message)),process.exitCode=1}});ma.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async r=>{try{await ld("remove",async()=>{let e=await s0(r.skill,r);return{skillName:r.skill,...mE(e)}},cd("remove",r))}catch(e){console.error(fa(e.message)),process.exitCode=1}});var hE=ma;import*as Sr from"fs";import{Command as BF,InvalidArgumentError as _o}from"commander";import{cyan as oh,red as QE}from"colorette";import WF from"ora";var dd=["cpp_crash","js_error","app_freeze"];function wi(r){return dd.includes(r)}var M=class extends Error{code;verdict;constructor(e,t,n){super(t),this.name="FaultLogError",this.code=e,this.verdict=n}};var c0=/^\s*#\d+\s+pc\s+[0-9a-fA-F]+\s+\S+/,l0=/^\s*at\s+\S+\s*\([^)]*\.(ets|ts|js):\d+:\d+\)/,ha=/(?:^|\n)\s*Reason\s*:([^\n]*)/,Vm=/(?:^|\n)\s*Registers\s*:/i,d0=/(?:^|\n)\s*Timestamp\s*:/i,u0=/(?:^|\n)\s*(?:Pid|Process)\s*:/i,wE=/(?:^|\n)\s*Fault thread info\s*:/i,vE=/(?:^|\n)\s*Process life time\s*:/i,Gm=/(?:^|\n)\s*Error message\s*:/i,qm=/(?:^|\n)\s*Stacktrace\s*:/i,zm=/(?:^|\n)\s*MSG\s*(?::|=)/i,ud=/\b(THREAD_BLOCK_6S|APP_INPUT_BLOCK|LIFECYCLE_TIMEOUT)\b/,p0=/(?:^|\n)\s*(?:Tid|Name)\s*:/,Bm=/\b(SIGSEGV|SIGABRT|SIGBUS|SIGILL|SIGFPE|SIGPIPE|Signal)\b/i,Wm=/\b(TypeError|SyntaxError|RangeError|ReferenceError|EvalError|URIError|Error)\b/,f0=/^\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s+/,m0=/^(-+\s+beginning\s+of\s+\w+\s+-+$|\[\s*\d+-\d+\s+\d+:\d+:\d+\.\d+\s+\d+:\d+\s+\w\/)/,h0=[[/#Basic Statistical/i,"#Basic Statistical \u7EDF\u8BA1\u6BB5"],[/#CpuFreq Usage/i,"#CpuFreq Usage \u9891\u70B9\u6BB5"],[/#ThreadInfos\s+Tid\s*:/i,"#ThreadInfos Tid \u7EBF\u7A0B\u4FE1\u606F\u5934"],[/(?:^|\n)\s*SnapshotTime\s*:/i,"SnapshotTime \u5FEB\u7167\u65F6\u95F4\u6233\u5B57\u6BB5"],[/SubmitterStacktrace/,"SubmitterStacktrace \u63D0\u4EA4\u8005\u6808\u6BB5"],[/(?:^|\n)\s*StaticsDuration\s*:/i,"StaticsDuration \u7EDF\u8BA1\u65F6\u957F\u5B57\u6BB5"]];function pd(r,e){let t=e.exec(r);return t!==null&&t[1]!==void 0&&t[1]!==""?t[1].trim():null}function g0(r){let e=0,t=[ha,Vm,d0,u0,wE,vE,Gm,qm,zm,ud];for(let n of t)n.test(r)&&(e+=1);return e>=2}function bE(r){let e=[];for(let t of r.split(`
|
|
1315
|
+
`))if(c0.test(t)&&e.push(t.trim()),e.length>=3)break;return e}function SE(r){let e=[];for(let t of r.split(`
|
|
1316
|
+
`))if(l0.test(t)&&e.push(t.trim()),e.length>=3)break;return e}function EE(r){return r.split(`
|
|
1317
|
+
`).filter(e=>p0.test(e)).length}function y0(r,e){let t=[],n=pd(r,ha);n!==null&&Bm.test(n)&&t.push(`Reason \u5B57\u6BB5\u4E3A Signal \u5F62\u6001\uFF1A${n}`),Vm.test(r)&&t.push("\u5B58\u5728 Registers \u6BB5"),wE.test(r)&&t.push("\u5B58\u5728 Fault thread info \u6BB5"),vE.test(r)&&t.push("\u5B58\u5728 Process life time \u6BB5");let i=bE(r);return i.length>0&&t.push(`Native \u6808\u5E27\u5F62\u5982 #NN pc <\u5730\u5740> <\u8DEF\u5F84>\uFF08\u547D\u4E2D ${i.length} \u5E27\uFF09`),e?n!==null&&Bm.test(n)&&t.length>=3?{type:"cpp_crash",evidence:t}:null:i.length>0?{type:"cpp_crash",evidence:t}:null}function w0(r,e){let t=[],n=pd(r,ha);n!==null&&Wm.test(n)&&t.push(`Reason \u5B57\u6BB5\u4E3A JS \u9519\u8BEF\u7C7B\u540D\uFF1A${n}`),Gm.test(r)&&t.push("\u5B58\u5728 Error message \u5B57\u6BB5"),qm.test(r)&&t.push("\u5B58\u5728 Stacktrace \u5B57\u6BB5");let i=SE(r);return i.length>0&&t.push(`JS \u6808\u5E27\u5F62\u5982 at f(path.ets:\u884C:\u5217)\uFF08\u547D\u4E2D ${i.length} \u5E27\uFF09`),e?n!==null&&Wm.test(n)&&t.length>=3?{type:"js_error",evidence:t}:null:i.length>0?{type:"js_error",evidence:t}:null}function v0(r,e){let t=[],n=ud.exec(r);n!==null&&t.push(`Reason/\u4E8B\u4EF6\u540D\u4E3A\u51BB\u5C4F\u7C7B\u578B\uFF1A${n[1]}`),zm.test(r)&&t.push("\u5B58\u5728 MSG \u5B57\u6BB5\uFF08\u627F\u8F7D\u4E3B\u7EBF\u7A0B\u961F\u5217\uFF09");let i=EE(r);return i>=2&&t.push("\u591A\u7EBF\u7A0B\u5206\u8282\u7ED3\u6784\uFF08Tid/Name \u5206\u5757\uFF09"),e?n!==null&&t.length>=3?{type:"app_freeze",evidence:t}:null:i>=2||n!==null?{type:"app_freeze",evidence:t}:null}function b0(r){return h0.filter(([e])=>e.test(r)).map(([,e])=>e)}function S0(r,e){if(r.trim()==="")return{reason:"empty",detail:"\u8F93\u5165\u4E3A\u7A7A\u6587\u4EF6\u6216\u65E0\u5185\u5BB9"};let t=r.split(`
|
|
1318
|
+
`).filter(i=>i.trim()!=="");return t.length===0?{reason:"empty",detail:"\u8F93\u5165\u4E3A\u7A7A\u6587\u4EF6\u6216\u65E0\u5185\u5BB9"}:e?null:t.filter(i=>f0.test(i)).length/t.length>.6?{reason:"hilog_stream",detail:"\u8F93\u5165\u4E3A HiLog \u6D41\u6C34\u65E5\u5FD7\uFF0C\u975E FaultLog\uFF0C\u65E0\u6CD5\u8FDB\u884C\u6545\u969C\u7C7B\u578B\u5206\u8BCA"}:m0.test(t[0])?{reason:"other_platform",detail:"\u8F93\u5165\u4E3A\u5176\u4ED6\u5E73\u53F0\u65E5\u5FD7\uFF0C\u975E\u672C\u5E73\u53F0\u6545\u969C\u65E5\u5FD7"}:null}function PE(r,e){if(e!=="cpp_crash")return null;let t=[],n=pd(r,ha)??"";if(/\bsigsegv\b/i.test(n)){let i=/0x[0-9a-fA-F]+/i.exec(n);if(i!==null){let o=Number.parseInt(i[0],16);o>0&&o<65536&&t.push(`\u5D29\u6E83\u5730\u5740 ${i[0]} \u843D\u5728\u4F4E\u5730\u5740\u533A\u95F4\uFF0C\u7591\u4F3C\u8E29\u5185\u5B58\u76EE\u6807`)}}if(/0x[a-fA-F0-9]{8}\b/i.test(r)){let i=/\b0x(61616161|deadbeef|beefbeef|00)+\b/i.exec(r);i!==null&&t.push(`\u7591\u4F3C\u586B\u5145\u6A21\u5F0F\u547D\u4E2D\uFF1A0x${i[1]}`)}return/SIGABRT/i.test(n)&&/stack|overflow|corrupt/i.test(r)&&t.push("SIGABRT \u4E14\u4E0A\u4E0B\u6587\u542B stack/corrupt \u5173\u952E\u5B57"),t.length===0?{suspected:!1,confidence:"low",evidence:["\u672A\u547D\u4E2D\u8E29\u5185\u5B58\u6B63\u5411\u7279\u5F81"]}:{suspected:!0,confidence:t.length>=2?"medium":"low",evidence:t}}function CE(r,e,t){return e?r.type==="app_freeze"?r.evidence.length>=3?"high":"medium":r.evidence.length>=4?"high":"medium":t?"medium":"low"}function E0(r,e,t){if(!t)return r==="cpp_crash"?"\u672A\u547D\u4E2D Native \u6808\u5E27\u6B63\u5411\u7279\u5F81":r==="js_error"?"\u672A\u547D\u4E2D JS \u6808\u5E27\u6B63\u5411\u7279\u5F81":"\u672A\u547D\u4E2D\u591A\u7EBF\u7A0B\u5206\u8282\u6216\u51BB\u5C4F\u4E8B\u4EF6\u540D\u6B63\u5411\u7279\u5F81";let n=pd(e,ha),i=[];return r==="cpp_crash"?(n!==null&&Bm.test(n)||i.push("Signal \u5F62\u6001\u7684 Reason"),Vm.test(e)||i.push("Registers \u6BB5"),bE(e).length===0&&i.push("Native \u6808\u5E27")):r==="js_error"?(n!==null&&Wm.test(n)||i.push("JS \u9519\u8BEF\u7C7B\u540D\u7684 Reason"),Gm.test(e)||i.push("Error message \u5B57\u6BB5"),qm.test(e)||i.push("Stacktrace \u5B57\u6BB5"),SE(e).length===0&&i.push("JS \u6808\u5E27")):(ud.test(e)||i.push("\u51BB\u5C4F\u4E8B\u4EF6\u540D"),zm.test(e)||i.push("MSG \u5B57\u6BB5"),EE(e)<2&&i.push("\u591A\u7EBF\u7A0B\u5206\u8282")),i.length>0?`\u7F3A\u5C11\uFF1A${i.join("\u3001")}`:"\u6B63\u5411\u7279\u5F81\u672A\u8FBE\u5230\u5B8C\u6574\u65E5\u5FD7\u5224\u5B9A\u9608\u503C"}function fd(r,e,t){let n=new Set(r.map(i=>i.type));return dd.filter(i=>!n.has(i)).map(i=>({type:i,reason:E0(i,t,e)}))}function gE(r,e){let t=r.find(n=>n.type===e);if(t===void 0)throw new M("INTERNAL_ERROR",`identify \u5185\u90E8\u9519\u8BEF\uFF1A\u7F3A\u5C11 ${e} \u68C0\u6D4B\u547D\u4E2D`);return t}function P0(r,e,t){let n={type:r.type,confidence:CE(r,e,!1),completeness:e?"full":"fragment",evidence:r.evidence,excluded:fd([r],e,t),candidates:[],filename_hint:""};if(r.type==="cpp_crash"&&(n.memory_corruption_suspect=PE(t,r.type)??void 0),r.type==="app_freeze"){let i=ud.exec(t);i!==null&&(n.subtype=i[1])}return n}function C0(r,e){let t=gE(r,"cpp_crash"),n=gE(r,"js_error");return{type:"cpp_crash",confidence:"medium",completeness:"fragment",evidence:t.evidence,excluded:fd([t,n],!1,e),candidates:[{type:"js_error",confidence:"low",evidence:n.evidence,arbitrable:!0}],memory_corruption_suspect:PE(e,"cpp_crash")??void 0,filename_hint:""}}function yE(r,e,t){if(r.length===1)return P0(r[0],e,t);let n=new Set(r.map(i=>i.type));return n.has("cpp_crash")&&n.has("js_error")&&!e?C0(r,t):{type:"unknown",confidence:"low",completeness:e?"full":"fragment",evidence:[],excluded:fd(r,e,t),candidates:r.map(i=>({type:i.type,confidence:CE(i,e,!1),evidence:i.evidence,arbitrable:!1})),filename_hint:""}}function k0(r){return{type:"unknown",confidence:"low",completeness:"fragment",evidence:[],excluded:[],candidates:[],filename_hint:"",out_of_scope:r}}function R0(r,e){let t=[];for(let n of[y0,w0,v0]){let i=n(r,e);i!==null&&t.push(i)}return t}function D0(r){let e=r.length>=3;return{type:"sample_stack",confidence:e?"high":"medium",completeness:e?"full":"fragment",evidence:[`\u91C7\u6837\u6808(\u589E\u5F3A\u65E5\u5FD7)\u7ED3\u6784\u6807\u8BB0\uFF1A${r.join("\u3001")}`],excluded:[{type:"cpp_crash",reason:"\u8F93\u5165\u4E3A\u91C7\u6837\u6808(\u589E\u5F3A\u65E5\u5FD7)\uFF1Anative \u5E27\u4E3A\u5468\u671F\u5FEB\u7167\uFF0C\u975E\u5D29\u6E83 faultlog"},{type:"js_error",reason:"\u8F93\u5165\u4E3A\u91C7\u6837\u6808(\u589E\u5F3A\u65E5\u5FD7)\uFF1A\u65E0 JS \u9519\u8BEF Reason / Stacktrace \u7ED3\u6784"},{type:"app_freeze",reason:"\u8F93\u5165\u4E3A\u91C7\u6837\u6808(\u589E\u5F3A\u65E5\u5FD7)\uFF1A\u65E0\u51BB\u5C4F\u4E8B\u4EF6\u540D / MSG \u5B57\u6BB5\uFF0C\u9700\u914D\u5957\u51BB\u5C4F faultlog \u5B9A\u7C7B"}],candidates:[],filename_hint:""}}function x0(r,e){return{type:"unknown",confidence:"low",completeness:r?"full":"fragment",evidence:[],excluded:fd([],r,e),candidates:[],filename_hint:""}}function md(r){let e=g0(r),t=S0(r,e);if(t!==null)return k0(t);let n=b0(r),i=R0(r,e);if(i.length>0&&e){let o=yE(i,e,r);return n.length>0&&(o.evidence=[...o.evidence,`\u540C\u65F6\u68C0\u51FA\u91C7\u6837\u6808(\u589E\u5F3A\u65E5\u5FD7)\u7ED3\u6784\u6807\u8BB0\uFF08${n.length} \u9879\uFF09\uFF0C\u53EF\u4F5C\u4E3A\u51BB\u5C4F\u5206\u6790\u914D\u5957\u8BC1\u636E`]),o}return n.length>=2?D0(n):i.length===0?x0(e,r):yE(i,e,r)}import*as hd from"fs";import*as kE from"path";var ga=20*1024*1024,RE=256*1024,DE=256*1024;function I0(r){return r.replace(/\r\n/g,`
|
|
1319
|
+
`).replace(/\r/g,`
|
|
1320
|
+
`)}function A0(r){return r.startsWith("\uFEFF")?r.slice(1):r}function Jm(r,e){let t=r.length,n;if(t<=e)n=r.toString("utf8");else{let i=Math.floor(e/2),o=r.subarray(0,i).toString("utf8"),s=r.subarray(Math.max(0,t-i)).toString("utf8");n=`${o}
|
|
1321
|
+
\u2026\uFF08\u4E2D\u6BB5\u7701\u7565\uFF09\u2026
|
|
1322
|
+
${s}`}return A0(I0(n))}function vi(r,e){let t=hd.statSync(r,{throwIfNoEntry:!1});if(t===void 0||!t.isFile())throw new M("FILE_NOT_FOUND",`Fault log not found or not a regular file: ${r}`);if(t.size>ga)throw new M("INPUT_OVERSIZED",`Fault log exceeds ${ga/1024/1024}MB limit (size=${t.size}). Provide a smaller or complete file.`);let n=hd.readFileSync(r),i=md(Jm(n,RE+DE));return i.filename_hint=e??kE.basename(r),i}function ya(r,e="pasted.log"){let t=Buffer.from(r,"utf8");if(t.length>ga)throw new M("INPUT_OVERSIZED",`Fault log content exceeds ${ga/1024/1024}MB limit (size=${t.length}). Provide a smaller or complete log.`);let n=md(Jm(t,RE+DE));return n.filename_hint=e,n}import*as xE from"fs";var T0=[/^(\d{4})[-/](\d{2})[-/](\d{2})[ \-T](\d{2}):(\d{2}):(\d{2})(?:[.:](\d{1,6}))?$/,/^(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})(?:\.(\d{1,6}))?$/,/^(\d{4})(\d{2})(\d{2})-?(\d{2})(\d{2})(\d{2})(\d{0,6})$/],N0={jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12};function Ao(r){let e=r.replace(/\r\n/g,`
|
|
1323
|
+
`).replace(/\r/g,`
|
|
1324
|
+
`);return(e.startsWith("\uFEFF")?e.slice(1):e).split(`
|
|
1325
|
+
`)}function wa(r){return Ao(xE.readFileSync(r,"utf8"))}function gd(r){return r.slice(r.lastIndexOf("/")+1)}function To(r,e,t,n=!0){let i=-1;for(let a=0;a<r.length;a++)if(e.test(r[a])){i=a;break}if(i<0)return[[],-1];let o=r.length;for(let a=i+1;a<r.length;a++)if(t.test(r[a])){o=a;break}let s=n?i:i+1;return[r.slice(s,o),i]}function bi(r,e){let t=new Map(Object.entries(e)),n={};for(let i of r){if(t.size===0)break;for(let o of[...t.keys()]){let s=t.get(o);if(s===void 0)continue;let a=s.exec(i);a!==null&&a[1]!==void 0&&a[1].trim()!==""&&(n[o]=a[1].trim(),t.delete(o))}}return n}function IE(r,e){let t=new Map([["",[]]]);for(let o of e)t.set(o,[]);let n="",i=[...e];for(let o of r){for(let s=0;s<i.length;s++)if(o.trimStart().startsWith(i[s])){n=i[s],i=i.slice(s+1);break}t.get(n)?.push(o)}return t}function AE(r,e,t,n,i,o,s){let a=new Date(r,e-1,t,n,i,o,s);return a.getFullYear()!==r||a.getMonth()!==e-1||a.getDate()!==t||a.getHours()!==n||a.getMinutes()!==i||a.getSeconds()!==o||a.getMilliseconds()!==s?null:a}function _0(r){let e=/\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})/.exec(r);if(e===null)return null;let t=N0[e[1].toLowerCase()]??0;return t===0?null:AE(Number.parseInt(e[6],10),t,Number.parseInt(e[2],10),Number.parseInt(e[3],10),Number.parseInt(e[4],10),Number.parseInt(e[5],10),0)}function No(r){if(!r)return null;let e=r.trim();for(let t of T0){let n=t.exec(e);if(n===null)continue;let i=(n[7]??"").padEnd(6,"0").slice(0,6),o=Math.floor(Number.parseInt(i,10)/1e3),s=AE(Number.parseInt(n[1],10),Number.parseInt(n[2],10),Number.parseInt(n[3],10),Number.parseInt(n[4],10),Number.parseInt(n[5],10),Number.parseInt(n[6],10),o);if(s!==null)return s}return _0(e)}function yd(r){if(r===null)return"";let e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}-${e(r.getMonth()+1)}-${e(r.getDate())} ${e(r.getHours())}:${e(r.getMinutes())}:${e(r.getSeconds())}.${String(r.getMilliseconds()).padStart(3,"0")}`}var M0=/(?<src_pid>\d+):(?<src_tid>\d+) to (?<dst_pid>\d+):(?<dst_tid>\d+) code (?<code>\S+) wait:(?<wait>[\d.]+) s(?: frz_state:(?<frz_state>\d+))?/,NE=/(?:catcher stacktrace for |Binder catcher stacktrace, type is \w+, )pid : (?<pid>\d+)/;function va(r){return{pid:r.srcPid,tid:r.srcTid}}function ba(r){return{pid:r.dstPid,tid:r.dstTid}}function Tt(r){return`${r.pid}:${r.tid}`}function Km(r,e){return r.pid===e.pid&&r.tid===e.tid}function wd(r,e,t){let n=e.get(r.pid)??"",i=t?.get(Tt(r))??"",o=[];for(let a of[n,i])a!==""&&!o.includes(a)&&o.push(a);let s=`${r.pid}:${r.tid}`;return o.length>0&&(s+=`(${o.join("/")})`),r.tid==="0"&&(s+="(binder\u7EBF\u7A0B\u8017\u5C3D,IPC FULL)"),s}function O0(r,e,t){r.trans.push({srcPid:t.groups?.src_pid??"",srcTid:t.groups?.src_tid??"",dstPid:t.groups?.dst_pid??"",dstTid:t.groups?.dst_tid??"",code:t.groups?.code??"",waitSeconds:Number.parseFloat(t.groups?.wait??"0"),frzState:t.groups?.frz_state??"",isAsync:e.trimStart().startsWith("async"),raw:e.trim()})}function _E(r){let e={trans:[],peers:new Map},[t]=To(r,/(?<!Peer)BinderCatcher --/,/end time:|^-{5,}\s*$/,!0);if(t.length===0)return e;let n=t.length;for(let i=0;i<t.length;i++){let o=t[i];if(o.includes("PeerBinder Stacktrace")||NE.test(o)){n=i;break}let s=M0.exec(o);s!==null&&O0(e,o,s)}return L0(t.slice(n),e),e}function L0(r,e){let t=[];for(let n=0;n<r.length;n++){let i=NE.exec(r[n]);i!==null&&t.push({index:n,pid:i.groups?.pid??""})}for(let n=0;n<t.length;n++){let i=t[n],o=n+1<t.length?t[n+1].index:r.length,s=r.slice(i.index,o),a=/Process name:(.*)/.exec(s.join(`
|
|
1326
|
+
`));e.peers.set(i.pid,{pid:i.pid,processName:a!==null?a[1].trim():""})}}function F0(r,e){return r.srcPid!==e.pid?!1:r.srcTid===e.tid||e.tid==="0"}function $0(r,e){return r.dstPid!==e.pid?!1:r.dstTid===e.tid||r.dstTid==="0"}function j0(r,e,t){return t?F0(r,e)?ba(r):null:$0(r,e)?va(r):null}function ME(r,e,t){let n={pid:e,tid:t},i=r.trans.filter(d=>!d.isAsync),o=[n];for(let d of i)for(let h of[va(d),ba(d)])h.pid===e&&!o.some(y=>Km(y,h))&&o.push(h);let s=TE(i,o,!0),a=TE(i,o,!1),c=J0([...s,...a]),l={faultNode:n,anchor:o,chain:null,notes:[]};return c.length>0?(l.chain={edges:z0(c),cycles:q0(c)},c.some(d=>d.dstTid==="0")&&l.notes.push("\u4F20\u64AD\u94FE\u4E2D\u5B58\u5728\u5BF9\u7AEFtid\u4E3A0\u7684\u8C03\u7528\uFF0C\u5BF9\u5E94\u8FDB\u7A0Bbinder\u7EBF\u7A0B\u8017\u5C3D\uFF08IPC FULL\uFF09")):l.notes.push("\u6545\u969C\u8FDB\u7A0B\u672A\u53C2\u4E0Ebinder\u540C\u6B65\u901A\u4FE1\uFF0C\u6545\u969C\u7EBF\u7A0B\u672A\u963B\u585E\u5728IPC\u4E0A"),l}function TE(r,e,t){let n=new Set(e.map(Tt)),i=[...e],o=[];for(;i.length>0;){let s=i.pop();if(s===void 0)break;for(let a of r){let c=j0(a,s,t);c!==null&&(o.includes(a)||o.push(a),n.has(Tt(c))||(n.add(Tt(c)),i.push(c)))}}return o}function H0(r){let e={outgoing:new Map,incoming:new Map,nodeOfKey:new Map};for(let t of r){let n=va(t),i=ba(t),o=Tt(n),s=Tt(i);e.nodeOfKey.set(o,n),e.nodeOfKey.set(s,i),e.outgoing.set(o,[...e.outgoing.get(o)??[],i]),e.incoming.set(s,[...e.incoming.get(s)??[],n])}return e}function U0(r){let e=new Set,t=[];for(let n of r.outgoing.keys()){if(e.has(n))continue;e.add(n);let i=[{key:n,next:0}];for(;i.length>0;){let o=i[i.length-1];if(o===void 0)break;let a=(r.outgoing.get(o.key)??[])[o.next];if(a===void 0){t.push(o.key),i.pop();continue}o.next+=1;let c=Tt(a);!e.has(c)&&r.outgoing.has(c)&&(e.add(c),i.push({key:c,next:0}))}}return t}function B0(r,e,t){t.add(e);let n=[e];for(let i=0;i<n.length;i++){let o=n[i];if(o!==void 0)for(let s of r.incoming.get(o)??[]){let a=Tt(s);!t.has(a)&&r.outgoing.has(a)&&(t.add(a),n.push(a))}}return n.map(i=>r.nodeOfKey.get(i)).filter(i=>i!==void 0)}function W0(r,e){let t=new Set,n=[];for(let i=e.length-1;i>=0;i--){let o=e[i];o===void 0||t.has(o)||n.push(B0(r,o,t))}return n}function V0(r,e,t){let n=[],i=r;for(;i!==void 0&&!Km(i,e);)n.push(i),i=t.get(Tt(i));return i===void 0?[]:[e,...n.reverse()]}function G0(r,e){let t=Tt(r),n=new Map,i=new Set([t]),o=[r];for(;o.length>0;){let s=o.shift();if(s===void 0)break;for(let a of e.outgoing.get(Tt(s))??[]){if(Km(a,r))return V0(s,r,n);let c=Tt(a);!i.has(c)&&e.outgoing.has(c)&&(i.add(c),n.set(c,s),o.push(a))}}return null}function q0(r){let e=H0(r),t=W0(e,U0(e)),n=[];for(let i of t){let o=i[0];if(o===void 0)continue;let s=G0(o,e);s!==null&&s.length>0&&n.push(s)}return n}function z0(r){return[...r].sort((e,t)=>t.waitSeconds-e.waitSeconds)}function J0(r){let e=[],t=new Set;for(let n of r)t.has(n.raw)||(t.add(n.raw),e.push(n));return e}var Ym=/^\s*Tid:(\d+)(?:,|\s)+Name:(.*)/,OE=/^#\d+ [\w\s]+ .*/,LE=/at\s+(\w+)\s+\((.*\.\w+):\d+:\d+\)/,K0=[[/has been crashed/,"\u76EE\u6807\u8FDB\u7A0BCrash\uFF1A\u6293\u6808\u65F6\u8FDB\u7A0B\u5DF2\u6536\u5230crash\uFF0C\u8BF7\u53C2\u8003\u9644\u8FD1\u65F6\u95F4\u70B9\u7684Crash\u65E5\u5FD7"],[/SIGDUMP error/,"\u76EE\u6807\u8FDB\u7A0B\u5728dump\u5806\u6808\u524D\u5C31\u5DF2\u7ECF\u9000\u51FA"],[/is dumping/,"\u76EE\u6807\u8FDB\u7A0B\u6B63\u5728dump\uFF0C\u77ED\u65F6\u95F4\u5185\u8FDE\u7EED\u8BF7\u6C42\uFF0C\u8BF7\u53C2\u8003\u9644\u8FD1\u65F6\u95F4\u70B9\u8BE5\u8FDB\u7A0B\u7684\u5176\u4ED6\u62A5\u9519\u65E5\u5FD7"],[/State:\tS \(sleeping\)/,"dump\u5806\u6808\u65F6\u8FDB\u7A0B\u6B63\u5728\u7761\u7720"],[/errno\(2\)/,"\u76EE\u6807\u8FDB\u7A0B\u65E0\u54CD\u5E94\u4FE1\u53F7\uFF0C\u8D85\u65F6\u540E\u5DF2\u7ECF\u9000\u51FA"],[/pid\(\d+\) process has exited/,"dump\u5806\u6808\u5931\u8D25\uFF0C\u8FDB\u7A0B\u5DF2\u7ECF\u9000\u51FA"],[/Failed to dump normal stacktrace/,"\u6B63\u5E38\u6293\u6808\u5931\u8D25"]];function Y0(r,e){let t=r.raw.replace(/^#\d+ pc \w+/,"");t=t.replace(/\([\da-fA-F]{16,}\)/g,"").trim(),r.brief=t;let n=e[3]??"";e.length>3&&(n.startsWith("/system")||n.startsWith("/vendor")||n.startsWith("/prod"))||r.raw.includes("libarkweb_engine.so")||r.raw.includes("[shmm]")?r.area="system":e.length>3&&n.startsWith("/data")&&(r.area="app")}function X0(r){r.brief=r.raw.replace(/^#\d+/,"").trim(),r.area=r.raw.includes("/foundation/arkui")?"system":"app"}function vd(r){let e=r.trim().split(/\s+/),t={raw:r,brief:"",isNative:e.length>1&&e[1]==="pc",area:"other"};return t.isNative?Y0(t,e):X0(t),t}function FE(r){let e=[];for(let t of r)(OE.test(t)||LE.test(t))&&e.push(vd(t));return e}function bd(r){let e=new Map,t=null;for(let n of r){let i=Ym.exec(n);if(i!==null){t={tid:i[1],name:i[2].trim(),frames:[]},e.set(t.tid,t);continue}t!==null&&(OE.test(n)||LE.test(n))&&t.frames.push(vd(n))}return e}function Z0(r,e){for(let[t,n]of K0)if(t.test(r)){let i=r.trim();if(!e.has(i))return e.add(i),`${i} \uFF08${n}\uFF09`}return null}function $E(r){let e=[],t=new Set;for(let n of r){let i=Z0(n,t);i!==null&&e.push(i)}return e}var Q0=/^\*{3,}\s*$/,eF=/Catche stack trace end time:|BinderCatcher --|PeerBinderCatcher|^-{5,}\s*$/,tF=/^Tid:\d+(?:,|\s)+Name:/,rF=/\s+(\d+)\s+(\d+\.\d+)%\s+\d+\.\d+%\s+\d+\.\d+%\s+\d+\s+\d+\s+(.*)/,nF={module_name:/Module name:(.*)/,reason:/Reason:(.*)/,process_name:/(?:PROCESS_NAME|Process name):(.*)/,pid:/(?:PID = |Pid:|pid=)(.*)/},iF={start_time:/start time:(.*)/,event_name:/EVENTNAME = (.*)/,timestamp:/TIMESTAMP = (.*)/,pid:/(?:PID = |Pid:|pid=)(.*)/,tid:/(?:TID = |Tid:|tid=)(.*)/,uid:/(?:UID = |Uid:|uid=)(.*)/,module_name:/MODULE_NAME = (.*)/,process_name:/(?:PROCESS_NAME = |PROCESS_NAME:)(.*)/,msg:/MSG =(.*)/,fault_time:/Fault time:(.*)/};function oF(){return{start_time:"",event_name:"",timestamp:"",pid:"",tid:"",uid:"",module_name:"",process_name:"",msg:"",fault_time:""}}function sF(r){let e=r.length;for(let n=0;n<r.length;n++)if(r[n].includes("start time:")){e=n;break}let t=bi(r.slice(0,e),nF);return{reason:t.reason??"",module_name:t.module_name??"",process_name:t.process_name??"",pid:t.pid??""}}function aF(r){let e=-1,t=-1;for(let i=0;i<r.length;i++)if(e<0&&/start time:/.test(r[i])&&(e=i),/MSG =/.test(r[i])){t=i+2;break}if(e<0||t<0)return oF();let n=bi(r.slice(e,t),iF);return{start_time:n.start_time??"",event_name:n.event_name??"",timestamp:n.timestamp??"",pid:n.pid??"",tid:n.tid??"",uid:n.uid??"",module_name:n.module_name??"",process_name:n.process_name??"",msg:n.msg??"",fault_time:n.fault_time??""}}function cF(r){let e=[];for(let t=0;t<r.length;t++)Q0.test(r[t])&&e.push(t);if(e.length>=2){let t=e[1];return[r.slice(0,t),r.slice(t)]}return[r,[]]}function jE(r){let e=aF(r),[t]=To(r,tF,eF),n=bd(t),i=$E(t);return{msg:e,stacks:n,stack_errors:i}}function lF(r){let e=new Map,[t]=To(r,/--\[cpuusage\]--/,/cpuusage end time:/);for(let n of t){let i=rF.exec(n);if(i!==null){let o=i[1],s=gd(i[3].trim());e.has(o)||e.set(o,s)}}return e}function dF(r){let[e]=To(r,/FfrtCallback:|FfrtCatcher -- start time/,/FfrtCatcher -- end time/);for(let t of e){let n=/worker tid (\d+) queue task is running, task id (\d+)/.exec(t);if(n!==null)return n[1]}return""}function uF(r){let e=new Map(r.cpuProcessNames);for(let[i,o]of r.binder.peers)o.processName!==""&&e.set(i,gd(o.processName));let t=Sd(r),n=Xm(r);return t!==""&&n!==""&&e.set(t,gd(n)),e}function Sd(r){return r.warning.msg.pid||r.header.pid}function Xm(r){return r.warning.msg.process_name||r.header.process_name||r.header.module_name}function HE(r){return r.ffrtTid!==""?r.ffrtTid:r.warning.msg.tid||Sd(r)}function UE(r){let e=r.warning.msg;return No(e.fault_time)||No(e.msg)||No(e.timestamp)}function BE(r){if(r.length===0)throw new M("FILE_NOT_FOUND","\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A");let e=sF(r),[t,n]=cF(r),i=jE(t),o=n.length>0?jE(n):null,s={reason:e.reason||i.msg.event_name,header:e,warning:i,block:o,binder:_E(r),cpuProcessNames:lF(r),ffrtTid:dF(r),processNames:new Map};return s.processNames=uF(s),s}var pF=["Fault thread info:","Registers:","Other thread info:","Memory near registers:","FaultStack:","Maps:","OpenFiles:","HiLog:"],fF={device_info:/Device info:(.*)/,build_version:/Build info:(.*)/,module_name:/Module name:(.*)/,app_version:/Version:(.*)/,is_pre_installed:/PreInstalled:(.*)/,foreground:/Foreground:(.*)/,pid:/Pid:(.*)/,uid:/Uid:(.*)/,process_name:/Process name:(.*)/,process_life_time:/Process life time:(.*)/,timestamp:/Timestamp:(.*)/,reason:/Reason:(.*)/,last_fatal_message:/LastFatalMessage:(.*)/};function mF(r){let e=-1;for(let n=0;n<r.length;n++)if(r[n].includes("*** GWP-ASan detected a memory error ***")){e=n;break}if(e<0)return"";let t=r.length;for(let n=e;n<r.length;n++)if(r[n].includes("* End GWP-ASan report *")){t=n+1;break}return r.slice(e,t).join(`
|
|
1327
|
+
`).replace(/\n+$/,"")}function WE(r){if(r.length===0)throw new M("FILE_NOT_FOUND","\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A");let e=IE(r,[...pF]),t=bi(e.get("")??[],fF),n=bd(e.get("Fault thread info:")??[]);return{header:{device_info:t.device_info??"",build_version:t.build_version??"",module_name:t.module_name??"",app_version:t.app_version??"",is_pre_installed:t.is_pre_installed??"",foreground:t.foreground??"",pid:t.pid??"",uid:t.uid??"",process_name:t.process_name??"",process_life_time:t.process_life_time??"",timestamp:t.timestamp??"",reason:t.reason??"",last_fatal_message:t.last_fatal_message??""},faultStack:n.size>0?[...n.values()][0]:null,gwpAsanText:mF(r)}}var hF={module_name:/Module name:(.*)/,process_name:/Process name:(.*)/,package_name:/Package name:(.*)/,pid:/Pid:(.*)/,uid:/Uid:(.*)/,fault_time:/Fault time:(.*)/,timestamp:/Timestamp:(.*)/,reason:/Reason:(.*)/,error_name:/Error name:(.*)/,error_message:/Error message:(.*)/,error_code:/Error code:(.*)/,page:/page:(.*)/,app_version:/Version:(.*)/,fingerprint:/Fingerprint:(.*)/},gF=/^\s*(?:#\d+\s+)?at\s+\S+\s*\(.*:\d+:\d+\)/;function VE(r){if(r.length===0)throw new M("FILE_NOT_FOUND","\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A");let e=bi(r,hF),t="",n="";for(let i of r){let o=Ym.exec(i);if(o!==null){t=o[1],n=o[2].trim();break}}return{header:{module_name:e.module_name??"",process_name:e.process_name??"",package_name:e.package_name??"",pid:e.pid??"",uid:e.uid??"",fault_time:e.fault_time??"",timestamp:e.timestamp??"",reason:e.reason??"",error_name:e.error_name??"",error_message:e.error_message??"",error_code:e.error_code??"",page:e.page??"",app_version:e.app_version??"",fingerprint:e.fingerprint??""},faultTid:t,faultThreadName:n,frames:yF(r)}}function yF(r){let e=-1;for(let n=0;n<r.length;n++)if(r[n].trim()==="Stacktrace:"){e=n;break}if(e<0)return[];let t=[];for(let n=e+1;n<r.length;n++){let i=r[n];if(i.trim()!==""){if(!gF.test(i))break;t.push(i)}}return t}function Zm(r){for(let e=0;e<r.length;e++)if(r[e].trimStart().startsWith("HiLog:"))return r.slice(e).join(`
|
|
1328
|
+
`);return""}import*as Sa from"fs";import*as Ed from"path";var GE={high:0,medium:1,low:2},qE={full:0,fragment:1},wF=/(\d{13,17})(?:\D*)$/;function vF(r){if(r.length>=14&&(r.startsWith("19")||r.startsWith("20"))){let e=Number.parseInt(r.slice(4,6),10),t=Number.parseInt(r.slice(6,8),10),n=Number.parseInt(r.slice(8,10),10),i=Number.parseInt(r.slice(10,12),10),o=Number.parseInt(r.slice(12,14),10);if(e<1||e>12||t<1||t>31||n>23||i>59||o>59)return null;let s=r.slice(14,17),a=0;s!==""&&(a=Math.round(Number.parseInt(s,10)*1e3/10**s.length));let c=new Date(Number.parseInt(r.slice(0,4),10),e-1,t,n,i,o,a);return Number.isNaN(c.getTime())||c.getDate()!==t?null:c.getTime()}if(r.length===13){let e=Number.parseInt(r,10);return Number.isNaN(e)?null:e}return null}function bF(r){let e=wF.exec(Ed.basename(r));if(e!==null){let n=vF(e[1]);if(n!==null)return n}let t=Sa.statSync(r,{throwIfNoEntry:!1});return t!==void 0?t.mtimeMs:0}function zE(r,e){let t=Sa.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=Ed.join(r,n.name);n.isDirectory()?zE(i,e):n.isFile()&&e.push(i)}}function SF(r){try{let e=vi(r);return{type:e.type,confidence:e.confidence,completeness:e.completeness}}catch{return{type:"unreadable",confidence:"low",completeness:"fragment"}}}function EF(r,e){let t=GE[r.confidence]-GE[e.confidence];if(t!==0)return t;let n=qE[r.completeness]-qE[e.completeness];return n!==0?n:r.timeMs!==e.timeMs?e.timeMs-r.timeMs:r.path.localeCompare(e.path)}function Qm(r){let e=Sa.statSync(r,{throwIfNoEntry:!1});if(e===void 0)throw new M("FILE_NOT_FOUND",`\u8DEF\u5F84\u4E0D\u5B58\u5728: ${r}`);if(e.isFile())throw new M("INVALID_INPUT",`\u9884\u671F\u4E3A\u76EE\u5F55: ${r}`);let t=[];zE(r,t);let n=[],i={};for(let o of t){let s=SF(o);i[s.type]=(i[s.type]??0)+1,wi(s.type)&&n.push({path:o,type:s.type,confidence:s.confidence,completeness:s.completeness,timeMs:bF(o)})}return n.sort(EF),{candidates:n,typeCounts:i}}function JE(r){if(!wi(r.type)){let e=r.out_of_scope!==void 0?`\uFF08${r.out_of_scope.detail}\uFF09`:"";throw new M("UNRECOGNIZED_LOG",`\u65E0\u6CD5\u89E3\u6790\u8BE5\u65E5\u5FD7\uFF1A\u8BC6\u522B\u4E3A ${r.type}\uFF0C\u4EC5\u652F\u6301 cpp_crash / js_error / app_freeze${e}`,r)}return r.type}function Pd(r){if(r.path!==void 0){let e=vi(r.path),t=JE(e),n=wa(r.path);return KE(t,e,n,{kind:"file",path:r.path})}if(r.content!==void 0){let e=ya(r.content),t=JE(e),n=Ao(r.content);return KE(t,e,n,{kind:"file",path:e.filename_hint})}throw new M("INVALID_INPUT","\u5FC5\u987B\u63D0\u4F9B\u65E5\u5FD7\u6587\u4EF6\u8DEF\u5F84\u6216\u65E5\u5FD7\u5185\u5BB9")}function eh(r){let{candidates:e,typeCounts:t}=Qm(r);if(e.length===0){let a=Object.entries(t).map(([c,l])=>`${c}=${l}`).join(", ");throw new M("UNRECOGNIZED_LOG",`\u672A\u5728 ${r} \u4E2D\u627E\u5230\u53EF\u5206\u6790\u7684\u6545\u969C\u65E5\u5FD7\uFF08\u652F\u6301 cpp_crash / js_error / app_freeze\uFF09`+(a!==""?`\uFF1B\u626B\u63CF\u6587\u4EF6\u5224\u5B9A\u5206\u5E03\uFF1A${a}`:""))}let n=e[0],i=Pd({path:n.path}),o=e.map(a=>({path:a.path,type:a.type,confidence:a.confidence,completeness:a.completeness})),s={kind:"directory",path:r,candidates:o};return i.source=s,i}function th(r){if(r.path!==void 0){let e=Zm(wa(r.path));if(e==="")throw new M("INVALID_INPUT","\u65E5\u5FD7\u4E2D\u672A\u627E\u5230 HiLog \u533A\u6BB5");return e}if(r.content!==void 0){let e=Zm(Ao(r.content));if(e==="")throw new M("INVALID_INPUT","\u65E5\u5FD7\u4E2D\u672A\u627E\u5230 HiLog \u533A\u6BB5");return e}throw new M("INVALID_INPUT","\u5FC5\u987B\u63D0\u4F9B\u65E5\u5FD7\u6587\u4EF6\u8DEF\u5F84\u6216\u65E5\u5FD7\u5185\u5BB9")}function KE(r,e,t,n){let i;return r==="app_freeze"?i=kF(BE(t)):r==="cpp_crash"?i=RF(WE(t)):i=DF(VE(t)),{schemaVersion:"1.0.0",logType:r,...e.subtype!==void 0?{subtype:e.subtype}:{},source:n,identify:e,"key-report":i}}function PF(r,e,t){let n=r.frzState!==""?{"frz-state":r.frzState}:{};return{from:wd(va(r),e,t),to:wd(ba(r),e,t),relation:"\u540C\u6B65\u7B49\u5F85","wait-seconds":r.waitSeconds,code:r.code,...n}}function CF(r,e){let t=new Map,n=r.block!==null?[r.warning,r.block]:[r.warning];for(let i of n)for(let[o,s]of i.stacks)s.name!==""&&t.set(`${e}:${o}`,s.name);return t}function YE(r,e,t,n){let i=t!==null?t.frames.map(s=>s.raw):[],o={role:r,tid:e,name:t!==null?t.name:"",frames:i};return i.length===0&&(o.note=n.length>0?n.join("\uFF1B"):"\u672A\u6293\u5230\u8BE5\u7EBF\u7A0B\u5806\u6808"),o}function kF(r){let e=Sd(r),t=Xm(r),n=HE(r),i=UE(r),o={\u6545\u969C\u65F6\u95F4:i!==null?yd(i):r.warning.msg.fault_time||r.warning.msg.timestamp,PID:e,\u8FDB\u7A0B\u540D:t,\u6545\u969C\u7C7B\u578B:"appfreeze",...r.reason!==""?{\u6545\u969C\u539F\u56E0:r.reason}:{}},s=[YE("fault",n,r.warning.stacks.get(n)??null,r.warning.stack_errors)];r.block!==null&&s.push(YE("fault-secondary",n,r.block.stacks.get(n)??null,r.block.stack_errors));let a=ME(r.binder,e,n),c=CF(r,e),l={"basic-info":o,threads:s,binders:a.chain!==null?a.chain.edges.map(d=>PF(d,r.processNames,c)):[]};return a.notes.length>0&&(l["binder-notes"]=a.notes),a.chain!==null&&a.chain.cycles.length>0&&(l.cycles=a.chain.cycles.map(d=>{let h=d.map(y=>wd(y,r.processNames,c));return`${h.join(" -> ")} -> ${h[0]}`})),l}function RF(r){let e={\u6545\u969C\u65F6\u95F4:r.header.timestamp,PID:r.header.pid,\u8FDB\u7A0B\u540D:r.header.process_name||r.header.module_name,\u6545\u969C\u7C7B\u578B:"cppcrash",...r.header.reason!==""?{\u6545\u969C\u539F\u56E0:r.header.reason}:{},...r.header.last_fatal_message!==""?{LastFatalMessage:r.header.last_fatal_message}:{}},t=r.faultStack,n={"basic-info":e,threads:[{role:"fault",tid:t!==null?t.tid:"",name:t!==null?t.name:"",frames:t!==null?t.frames.map(i=>i.raw):[],...t===null||t.frames.length===0?{note:"\u672A\u89E3\u6790\u5230\u5D29\u6E83\u7EBF\u7A0B\u5806\u6808"}:{}}],binders:[]};return r.gwpAsanText!==""&&(n["gwp-asan"]=r.gwpAsanText),n}function DF(r){return{"basic-info":{\u6545\u969C\u65F6\u95F4:r.header.fault_time||r.header.timestamp,PID:r.header.pid,\u8FDB\u7A0B\u540D:r.header.process_name||r.header.package_name||r.header.module_name,\u6545\u969C\u7C7B\u578B:"jserror",...r.header.reason!==""||r.header.error_name!==""?{\u6545\u969C\u539F\u56E0:r.header.reason||r.header.error_name}:{},...r.header.error_message!==""?{\u9519\u8BEF\u4FE1\u606F:r.header.error_message}:{}},threads:[{role:"fault",tid:r.faultTid,name:r.faultThreadName,frames:r.frames,...r.frames.length===0?{note:"\u672A\u89E3\u6790\u5230 Stacktrace \u5E27"}:{}}],binders:[]}}function rh(r){let e=r["key-report"],t=["=".repeat(60)];t.push("\u3010\u57FA\u672C\u4FE1\u606F\u3011"),t.push(...xF(e["basic-info"]));for(let n of e.threads)t.push(...IF(n.role==="fault"?"\u6545\u969C\u7EBF\u7A0B\u5806\u6808":"\u6545\u969C\u7EBF\u7A0B\u5806\u6808\uFF08\u4E8C\u6B21\u6293\u6808\uFF09",n));return t.push(...AF(e)),e["gwp-asan"]!==void 0&&e["gwp-asan"]!==""&&(t.push("\u3010GWP-ASan \u539F\u59CB\u62A5\u544A\u3011"),t.push(e["gwp-asan"])),t.join(`
|
|
1329
|
+
`)}function xF(r){let e=[],t=r.\u8FDB\u7A0B\u540D??"";for(let[n,i]of Object.entries(r))if(n!=="\u8FDB\u7A0B\u540D"){if(n==="PID"){i!==""&&t!==""?e.push(`PID\uFF1A${i} \u8FDB\u7A0B\u540D\uFF1A${t}`):i!==""?e.push(`PID\uFF1A${i}`):t!==""&&e.push(`\u8FDB\u7A0B\u540D\uFF1A${t}`);continue}i!==""&&e.push(`${n}\uFF1A${i}`)}return e}function IF(r,e){let t=[`\u3010${r}\u3011`];return(e.tid!==""||e.name!=="")&&t.push(`Tid:${e.tid}, Name:${e.name}`),e.frames.forEach((n,i)=>{/^\s*#\d+/.test(n)?t.push(`#${String(i).padStart(2,"0")} ${vd(n).brief}`):t.push(n.trim())}),e.frames.length===0&&e.note===void 0&&t.push("\u672A\u83B7\u53D6\u5230\u8BE5\u7EBF\u7A0B\u5806\u6808"),e.note!==void 0&&t.push(`\u8BF4\u660E\uFF1A${e.note}`),t}function AF(r){let e=r["binder-notes"]??[];if(r.binders.length===0&&e.length===0)return[];let t=["\u3010binder \u4F20\u64AD\u94FE\u3011"];if(r.binders.length>0){t.push("\u4F20\u64AD\u94FE\u8C03\u7528\u8FB9\uFF08\u6309\u7B49\u5F85\u65F6\u957F\u964D\u5E8F\uFF09\uFF1A");for(let n of r.binders){let i=n["frz-state"]!==void 0?` frz_state:${n["frz-state"]}`:"";t.push(` ${n.from} -> ${n.to} ${n.relation} ${n["wait-seconds"].toFixed(2)}s${i}`)}}for(let n of r.cycles??[])t.push(`\u26A0 \u68C0\u6D4B\u5230binder\u6B7B\u9501\u73AF\uFF1A${n}`);for(let n of e)t.push(`\u63D0\u793A\uFF1A${n}`);return t}var TF="#Basic Statistical",NF="#CpuFreq Usage",_F="#ThreadInfos Tid:",MF=/^StaticsDuration:\s+(\d+)\s+ms/,OF=/^CpuTime:\s+(\d+)\s+ms/,LF=/^cpu(\d+) Usage (\d+.\d+)%/;function nh(r,e){let t,n,i;if(r.path!==void 0)t=vi(r.path),n=wa(r.path),i=r.path;else if(r.content!==void 0)t=ya(r.content),n=Ao(r.content),i=t.filename_hint;else throw new M("INVALID_INPUT","\u5FC5\u987B\u63D0\u4F9B\u91C7\u6837\u6808\u6587\u4EF6\u8DEF\u5F84\u6216\u91C7\u6837\u6808\u5185\u5BB9");if(t.type!=="sample_stack")throw new M("INVALID_INPUT",`\u8BE5\u65E5\u5FD7\u4E0D\u662F\u91C7\u6837\u6808\u6587\u4EF6\uFF08\u5224\u5B9A\u4E3A ${t.type}\uFF09\uFF0C--stack \u4EC5\u652F\u6301\u91C7\u6837\u6808\u65E5\u5FD7`);let o=$F(n);return{schemaVersion:"1.0.0",logType:"sample_stack",source:{kind:"file",path:i},identify:t,summary:FF(n,o.size),hotspots:HF(o,e)}}function XE(r){let e=-1,t=-1,n=-1;for(let i=0;i<r.length;i++){let o=r[i];o.includes(TF)&&(e=i),o.includes(NF)&&(t=i),o.includes(_F)&&(n=i)}return[e,t,n]}function FF(r,e){let[t,n,i]=XE(r),o=0,s=0;if(t>=0){let c=n>=0?n:r.length;for(let l of r.slice(t,c)){let d=MF.exec(l);d!==null&&(o=Number.parseInt(d[1],10));let h=OF.exec(l);h!==null&&(s=Number.parseInt(h[1],10))}}let a={};if(n>=0){let c=i>=0?i:r.length;for(let l of r.slice(n,c)){let d=LF.exec(l);d!==null&&(a[d[1]]=Number.parseFloat(d[2]))}}return{"statics-duration-ms":o,"cpu-time-ms":s,"cpu-usage":a,"snapshot-count":e}}function $F(r){let[,,e]=XE(r),t=e>=0?r.slice(e):[],n=[],i=[],o=-1;for(let a=0;a<t.length;a++){let c=t[a];if(c.includes("Timestamp:")||c.includes("SnapshotTime:")){n.push(a),i.push(No(c.slice(c.indexOf(":")+1).trim()));continue}o<0&&c.includes("SubmitterStacktrace")&&(o=a)}let s=new Map;for(let a=0;a<n.length;a++){let c=i[a];if(c==null)continue;let l=n[a]+1,d=a+1<n.length?n[a+1]:o>=0?o:t.length;s.set(c.getTime(),{date:c,frames:FE(t.slice(l,d))})}return s}function jF(r){let e=[];for(let t=r.frames.length-1;t>=0;t--){let n=r.frames[t];n.area!=="system"&&(n.brief.includes("anonymous")||e.push(n.brief))}return e.length>0?e:null}function HF(r,e){let t=new Map,n=new Map,i=[...r.keys()].sort((s,a)=>s-a);for(let s of i){let a=r.get(s);if(a===void 0)continue;let c=jF(a);if(c===null)continue;let l=c[0],d=t.get(l);d===void 0?t.set(l,[a.date]):d.push(a.date),n.set(s,c)}let o=[...t.entries()].sort((s,a)=>a[1].length-s[1].length).map(([s,a])=>({"parent-node":s,count:a.length,"total-snapshots":r.size,chains:a.sort((c,l)=>c.getTime()-l.getTime()).map(c=>({timestamp:yd(c),calls:n.get(c.getTime())??[]}))}));return e!==void 0?o.slice(0,e):o}function ih(r){let e=r.summary,t=["=".repeat(24),"\u91C7\u6837\u6808\u5206\u6790\u62A5\u544A","=".repeat(24),"\u3010\u57FA\u672C\u4FE1\u606F\u3011",`StaticsDuration: ${e["statics-duration-ms"]}ms`,`CpuTime: ${e["cpu-time-ms"]}ms`],n=Object.entries(e["cpu-usage"]);if(n.length===0)t.push("CPU\u4F7F\u7528\u7387: \u672A\u83B7\u53D6\u5230");else{t.push("CPU\u4F7F\u7528\u7387:");for(let[i,o]of n)t.push(` CPU${i}: ${o}%`)}return t.push(`\u5FEB\u7167\u603B\u6570: ${e["snapshot-count"]}`),t.push("\u3010\u7236\u8282\u70B9\u7EDF\u8BA1\u3011"),r.hotspots.length===0?t.push("\u672A\u89E3\u6790\u5230\u4E1A\u52A1\u5E27\u70ED\u70B9"):UF(t,r.hotspots),t.join(`
|
|
1330
|
+
`)}function UF(r,e){let t=Math.max(...e.map(n=>n["parent-node"].length))+2;e.forEach((n,i)=>{i>0&&r.push("");let o=n.count*100/n["total-snapshots"],s=Number.isInteger(o)?`${o}%`:`${o.toFixed(1)}%`;r.push(`${n["parent-node"].padEnd(t)}\u51FA\u73B0\u6B21\u6570: ${n.count}/${n["total-snapshots"]} \u5360\u6BD4: ${s}`),r.push(" \u8C03\u7528\u94FE:"),n.chains.forEach((a,c)=>{r.push(` [\u5FEB\u7167${c+1}] ${a.calls.join(" -> ")}`)})})}var VF=new Set(["default","json","report"]),GF=new Set(["default","json","report","hilog"]),qF=20;function zF(r){return["log",...r.device?["--device"]:[],...r.crash?["--crash"]:[],...r.stack?["--stack"]:[],...r.path?["--path"]:[],...r.format?["--format"]:[],...r.limit!==void 0?["--limit"]:[],...r.level?["--level"]:[],...r.bundleName?["--bundle-name"]:[],...r.keyword?["--keyword"]:[],...r.tail!==void 0?["--tail"]:[],...r.from!==void 0?["--from"]:[],...r.to!==void 0?["--to"]:[],...r.follow?["--follow"]:[]]}function JF(r){return{event:v.CommandExecuted,args:zF(r),operation:r.path!==void 0?"local_identify":r.crash?"faultlogger_report":"hilog",logType:r.stack?"stack":r.crash?"crash":"common",bundleName:r.bundleName??"ALL"}}function KF(r){return r instanceof w?r.traceMessage:r instanceof Error?r.code??r.name:"UnknownError"}function YF(r){return r.out_of_scope!==void 0?"out_of_scope":r.type==="unknown"?r.candidates.length>0?"ambiguous":"unknown":"identified"}function XF(r){let e=r.source;return("candidates"in e?e.candidates?.[0]?.path:void 0)??e.path}function ZF(r){try{let t=Sr.openSync(r,"r");try{let n=Buffer.alloc(2048),i=Sr.readSync(t,n,0,2048,0),o=/(?:^|\n)\s*Module name:\s*([^\r\n]+)/.exec(n.toString("utf-8",0,i)),s=o!==null?o[1].trim():"";return s!==""?s:void 0}finally{Sr.closeSync(t)}}catch{return}}function QF(r){return r.replace(/[^\s:,,]*[\\/][^\s]*/g,e=>{if(e==="/"||e==="\\")return e;let t=e.slice(e.lastIndexOf(".")+1);return/^[A-Za-z0-9]{1,10}$/.test(t)?`***.${t}`:"***"})}function e$(r,e,t){let n=t?.verdict??e?.identify;if(n===void 0)return r;let i=YF(n);if(wi(n.type)?r.faultType=n.type:i!=="identified"&&(r.faultType=i),e!==void 0){let o=ZF(XF(e));o!==void 0&&(r.bundleName=o)}return r}async function t$(r,e){let t=Date.now(),n=!0,i=null,o,s,a;try{s=await e()}catch(c){n=!1,i=KF(c),o=c.message,c instanceof M&&(a=c),console.error(QE(c.message)),process.exitCode=1}finally{e$(r,s,a),r.errorMessage=o===void 0?void 0:QF(o);let c={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(r,c).catch(()=>{})}}function r$(r){try{return E.parsePositiveInteger(r,"tail")}catch{throw new _o("`tail` must be a positive integer.")}}function n$(r){try{return E.parsePositiveInteger(r,"limit")}catch{throw new _o("`limit` must be a positive integer.")}}function i$(r){if(!GF.has(r))throw new _o("`--format` must be one of: default, json, report, hilog.");return r}function ZE(r,e){try{return E.parseDurationToSeconds(r,e)}catch{throw new _o(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function o$(r){try{return E.assertHilogLevel(r),r}catch{throw new _o("`level` must be one of: D, I, W, E, F.")}}function s$(r){try{return E.assertBundleNameStrict(r),r}catch(e){throw new _o(e.message)}}function a$(r){if(r.to&&r.follow)throw new M("INVALID_ARGUMENTS","`--to` cannot be used with `--follow`.")}function c$(r){if(r.stack===!0&&r.crash===!0)throw new M("INVALID_ARGUMENTS","`--stack` cannot be used with `--crash`.");if(r.stack===!0&&r.path===void 0)throw new M("INVALID_ARGUMENTS","`--stack` requires a local sample stack file (use --path).");if(r.path!==void 0&&r.crash!==!0&&r.stack!==!0)throw new M("INVALID_ARGUMENTS","`--path` requires `--crash` or `--stack`.");if(r.limit!==void 0&&r.stack!==!0)throw new M("INVALID_ARGUMENTS","`--limit` is only valid with `--stack`.");if(r.format!==void 0){if(r.crash!==!0&&r.stack!==!0)throw new M("INVALID_ARGUMENTS","`--format` is only valid with `--crash` or `--stack`.");if(r.path===void 0)throw new M("INVALID_ARGUMENTS","`--format` requires a local fault log (use --path).");if(r.stack===!0&&!VF.has(r.format))throw new M("INVALID_ARGUMENTS","`--format` must be one of: default, json, report.")}}function l$(r){let e=[];if(r.device!==void 0&&e.push("--device"),r.level!==void 0&&e.push("--level"),r.bundleName!==void 0&&e.push("--bundle-name"),r.keyword!==void 0&&e.push("--keyword"),r.follow===!0&&e.push("--follow"),r.tail!==void 0&&e.push("--tail"),r.from!==void 0&&e.push("--from"),r.to!==void 0&&e.push("--to"),e.length>0)throw new M("INVALID_ARGUMENTS",`\`--path\` cannot be combined with device log options: ${e.join(", ")}.`)}function eP(r){if(!Sr.existsSync(r))throw new M("FILE_NOT_FOUND",`\u8DEF\u5F84\u4E0D\u5B58\u5728\uFF1A${r}`);return Sr.statSync(r).isDirectory()?"directory":"file"}function tP(r){console.log(JSON.stringify(r,null,2))}function d$(r,e,t){if(eP(r)!=="file")throw new M("INVALID_INPUT",`\u91C7\u6837\u6808\u5206\u6790\u4EC5\u652F\u6301\u6587\u4EF6\u8DEF\u5F84\uFF0C\u6536\u5230\u76EE\u5F55\uFF1A${r}`);let i=nh({path:r},t);if(e==="json")return tP(i),i;let o=ih(i);return e==="report"?(console.log(o),i):(console.log(`\u5206\u6790\u6587\u4EF6\uFF1A${r}`),console.log(o),i)}function u$(r,e){let t=eP(r),n=t==="directory"?eh(r):Pd({path:r}),i=t==="directory"?n.source.candidates?.[0]?.path??r:r;if(e==="hilog")return console.log(th({path:i})),n;if(e==="json")return tP(n),n;let o=rh(n);return e==="report"?(console.log(o),n):(t==="directory"?(console.log(`\u5206\u6790\u76EE\u5F55\uFF1A${r}`),console.log(`\u9009\u4E2D\u65E5\u5FD7\uFF1A${i}`)):console.log(`\u5206\u6790\u6587\u4EF6\uFF1A${r}`),console.log(o),n)}function p$(r){l$(r);let e=r.path??"",t=r.format??"default";return r.stack===!0?d$(e,t,r.limit??qF):u$(e,t)}async function f$(r,e,t,n,i){return t.crash?await r.getCrashLog(e,t.bundleName):await r.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:n,toSeconds:i})}function m$(r,e,t,n){let i=E.filterLogsByRelativeWindow(r,t,n);return e.tail?E.getLastLines(i,e.tail):i}var h$=new BF("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(QE(r))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--stack","Analyze a local sample stack file (requires --path)").option("--path <path>","Local fault log file or directory to analyze (requires --crash or --stack)").option("--format <format>","Output format: default, json, report (plus hilog with --crash)",i$).option("--limit <num>","Max hotspots shown by --stack",n$).option("--level <level>","Log level filter: D, I, W, E, F",o$).option("--bundle-name <bundle-name>","Filter by application bundle name",s$).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",r$).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>ZE(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>ZE(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await t$(JF(r),()=>g$(r))});async function g$(r){if(c$(r),r.stack===!0||r.path!==void 0)return p$(r);await y$(r)}async function y$(r){let e=WF({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{a$(r);let n=r.from,i=r.to,o=await P.new(),s=new dn(o),a=await s.selectDevice(r.device);if(!a)throw new w("No active devices found.","No active devices found.");f(oh(`deviceId: ${a}`)),f(oh(`type: ${r.crash?"Crash logs":"Common logs"}`)),f(oh("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await f$(s,a,r,n,i);t(),r.crash&&c&&(c=m$(c,r,n,i)),c&&console.log(c)}finally{t()}}var rP=h$;import Pa from"path";import zr from"fs";import ch from"process";import pP from"os";import{Command as T$}from"commander";import{green as cP,red as sh,cyan as N$,yellow as lP}from"colorette";import ve from"fs-extra";import J from"path";import*as oP from"os";import{fileURLToPath as w$}from"url";var nP={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},v$=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"],Mo=["phone","tablet","2in1","car","wearable","tv"],iP=["entry","src","main","module.json5"];function b$(){let r=import.meta.url,e=w$(r);if(e.includes("dist")){let o=J.dirname(e),s=J.dirname(o);return J.join(s,"templates","application")}let t=J.dirname(e),n=J.dirname(t),i=J.dirname(n);return J.join(i,"templates","application")}function sP(r,e){ve.mkdirSync(e,{recursive:!0});for(let t of ve.readdirSync(r,{withFileTypes:!0})){let n=J.join(r,t.name),i=J.join(e,t.name);if(t.isDirectory()){sP(n,i);continue}ve.existsSync(i)||(ve.mkdirSync(J.dirname(i),{recursive:!0}),ve.copyFileSync(n,i))}}function Ea(r,e){let t=ve.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&ve.writeFileSync(r,n,"utf-8")}function S$(r){if(nP[r])return nP[r];if(r>=26){let e=`${r}.0.0`;return{sdkVersion:e,modelVersion:e}}}function E$(r,e){if(e===22)return;let t=S$(e);t&&(Ea(J.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Ea(J.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Ea(J.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function P$(r){return v$.filter(t=>!ve.existsSync(J.join(r,t))).length===0}function C$(r,e){let t=iP.join("/"),n=J.join(r,...iP),i=ve.readFileSync(n,"utf-8"),o=/^([ \t]*)"deviceTypes"\s*:\s*\[[\s\S]*?\]/m.exec(i);if(!o)throw new Error(`"deviceTypes" not found in ${t}.`);let s=i.includes(`\r
|
|
1309
1331
|
`)?`\r
|
|
1310
1332
|
`:`
|
|
1311
|
-
`,a=o[1],c=e.map((d,
|
|
1312
|
-
`+
|
|
1313
|
-
Failed to create project.`)),console.error(
|
|
1314
|
-
`)){let s=o.indexOf(
|
|
1315
|
-
`);return/not ready|not initialized|initializing|please retry|retry \d+s|syncing|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|no project path/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|Must specify|cannot be used together|invalid/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/does not exist|not exist|not found|No valid|not a .ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function
|
|
1316
|
-
\r
|
|
1317
|
-
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let
|
|
1318
|
-
\r
|
|
1319
|
-
`);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){u.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10);if(!Number.isFinite(s)||s<0||s>OR){u.warn(`[LspClient] Invalid Content-Length: ${o[1]}, drop until next packet`),this.buffer=this.buffer.slice(r+4);continue}let a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){u.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.logSocketRecv(d.json),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.logSocketRecv(l),this.emit("message",l),this.buffer=this.buffer.slice(c)}}logSocketRecv(t){this.socket&&u.debug(`[LspClient] [SOCKET RECV] ${t.slice(0,200)}`)}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){if(this.isClosing=!0,this.socket){this.socket.destroy(),this.socket=null,this.process=null;return}let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Dr=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){u.debug(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)try{i(t,r)}finally{this.callbacks.delete(e)}else{let o=[...this.callbacks.keys()].map(s=>String(s));u.debug(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{u.debug(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{i()}finally{this.timeouts.delete(e)}},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var Ra=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var ai=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function T(n){return typeof n=="object"&&n!==null}var Qy=20*1e3,BR=30*1e3,ev=300,WR=300;function VR(){let n=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(n===void 0||n==="")return ev;let e=parseInt(n,10);return Number.isFinite(e)?Math.max(WR,e):ev}var Ta=class{client;nextRequestId=1;stopOnce=null;callbacks=new ai;requestCallbacks=new Dr;diagnosticMap=new Map;initProgressReset=null;notificationWaiters=new Map;get lspPid(){return this.client.pid}constructor(e){this.client=new Ar(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{u.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(v.SHUTDOWN,null,this.nextRequestId++),u.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(v.EXIT,null),u.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(VR()),u.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(v.BROADCAST),this.callbacks.register(v.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(v.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,v.INITIALIZE,Ve);return this.client.sendRequest(v.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,v.INITIALIZE,0);return this.client.sendRequest(v.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(v.INITIALIZED,{})}sendInitializeAndWaitForNotification(e,t,r,i,o){return new Promise((s,a)=>{let c={initializeResolved:!1,notificationResolved:!1},l=this.startInitTimer(t,r,a);this.initProgressReset=()=>{l.reset(),o?.()};let d=()=>{c.initializeResolved&&c.notificationResolved&&(l.clear(),s())};this.notificationWaiters.set(t,()=>{c.notificationResolved=!0,d()});let g=this.nextRequestId++;this.client.sendRequest(v.INITIALIZE,e,g),this.requestCallbacks.registerPending(g,v.INITIALIZE,0).then(()=>{c.initializeResolved=!0;try{i()}catch(y){l.clear(),a(y instanceof Error?y:new Error(String(y)));return}d()},y=>{l.clear(),a(y)})})}startInitTimer(e,t,r){let i,o=()=>{clearTimeout(i),this.initProgressReset=null,this.notificationWaiters.delete(e)},s=()=>{i=setTimeout(()=>{o(),r(new Error(`LSP initialization timeout after ${t}ms`))},t)},a=()=>{clearTimeout(i),s()};return s(),{reset:a,clear:o}}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new Ra(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(v.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(v.DID_CLOSE,e)}sendLspRequest(e,t,r=BR){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(v.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(v.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);u.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):u.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(!t)return;this.initProgressReset?.();let r=this.notificationWaiters.get(t);if(r){this.notificationWaiters.delete(t),r();return}switch(t){case v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.handleProgress(e.params);break;case v.WINDOW_SHOW_MESSAGE:u.debug(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:u.debug(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){T(e)&&this.broadcastToClients({jsonrpc:x,method:v.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,v.PUBLISH_DIAGNOSTICS,Qy,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Qy}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,v.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:x,method:v.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var xa=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){u.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new ru(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},ru=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var GR={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},qR={MODULE_INIT_FINISH:Rn.MODULE_INIT_FINISH,INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},N={...GR,...qR},Rr={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"},tv=new Set([1e3,2e3,3e3,3001]);function zR(n){if(!T(n))return!1;let e=n.textDocument;return T(e)&&typeof e.uri=="string"}function JR(n){return T(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function YR(n){return T(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var Na=class n{client;isInitialized=!1;stopOnce=null;callbacks=new ai;requestCallbacks=new Dr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new Ar(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{u.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:N.EXIT,params:{}}),Rr.EXIT),u.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),u.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(N.BROADCAST),this.callbacks.register(N.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(N.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(N.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(N.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:x,method:N.INITIALIZED,params:{editors:e}}),Rr.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:x,id:0,result:{}}),Rr.EMPTY)}sendAsyncRequest(e,t,r,i){if(!T(t)){u.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!zR(t)){u.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){u.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=St(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;u.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(u.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!JR(r)){u.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:x,method:N.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),N.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!T(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){u.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;u.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:N.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Rr.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=St(t);e.textDocument.uri=i,u.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new xa(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,N.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:N.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Rr.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=St(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,N.PUBLISH_DIAGNOSTICS)),u.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:N.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Rr.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=St(e);u.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){u.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:x,method:N.DID_CLOSE,params:{textDocument:{uri:r}}}),Rr.DID_CLOSE)}getDiagnosticMessage(e){let t=St(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,N.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:x,method:N.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case N.MODULE_INIT_FINISH:return u.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(N.MODULE_INIT_FINISH),this.callbacks.unregister(N.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case N.INDEXING_PROGRESS_UPDATE:return u.info(`[LSP] onIndexingProgressUpdate: ${YR(t.params)}`),this.callbacks.invoke(N.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case N.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case N.ON_PACKAGE_CHANGE_FINISH:u.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case N.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case N.ON_ASYNC_HOVER:this.handleAsyncResponse(t,N.HOVER);return;case N.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,N.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case N.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,N.REFERENCES);return;default:u.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){u.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;T(t)&&T(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){u.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:x,method:N.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){u.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){u.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}u.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){u.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!T(r)){u.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){u.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){u.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,N.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){u.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){u.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(tv)&&this.finalizeDiagnostic(t,N.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import nu from"path";import*as ja from"path";var La=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Ma=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Oa=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var _a=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Fa=class{typeSetting=new Oa;parameterNames=new _a};var $a=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=de(ja.dirname(t)),this.indexingDataLocation=de(i),this.loggerPath=de(ja.join(r,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new La;gutterIconsSetting=new Ma;inlayHintsSetting=new Fa;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as rv from"path";var Co=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(de(rv.join(e,"src","main","resources")))}};var KR="OS",ci=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${KR}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new Co(e)):this.buildProfileParam=new Co}toString(){return JSON.stringify(this)}};var li=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as je from"path";import*as pi from"fs";var Ha=class{modulePath;dependencies={};dynamicDependencies={}};var mn=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var di=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as or from"path";import*as Ua from"fs";var ui=class{name="";version="";storePath="";dependencyPath="";path=""};var F={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Ne.OH_PACKAGE_JSON5},ko=`${F.HVIGOR_CACHE}/${F.DEPENDENCY}`,fn=`${F.DEPENDENCY}${F.JSON5}`,eK=Ne.SYNC_OUTPUT_PATH;var Io=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=or.join(this.dependencyPath,F.OH_PACKAGE_JSON5),r=rt(t);r&&(this.dependencies=this.getDependencyList(r,F.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,F.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,F.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!T(e))return r;let i=e[t];if(!T(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){u.error(`${o} package dependency value is not String ${t}`);continue}let a=new ui;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=or.normalize(or.join(this.modulePath,F.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),or.isAbsolute(s)){r.dependencyPath=o;return}i||(o=or.resolve(this.modulePath,s)),Ua.existsSync(o)&&Ua.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){u.error("parser dependency path is invalid",o)}}};import*as hn from"fs";import*as Tr from"path";import XR from"json5";var Ba=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return Tr.join(this.projectPath,F.OH_MODULES_PATH,F.OHPM_PATH,F.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let i of e)if(!n.checkObjectDepth(i,t,r+1))return!1;return!0}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&!n.checkObjectDepth(e[i],t,r+1))return!1;return!0}readLockFile(e){if(!hn.existsSync(e))return u.error("lock file does not exist"),this.clearDependencies(),null;try{let t=hn.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return u.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return u.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=hn.readFileSync(e,"utf8"),r=XR.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(u.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(u.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return u.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!T(e))return u.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return u.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(u.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,F.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,F.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,F.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!T(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!T(o)){u.error(`${i} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof o.storePath=="string"&&t.set(i,o.storePath)}return t}getDependencyList(e,t,r){if(!T(e))return[];let i=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(++i>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(T(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,o)}}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!T(i))return u.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!T(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){u.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!T(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",y=new ui;y.name=c,y.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(y,r,c,d,g);let I=`${c}@${g}`;this.storePathMap.has(I)&&(y.storePath=this.storePathMap.get(I)||""),o.push(y)}return o}parseDependencyPath(e,t,r,i,o){let s=Tr.resolve(this.projectPath,Tr.join(t,F.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=Tr.isAbsolute(a)?a:Tr.resolve(this.projectPath,a);hn.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){u.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function nv(n){return T(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var gn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Vt(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e,t){let r=this.projectPath,i=je.join(r,ko),o=je.join(i,fn);if(!pi.existsSync(i)||!pi.existsSync(o)){let l="Dependency map or JSON not found";return u.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:`${l}, please rebuild project`}}let s=new di(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,s),this.parseLockJson(s);let a=this.moduleInfoParse.getAllModuleInfo();if(a.length===0){let l="No modules found in build-profile.json5";return u.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:l}}let c=Date.now();for(let l=0;l<a.length;l++){let d=a[l];if(nv(d)){try{E.assertModuleName(d.name)}catch{u.warn(`[Parser] Skipping module with invalid name: ${d.name}`);continue}this.parseSingleModule(d,i,s,e),((l+1)%50===0||l+1===a.length)&&(u.info(`[Parser] getAllDependencyMap progress: ${l+1}/${a.length} (${Date.now()-c}ms)`),t?.(l+1,a.length))}}return u.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-c}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=je.join(r,ko),o=je.join(i,fn);if(!pi.existsSync(i)||!pi.existsSync(o))return u.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new di(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return u.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!nv(l))continue;let d=l.name;try{E.assertModuleName(d)}catch{u.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=je.resolve(this.projectPath,l.srcPath),y=je.join(i,d),I=de(g),le=this.buildModuleDependencies(d,I,y,a);le.moduleName=d,t.push(le)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=je.resolve(this.projectPath,e.srcPath),a=je.join(t,o),c=de(s),l=new ci(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new li(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new di(this.projectPath,e,t);Io.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Ha;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new mn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new mn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=je.join(e,F.OH_PACKAGE_JSON5);if(!pi.existsSync(r))return;Io.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new Ba(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=je.join(e,"src","main","module.json5"),i=rt(r);if(!T(i)||!T(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(T(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)T(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=je.join(e,"src","main","resources","base","profile","main_pages.json"),r=rt(t);return!T(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!T(t)||!T(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=je.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=rt(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!T(t)||!T(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!T(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=je.join(this.projectPath,"build-profile.json5");this.buildProfileCache=rt(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!T(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Wa=class{constructor(e=[]){this.valueSet=e}};var mi=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var iv=(A=>(A[A.File=1]="File",A[A.Module=2]="Module",A[A.Namespace=3]="Namespace",A[A.Package=4]="Package",A[A.Class=5]="Class",A[A.Method=6]="Method",A[A.Property=7]="Property",A[A.Field=8]="Field",A[A.Constructor=9]="Constructor",A[A.Enum=10]="Enum",A[A.Interface=11]="Interface",A[A.Function=12]="Function",A[A.Variable=13]="Variable",A[A.Constant=14]="Constant",A[A.String=15]="String",A[A.Number=16]="Number",A[A.Boolean=17]="Boolean",A[A.Array=18]="Array",A[A.Object=19]="Object",A[A.Key=20]="Key",A[A.Null=21]="Null",A[A.EnumMember=22]="EnumMember",A[A.Struct=23]="Struct",A[A.Event=24]="Event",A[A.Operator=25]="Operator",A[A.TypeParameter=26]="TypeParameter",A))(iv||{}),ov=()=>Object.values(iv).filter(n=>typeof n=="number");var Va=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ga=class{applyEdit=!0;workspaceEdit=new Va;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Wa(ov());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new mi;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var qa=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var za=class{constructor(e=[]){this.valueSet=e}};var Ja=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var sv=(R=>(R[R.Text=1]="Text",R[R.Method=2]="Method",R[R.Function=3]="Function",R[R.Constructor=4]="Constructor",R[R.Field=5]="Field",R[R.Variable=6]="Variable",R[R.Class=7]="Class",R[R.Interface=8]="Interface",R[R.Module=9]="Module",R[R.Property=10]="Property",R[R.Unit=11]="Unit",R[R.Value=12]="Value",R[R.Enum=13]="Enum",R[R.Keyword=14]="Keyword",R[R.Snippet=15]="Snippet",R[R.Color=16]="Color",R[R.File=17]="File",R[R.Reference=18]="Reference",R[R.Folder=19]="Folder",R[R.EnumMember=20]="EnumMember",R[R.Constant=21]="Constant",R[R.Struct=22]="Struct",R[R.Event=23]="Event",R[R.Operator=24]="Operator",R[R.TypeParameter=25]="TypeParameter",R))(sv||{}),av=()=>Object.values(sv).filter(n=>typeof n=="number");var Ya=class{completionItemKind=new za(av());completionItem=new Ja;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Ka=class{synchronization=new qa;completion=new Ya;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new mi;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Xa=class{workspace=new Ga;textDocument=new Ka;notebookDocument=null;window=null;general=null;experimental=null};var Za=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}};var Qa=class{constructor(e,t,r,i,o,s=!0,a,c=!1){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.nodePath=a;this.useSocket=c;this.serverPath=Cn(t,this.useStandardProtocol),this.logPath=hm(),this.indexLogPath=i||this.logPath,u.debug(`[LspServerProxy] arktsLangServer=${t}`),u.debug(`[LspServerProxy] useStandardProtocol=${this.useStandardProtocol}, useSocket=${this.useSocket}`),u.debug(`[LspServerProxy] serverPath=${this.serverPath}`);let l={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,projectPath:this.rootUri,useSocket:this.useSocket,nodePath:this.nodePath};this.messageHandle=this.useStandardProtocol?new Ta(l):new Na(l),this.messageHandle.setBroadcastToClients(d=>this.onLspMessage(d))}messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t,r){let i=!1;try{u.debug(`serverPath: ${this.serverPath}`),u.debug(`rootUri: ${this.rootUri}`),u.debug(`sdkPath: ${this.sdkPath}`),u.debug(`logPath: ${this.logPath}`);let o=St(this.rootUri),s=new $a(o,this.serverPath,this.logPath,this.indexLogPath),a=[],l=new gn(this.rootUri,this.sdkPath).getAllDependencyMap(a,r);if(l.status==="ERROR")throw new Error(`${l.message}`);this.fillModuleModelsPaths(a),s.modules=a;let d=Ss(a.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new Za(o,s,new Xa),this.useStandardProtocol?await this.startStandardProtocol(this.currentParams):await this.startLegacy(this.currentParams,e),i=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),u.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(i)}async startStandardProtocol(e){let t=this.messageHandle,r=()=>t.broadcastToClients({jsonrpc:x,method:v.ARKTS_INDEXING_PROGRESS,params:{}});this.useSocket?(u.info("[LSP] socket mode: waiting for initialize response + aceProject/onModuleInitFinish"),await t.sendInitializeAndWaitForNotification(e,Rn.MODULE_INIT_FINISH,Ve,()=>{u.info("[LSP] initialize response received"),r(),t.sendInitialized()},r),u.info("[LSP] initialize response + onModuleInitFinish received, initialization complete")):(await t.sendInitializeResettable(e,Ve),u.info("[LSP] initialize response received"),r(),t.sendInitialized())}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:x,method:v.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Ve),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){u.debug(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=T(r)?r:{};u.debug(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:x,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(v.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(v.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(v.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(v.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(v.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new gn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){u.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),u.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return u.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];u.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),u.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new mn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new ci(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new li([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=xn(nu.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=xn(nu.join(t,"default/openharmony/ets/api")),o=xn(nu.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case v.HOVER:this.stdHandle.sendLspRequest(v.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;case v.DEFINITION:this.stdHandle.sendLspRequest(v.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;case v.REFERENCES:this.stdHandle.sendLspRequest(v.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:x,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:x,id:e.id,error:{code:-32603,message:t.message}}));break;default:u.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Yy(e)){u.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case v.DID_OPEN:this.handleDidOpenNotification(e);break;case v.DID_CHANGE:this.handleDidChangeNotification(e);break;case v.DID_CLOSE:this.handleDidCloseNotification(e);break;case v.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case v.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case v.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:u.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){u.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(v.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as sr from"fs";import*as Ye from"path";import{createHash as QR}from"crypto";import{EventEmitter as eT}from"events";var ec=class extends eT{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),u.info(`[ConfigFileWatcher] Stopped watching: ${i}`));u.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!sr.existsSync(t)){u.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=sr.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{u.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),u.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){u.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=Ye.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=Ye.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=Ye.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=Ye.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){u.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,u.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=rt(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return u.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Ye.join(this.projectRoot,F.OH_PACKAGE_JSON5);sr.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=Ye.resolve(this.projectRoot,o.srcPath),a=Ye.join(s,F.OH_PACKAGE_JSON5);sr.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Ye.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=sr.readFileSync(t,"utf-8");return QR("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=sr.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{u.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){u.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){u.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){u.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),u.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Ye.basename(t),relativePath:Ye.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),u.info("[ConfigFileWatcher] All watchers stopped")}};import*as xr from"fs";import*as At from"path";import{createHash as tT}from"crypto";import{EventEmitter as rT}from"events";var tc=class extends rT{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=At.join(t,ko)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!xr.existsSync(this.depMapDir)){u.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=xr.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{u.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){u.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),u.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return de(At.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===F.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===fn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=At.join(this.depMapDir,r);xr.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,u.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=At.join(this.depMapDir,F.OH_PACKAGE_JSON5),r=At.join(this.depMapDir,fn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:(E.assertModuleName(s.name),At.join(this.depMapDir,s.name,F.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!xr.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),u.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=At.join(this.depMapDir,fn);try{let r=rt(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return u.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){u.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(u.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){u.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){u.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return de(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=(E.assertModuleName(a.name),At.join(this.depMapDir,a.name,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),u.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),u.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=(E.assertModuleName(o),At.join(this.depMapDir,o,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);u.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=xr.readFileSync(t,"utf-8");return tT("sha256").update(r).digest("hex")}catch{return null}}};import*as Ht from"fs";import*as rc from"path";import{EventEmitter as nT}from"events";var iu={Created:1,Changed:2,Deleted:3},iT=new Set(["oh_modules","node_modules","build",".hvigor",".git",".idea",".cxx",".preview"]);function oT(n){let e=n.replace(/\\/g,"/");return e.endsWith("/ets")&&e.includes("/src/")}var nc=class extends nT{projectRoot;debounceMs;pollMs;sourceDirs=[];watchers=new Map;snapshot=new Map;debounceTimer=null;pollInterval=null;initialScanDone=!1;constructor(e,t=500,r=1e4){super(),this.projectRoot=e,this.debounceMs=t,this.pollMs=r}start(){if(this.sourceDirs=this.discoverSourceDirs(),this.sourceDirs.length===0){u.warn("[SourceFileWatcher] No src/main/ets dir found, skip watching");return}this.refreshSnapshot(),this.initialScanDone=!0;for(let e of this.sourceDirs)this.addSourceDirWatcher(e);this.pollInterval=setInterval(()=>this.scanAndEmit(),this.pollMs),u.info(`[SourceFileWatcher] Started, watching ${this.sourceDirs.length} source dir(s), ${this.snapshot.size} ets file(s)`)}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);for(let[,e]of this.watchers)e.close();this.watchers.clear(),this.snapshot.clear(),this.initialScanDone=!1,u.info("[SourceFileWatcher] Stopped")}addSourceDirWatcher(e){if(!this.watchers.has(e))try{let t=Ht.watch(e,{recursive:!0},(r,i)=>this.onFsEvent(i));t.on("error",r=>{u.error(`[SourceFileWatcher] watch error for ${e}: ${r.message}`)}),this.watchers.set(e,t)}catch(t){u.error(`[SourceFileWatcher] Failed to watch ${e}: ${t instanceof Error?t.message:String(t)}`)}}refreshSourceDirs(){if(!this.initialScanDone)return;let e=this.discoverSourceDirs(),t=new Set(this.sourceDirs),r=new Set(e),i=e.filter(s=>!t.has(s)),o=[...t].filter(s=>!r.has(s));if(!(i.length===0&&o.length===0)){for(let s of i)this.addSourceDirWatcher(s);for(let s of o){let a=this.watchers.get(s);a&&(a.close(),this.watchers.delete(s))}this.sourceDirs=e,this.refreshSnapshot(),u.info(`[SourceFileWatcher] Module dirs changed: +${i.length} -${o.length}, now ${this.sourceDirs.length} source dir(s)`)}}discoverSourceDirs(){let e=[];return this.collectSourceDirs(rc.resolve(this.projectRoot),e,new Set,new Set),e}collectSourceDirs(e,t,r,i){let o;try{o=Ht.realpathSync(e)}catch{return}if(i.has(o))return;i.add(o);let s;try{s=Ht.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of s){if(!a.isDirectory()||iT.has(a.name))continue;let c=rc.resolve(e,a.name);if(!oT(c)){this.collectSourceDirs(c,t,r,i);continue}r.has(c)||(r.add(c),t.push(c))}}onFsEvent(e){!e||typeof e!="string"||e.replace(/\\/g,"/").toLowerCase().endsWith(".ets")&&this.scheduleScan()}scheduleScan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scanAndEmit()},this.debounceMs)}scanAndEmit(){if(!this.initialScanDone)return;let e=this.diffScan();e.length>0&&this.emit("sourceChanged",{changes:e})}refreshSnapshot(){let e=new Map;for(let t of this.sourceDirs)this.collectEtsFiles(t,e);this.snapshot=e}diffScan(){let e=new Map;for(let r of this.sourceDirs)this.collectEtsFiles(r,e);let t=[];for(let[r,i]of e){let o=this.snapshot.get(r);o?(o.mtimeMs!==i.mtimeMs||o.size!==i.size)&&t.push({uri:vt(r),type:iu.Changed}):t.push({uri:vt(r),type:iu.Created})}for(let[r]of this.snapshot)e.has(r)||t.push({uri:vt(r),type:iu.Deleted});return this.snapshot=e,t}collectEtsFiles(e,t){this.collectEtsFilesInto(e,t,new Set)}collectEtsFilesInto(e,t,r){let i;try{i=Ht.realpathSync(e)}catch{return}if(r.has(i))return;r.add(i);let o;try{o=Ht.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of o){let a=rc.resolve(e,s.name);if(s.isDirectory()){this.collectEtsFilesInto(a,t,r);continue}!s.isFile()||!s.name.toLowerCase().endsWith(".ets")||this.recordSnapshot(a,t)}}recordSnapshot(e,t){let r;try{r=Ht.statSync(e)}catch{return}t.set(e,{mtimeMs:r.mtimeMs,size:r.size})}};import{spawn as sT}from"child_process";var cv=["install","--all"];function lv(n,e){let t=n.split(/\r?\n/),r=t.pop()??"";for(let i of t)i&&(u.info("[ohpm] %s",i),e?.(i));return r}async function aT(n,e,t,r,i){return new Promise(o=>{u.info("[ohpm] spawning: %s %s %s, cwd=%s",n,e,cv.join(" "),t);let s=sT(n,[e,...cv],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),a="",c="";s.stdout?.on("data",l=>{a=lv(a+l.toString(),i)}),s.stderr?.on("data",l=>{c=lv(c+l.toString(),i)}),s.on("close",l=>{a&&(u.info("[ohpm] %s",a),i?.(a)),c&&(u.info("[ohpm] %s",c),i?.(c)),u.info("[ohpm] process exited, code=%s",l),o({exitCode:l??-1})}),s.on("error",l=>{u.error("[ohpm] process error: %s",l.message),o({exitCode:-1})})})}async function dv(n,e,t,r,i){try{if(!t)return u.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!r)return u.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o}=await aT(t,r,n,e,i);return o===0?(u.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(u.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),!1)}catch(o){return u.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var uv={UNINITIALIZED:-32099,UNKNOWN:-32e3},Ao=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,uv.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,uv.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var fi=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;sourceFileWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[],t){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e,t)}catch(r){throw u.error(`[ArktsLspManager] start() synchronous failure: ${r instanceof Error?r.message:String(r)}`),r}}sendNotification(e){if(!this.lspProxy){u.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){u.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r,i,o,s,a,c){if(u.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return u.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let l=s?.skipHvigorSync===!0,d=await hs(e,async()=>await dv(e,t,r??"",i??"",a)?l?(u.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await bm(e,t,r??"",o??"",c)?(u.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(u.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(u.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return d.acquired?d.result:(u.info("[ArktsLspManager] 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}async performDispose(){try{this.configWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}try{this.sourceFileWatcher?.stop()}catch(e){u.warn(`[ArktsLspManager] sourceFileWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.sourceFileWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){u.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e,t){let r=new Qa(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol,this.config.nodePath,this.config.useSocket??!1);r.setOnMessage(i=>this.handleLspMessage(i)),r.start(e,i=>this.handleLspInitialized(i),t),this.lspProxy=r}handleLspInitialized=e=>{if(this.isInitialized=e,e)u.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.startSourceFileWatcher(),this.onMessage({jsonrpc:x,method:v.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();u.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Ao.uninitialized(t):Ao.unknown();this.onMessage({jsonrpc:x,method:v.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(u.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:x,method:v.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new ec(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new tc(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){u.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:x,method:v.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}startSourceFileWatcher(){this.sourceFileWatcher||(this.sourceFileWatcher=new nc(this.config.workspaceRoot),this.sourceFileWatcher.on("sourceChanged",e=>{if(!this.lspProxy){u.warn("[ArktsLspManager] LspServerProxy not initialized, skip didChangeWatchedFiles");return}this.sendNotification({jsonrpc:x,method:v.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:e.changes}}),u.info(`[ArktsLspManager] Notified didChangeWatchedFiles: ${e.changes.length} change(s)`)}),this.sourceFileWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){u.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),e.kind!==4&&this.sourceFileWatcher?.refreshSourceDirs(),this.onConfigChanged?.()}};var cT=10080*60*1e3,lT=7200*60*1e3,dT=120*1e3,hi=class n{manager=null;get aceServerPid(){return this.manager?.aceServerPid??null}initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodePath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;onInitProgress=null;onDepParseProgress=null;useStandardProtocol=!0;useSocket;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION,completion:v.COMPLETION,signatureHelp:v.SIGNATURE_HELP,documentHighlight:v.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i,o,s=!1){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i,this.nodePath=o,this.useSocket=s}setOnConfigChanged(e){this.onConfigChangedCallback=e}setOnInitProgress(e){this.onInitProgress=e}setOnDepParseProgress(e){this.onDepParseProgress=e}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}=this.resolveProjectAndDeveco();this.useStandardProtocol=r;let i=Se(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Zc(s,cT,"[ArkTS-Check]"),Zc(o,lT,"[ArkTS-Check]")}),ws(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}, useSocket=${this.useSocket}`),this.manager=new fi({sdkPath:l,arktsLangServerPath:t,workspaceRoot:de(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r,nodePath:this.nodePath,useSocket:this.useSocket}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(Ve),this.manager.start([],this.onDepParseProgress??void 0).catch(y=>{let I=y instanceof Error?y:new Error(String(y));this.failInit(I)})})}resolveProjectAndDeveco(){let e=Wt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=Qo(t);return{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:r}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=vt(e),i=await gt.promises.readFile(e,"utf8"),s=`deveco.apptool.${Re.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return uT(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},dT);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1320
|
-
`):"No valid .ets files"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,
|
|
1321
|
-
`)),t.length>0&&
|
|
1322
|
-
`));let i=
|
|
1323
|
-
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="No diagnostics collected"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){
|
|
1324
|
-
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await
|
|
1325
|
-
`)),
|
|
1333
|
+
`,a=o[1],c=e.map((d,h)=>`${a} "${d}"${h<e.length-1?",":""}`).join(s),l=`${a}"deviceTypes": [${s}${c}${s}${a}]`;ve.writeFileSync(n,i.replace(o[0],()=>l),"utf-8")}function k$(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function R$(r){return oP.platform()==="darwin"?J.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):J.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function D$(r,e){let t=R$(e);if(!ve.existsSync(t))return!1;let n=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of n){let s=J.join(t,i),a=J.join(r,o);ve.existsSync(s)&&(ve.mkdirSync(J.dirname(a),{recursive:!0}),ve.copyFileSync(s,a))}return!0}function x$(r){let e=k$(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let i=J.join(r,n);ve.mkdirSync(J.dirname(i),{recursive:!0}),ve.writeFileSync(i,e)}}function I$(r,e){e&&D$(r,e)||x$(r)}function A$(r){let e=[J.join(r,"gitignore.txt"),J.join(r,"entry","gitignore.txt")];for(let t of e)if(ve.existsSync(t)){let n=J.dirname(t);ve.renameSync(t,J.join(n,".gitignore"))}}function aP(r,e,t,n,i,o){let s=b$();if(!ve.existsSync(s))throw new Error(`Template directory not found: ${s}`);ve.mkdirSync(r,{recursive:!0}),sP(s,r),A$(r),I$(r,o),Ea(J.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Ea(J.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),C$(r,i),E$(r,n);let a=P$(r);if(!a)throw new Error("Template integrity check failed.");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,deviceTypes:i,verified:a}}function _$(r){if(r.length<1||r.length>200)throw new Pe("errorCode",`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Pe("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function M$(r){if(!r||r.length===0)return[Mo[0]];let e=r.map(n=>n.toLowerCase()),t=r.filter((n,i)=>!Mo.includes(e[i]));if(t.length>0)throw new Pe("errorCode",`Unsupported device type(s): ${t.map(n=>`"${n}"`).join(", ")}. Supported types: ${Mo.join(", ")}`);return[...new Set(e)]}function fP(r){if(pP.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function dP(r){if(r.length===0)throw new Pe("errorCode","Project path cannot be empty.");if(r.length>120)throw new Pe("errorCode",`Project path cannot exceed 120 characters (current: ${r.length}).`);let e=pP.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(r)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Pe("errorCode",`Project path can only contain ${o}.`)}let n=fP(r);if(/[\u4e00-\u9fff]/.test(n))throw new Pe("errorCode","Project path cannot contain Chinese characters.");if(n.endsWith("."))throw new Pe("errorCode","Project path cannot end with a dot (.)")}function O$(r){let e=r,t=Pa.parse(r).root;for(;e!==t;){if(zr.existsSync(e))return e;e=Pa.dirname(e)}return zr.existsSync(t)?t:null}function uP(r){let e=O$(r);if(!e)throw new Pe("errorCode",`No existing parent directory found for '${r}'. Cannot create project directory.`);try{zr.accessSync(e,zr.constants.W_OK)}catch{throw new Pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=Pa.join(e,`.deveco_write_test_${Date.now()}`);try{zr.writeFileSync(t,"test"),zr.unlinkSync(t)}catch{throw new Pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function L$(r){return`com.example.${r.toLowerCase()}`}function F$(r,e){if(e){let i=fP(e),o=Pa.resolve(i);if(zr.existsSync(o)){if(zr.readdirSync(o).length>0)throw new Pe("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else uP(o);return o}let t=ch.cwd(),n=Pa.join(t,r);if(zr.existsSync(n))throw new Pe("errorCode",`Directory '${n}' already exists. Cannot create project here.`);return uP(n),n}function $$(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let i=Number(r.apiLevel);if(!Number.isInteger(i)||i<17)throw new Pe("errorCode",`Invalid API version ${r.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Pe("errorCode",`Invalid API version ${r.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>n)throw new Pe("errorCode",`Invalid API version ${r.apiLevel}. Without DevEco Studio, supported range is API version 17-${n}`);return i}return t!==void 0?t:23}async function j$(){try{return await P.new()}catch(r){console.error(lP(`DevEco Studio not found: ${r.message}`)),console.log(lP("Use placeholder API level instead."));return}}var Pe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function ah(r,e,t,n){let i={event:v.CommandExecuted,args:["create"],apiLevel:n?.apiLevel??null},o={duration_ms:Date.now()-r,success:e,error_code:t};await R.track(i,o).catch(()=>{})}function H$(r){console.log(`
|
|
1334
|
+
`+cP("Project created successfully.")),console.log(`Project root: ${r.projectRoot}`),console.log(`App name: ${r.appName}`),console.log(`Bundle name: ${r.bundleName}`),console.log(`API level: ${r.apiLevel}`),console.log(`Device types: ${r.deviceTypes.join(", ")}`),console.log(cP("Template integrity check passed."))}var U$=new T$("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").option("--device-types <types...>",`Device types written to module.json5 (default: ${Mo[0]}; supported: ${Mo.join(", ")})`).action(async r=>{let e=Date.now();try{r.appName||(console.error(sh("Error: --app-name is required")),await ah(e,!1,"errorCode",r),ch.exit(1));let t=r.appName;_$(t);let n=M$(r.deviceTypes),i=r.bundleName||L$(t);E.assertBundleNameStrict(i),r.projectPath&&dP(r.projectPath);let o=F$(t,r.projectPath);dP(o),console.log(N$("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${i}`),console.log(`Device types: ${n.join(", ")}`);let s=await j$(),a=$$(r,s);console.log(`API level: ${a}`);let c=s?.devecoStudioPath,l=aP(o,t,i,a,n,c);H$(l),await ah(e,!0,null,r)}catch(t){let n=t,o=t instanceof Pe?t.code:n.code??n.name??"UnknownError";console.error(sh(`
|
|
1335
|
+
Failed to create project.`)),console.error(sh(n.message)),await ah(e,!1,o,r),ch.exit(1)}}),mP=U$;import{Command as B$}from"commander";import{red as W$,cyan as gP}from"colorette";function yP(r){return[...new Set([...r.agents,...r.projectAgents.map(({agent:e})=>e)])]}async function hP(r,e,t,n){await R.track(r,{duration_ms:Date.now()-e,success:t,error_code:n}).catch(()=>{})}async function V$(r,e,t,n,i){let o={event:v.SkillConfigOperation,subAction:"install",targetType:t?"path":n?"project":"global",agents:yP(r)},s=Date.now();try{let a=await new ar().installBundledSkill(e,r,i),c=a.every(l=>l.success);return await hP(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await hP(o,s,!1,c),a}}async function G$(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Rc(o,i,t);n.push(s)}for(let i of r.agents){let o=await Rc(i,e,t);n.push(o)}return n}async function q$(r,e){let t=[];for(let n of r){if(!Rr[n])continue;let o=await Mp(n,process.cwd(),e);t.push(o)}return t}function lh(r){return r!=="qoder"&&r!=="dsh"&&!!Rr[r]}async function z$(r,e,t){let n=yP(r).find(l=>!lh(l));if(t.agent&&n)throw new Error(`${n} does not support MCP configuration via DevEco CLI. Use --skill instead, or use other supported agents for MCP.`);let i=t.force??!1,o=r.projectAgents.filter(l=>lh(l.agent)),s=r.agents.filter(lh);if(o.length===0&&s.length===0)throw new Error("No agents supporting MCP configuration found; use --skill");let a={...r,projectAgents:o,agents:s},c=e?await G$(a,e,i):await q$(a.agents,i);c.length>0&&(console.log(gP("MCP Configuration:")),Op(c))}async function J$(r,e,t){let n={event:v.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},i=Date.now(),o=!0,s=null;try{await z$(r,e,t)}catch(a){throw o=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await R.track(n,a)}}async function K$(r){if(r.path&&r.mcp)throw new Error("--path applies to Skill installation only; remove --mcp");if(r.skill&&r.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=Vi(r.path,r.project,r.agent);if(t&&Dr(t,"Project directory",r.force),e&&Dr(e,"Directory",r.force),r.mcp){let s=await Lp(r,t);await J$(s,t,r);return}let n=await Gi(r,e,t),i=Xn(),o=await V$(n,i,e,t,r.force??!1);console.log(),o.length>0&&(console.log(gP("Skill Installation:")),Wi(o))}var Y$=new B$("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Replace existing Skill content or MCP configuration; create missing target directories").action(async r=>{try{await K$(r)}catch(e){console.error(W$(e instanceof Error?e.message:String(e))),process.exitCode=1}}),wP=Y$;import{Command as oH}from"commander";import{McpServer as Vj}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Gj}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Ta from"fs";import*as Ko from"path";import{z as De}from"zod";import Cd from"path";function SP(r,e,t,n,i){if(e.isError)return{};let o=e.content?.[0]?.text??"";if(!o)return{};let s;switch(r){case"check":s=X$(o);break;case"hover":s={hit:Oo(o)!=null};break;case"definition":case"declaration":s=vP(o,t,n,i,!0);break;case"references":s=Q$(o);break;case"implementation":s=vP(o,t,n,i,!1);break;case"documentSymbol":s=ej(o);break;case"callHierarchy":s=tj(o,t,n,i);break;case"workspaceSymbol":s=rj(o,t);break;default:s={}}return s}function EP(r){let e=Array.isArray(r.files)?r.files[0]:r.file;return typeof e!="string"||!e?void 0:Cd.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Oo(r){let e=r.indexOf(": ");if(e<0)return;let t=r.slice(e+2).trim();if(!(!t||t==="no result"))try{return JSON.parse(t)}catch{return}}function X$(r){let e={total:0,error:0,warn:0,info:0},t=new Set,n=" => Diagnostic: ";for(let o of r.split(`
|
|
1336
|
+
`)){let s=o.indexOf(n);if(s<0)continue;let a;try{a=JSON.parse(o.slice(s+n.length))}catch{continue}if(Array.isArray(a))for(let c of a)c&&typeof c=="object"&&Z$(c,e,t)}let i={diagTotal:e.total,diagError:e.error,diagWarn:e.warn,diagInfo:e.info};return t.size>0&&(i.rules=[...t]),i}function Z$(r,e,t){e.total++;let n=r.severity;n===1?e.error++:n===2?e.warn++:(n===3||n===4)&&e.info++,typeof r.source=="string"&&t.add(r.source)}function Q$(r){let e=Oo(r),t=Array.isArray(e)?e:[],n=new Set;for(let i of t){let o=i?.uri;typeof o=="string"&&n.add(o)}return{refTotal:t.length,fileCount:n.size}}function vP(r,e,t,n,i){let o=Oo(r);if(o==null)return{found:!1};let s=Array.isArray(o)?o:[o],a=s[0]?.uri;return i?{found:!0,sameFile:nj(a,e),sourceType:CP(a,t,n)}:{implTotal:s.length,found:!0}}function ej(r){let e=Oo(r),t=Array.isArray(e)?e:[],n=0,i=new Map,o=s=>{for(let a of s){if(!a||typeof a!="object")continue;n++;let c=a.kind;typeof c=="number"&&i.set(c,(i.get(c)??0)+1);let l=a.children;Array.isArray(l)&&o(l)}};return o(t),{symbolTotal:n,kindDist:dh(i)}}function tj(r,e,t,n){let o=Oo(r)?.calls,s=Array.isArray(o)?o:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let h=(a==="incoming"?l.from:l.to)?.uri,y=CP(h,t,n);c.set(y,(c.get(y)??0)+1)}return{callsTotal:s.length,calleeSrcDist:dh(c)}}function rj(r,e){let t=Oo(r),n=Array.isArray(t)?t:[],i=new Map,o=0;for(let c of n){if(!c||typeof c!="object")continue;let l=c.kind;typeof l=="number"&&i.set(l,(i.get(l)??0)+1);let d=c.tags;(Array.isArray(d)&&d.includes(1)||c.deprecated===!0)&&o++}let s={resultTotal:n.length,kindDist:dh(i),deprecatedHit:o},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function PP(r){if(typeof r!="string"||!r)return null;let e=r;return e.startsWith("file://")&&(e=e.slice(7),process.platform==="win32"&&e.startsWith("/")&&(e=e.slice(1))),e}function CP(r,e,t){let n=PP(r);return n?e&&bP(n,e)?"user_project":t&&bP(n,t)?"sdk":"system":"unknown"}function nj(r,e){let t=PP(r),n=e.file;return!t||typeof n!="string"?!1:kd(t)===kd(n)}function kd(r){try{return Cd.resolve(r).replace(/\\/g,"/").toLowerCase()}catch{return r.replace(/\\/g,"/").toLowerCase()}}function bP(r,e){let t=Cd.relative(kd(e),kd(r));return t!==""&&!t.startsWith("..")&&!Cd.isAbsolute(t)}function dh(r){let e={};for(let[t,n]of r)e[String(t)]=n;return e}var Rd=class{constructor(e,t,n,i){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=n;this.getSdkPath=i}tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:n}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>this.invokeTool(t.name,i,n)))}async invokeTool(e,t,n){if(g.debug(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return n(t);let i=ae(process.memoryUsage().rss),o=await this.resolveLspMemory(),s=Date.now(),a=!0,c=null,l;try{l=await n(t)}catch(d){throw a=!1,c=d instanceof Error?d.code??d.name:"UnknownError",d}finally{await this.trackToolCall(e,t,l,s,i,o,a,c)}return l}async trackToolCall(e,t,n,i,o,s,a,c){if(!this.telemetry)return;let l=n?.isError===!0,d=n&&!l?SP(e,n,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},h=l?!1:a,y=l&&n?ij(n):c,D={event:v.McpToolCall,subAction:e,mcpMemory:o,lspMemory:s,fileExt:EP(t),...d};typeof t.direction=="string"&&(D.direction=t.direction),await this.telemetry.track(D,{duration_ms:Date.now()-i,success:h,error_code:y})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await mt(e);return t===null?"unknown":ae(Number(t)*1024)}};function ij(r){let e=r.content.map(t=>t.text).join(`
|
|
1337
|
+
`);return/not ready|not initialized|initializing|please retry|retry \d+s|syncing|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|no project path/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|Must specify|cannot be used together|invalid/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/does not exist|not exist|not found|No valid|not a .ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function uh(r,e,t,n){return new Rd(r,e,t,n)}import*as Nt from"fs";import*as je from"path";function kP(r){return"method"in r&&!("id"in r)}import{spawn as RP}from"child_process";import*as DP from"crypto";import{EventEmitter as oj}from"events";import*as Jr from"fs";import*as xP from"net";import*as Xt from"path";var sj=50*1024*1024,aj=60*1e3,cj=10*1e3,lj=64*1024;function dj(r){let e=Xt.resolve(r).replace(/\\/g,"/");return e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),process.platform==="win32"?e.toLowerCase():e}function uj(r){return DP.createHash("sha1").update(dj(r)).digest("hex").slice(0,12)}function pj(r){let e=Xt.resolve(r),t=e.split(Xt.sep),n=t.lastIndexOf("out");return n>0?t.slice(0,n+1).join(Xt.sep):Xt.dirname(e)}var Cn=class extends oj{constructor(t){super();this.config=t}process=null;buffer=Buffer.alloc(0);isClosing=!1;socket=null;_ownsProcess=!1;get pid(){return this.process?.pid??null}get ownsProcess(){return this._ownsProcess}get isSocketMode(){return this.socket!==null}ensureDirectories(){let t=Xt.join(this.config.logPath,"lspLog");return Jr.existsSync(t)||Jr.mkdirSync(t,{recursive:!0}),Jr.existsSync(this.config.indexingDataLocation)||Jr.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){this.config.useSocket&&this.config.projectPath?await this.startSocket(t):await this.startStdio(t)}async startStdio(t){this._ownsProcess=!0;let n=this.ensureDirectories();m.debug(`[LspClient] serverMaxSize=${t}MB`);let i=Ss({serverPath:this.config.serverPath,lspLogPath:n,serverMaxSize:t}),o=Zn(this.config.nodePath);m.debug(`[LspClient] Starting process: node ${i.join(" ")}`),m.debug(`[LspClient] nodePath: ${o}`),this.process=RP(o,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(!0,!0),await new Promise(s=>setTimeout(s,500)),m.info("[LspClient] start lsp process success")}async startSocket(t){let n=this.ensureDirectories(),i=this.config.projectPath,o=pj(this.config.serverPath),s=Xt.join(i,".idea",".deveco","arkts",".cache",`lsp-socket-${uj(o)}.properties`),a=this.tryReadPortFile(s);if(a!==null)try{m.info(`[LspClient] Port file found (lspSocketPort=${a}), connecting to existing server`),this._ownsProcess=!1,await this.connectSocket(a),m.info("[LspClient] Connected to existing socket server");return}catch(d){m.warn(`[LspClient] Failed to connect to existing socket server (port=${a}): ${d instanceof Error?d.message:d}, falling back to spawn`)}let c=3,l=null;for(let d=1;d<=c;d++)try{d===1?m.info("[LspClient] Spawning server in socket mode"):m.info(`[LspClient] Retry ${d}/${c} spawning socket server`),this._ownsProcess=!0,await this.spawnSocketServer(t,n,i),m.info("[LspClient] Socket server started and connected");return}catch(h){l=h instanceof Error?h:new Error(String(h)),m.warn(`[LspClient] Spawn attempt ${d}/${c} failed: ${l.message}`),this.cleanupSpawnResidue()}throw new Error(`Failed to start socket server after ${c} attempts: ${l?.message}`)}cleanupSpawnResidue(){if(this.process){try{this.process.exitCode===null&&this.process.signalCode===null&&this.process.kill()}catch{}this.process=null}if(this.socket){try{this.socket.destroy()}catch{}this.socket=null}}tryReadPortFile(t){try{if(!Jr.existsSync(t))return null;let i=Jr.readFileSync(t,"utf8").match(/lspSocketPort\s*=\s*(\d+)/);if(i){let o=parseInt(i[1],10);if(Number.isFinite(o)&&o>0)return o}return null}catch{return null}}async spawnSocketServer(t,n,i){m.debug(`[LspClient] serverMaxSize=${t}MB`);let o=Ss({serverPath:this.config.serverPath,lspLogPath:n,serverMaxSize:t,transportFlag:"--scope=multi",projectPath:i}),s=Zn(this.config.nodePath);m.debug(`[LspClient] Starting process (socket): node ${o.join(" ")}`),m.debug(`[LspClient] nodePath: ${s}`),this.process=RP(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0,detached:!0});let a=await this.waitForPortFromStdout(aj);m.debug(`[LspClient] LSP_SOCKET_LISTENING port=${a}`),await this.connectSocket(a),this.bindProcessEvents(!0,!1)}waitForPortFromStdout(t){return new Promise((n,i)=>{let o=this.process?.stdout;if(!o){i(new Error("LSP server failed to start: no stdout"));return}let s=/LSP_SOCKET_LISTENING:(\d+)/,a="",c=setTimeout(()=>{o.removeListener("data",l),i(new Error("LSP server failed to start: port not received within timeout"))},t),l=d=>{a+=d.toString("utf8");let h=a.match(s);if(h){clearTimeout(c),o.removeListener("data",l),n(parseInt(h[1],10));return}a=a.slice(-lj)};o.on("data",l)})}connectSocket(t){return new Promise((n,i)=>{let o=xP.connect(t,"127.0.0.1"),s=setTimeout(()=>{o.destroy(),i(new Error(`TCP connection to LSP socket timed out (port ${t})`))},cj);o.on("connect",()=>{clearTimeout(s),this.socket=o,this.bindSocketEvents(o),n()}),o.on("error",a=>{clearTimeout(s),i(new Error(`TCP connection to LSP socket failed: ${a.message}`))})})}bindSocketEvents(t){t.on("data",n=>this.handleData(n)),t.on("error",n=>{m.error(`[LspClient] socket error: ${n.message}`),this.isClosing||this.emit("error",n)}),t.on("close",()=>{m.info("[LspClient] socket closed"),this.isClosing||this.emit("error",new Error("LSP socket closed"))})}attachProcess(t,n){if(this.process)throw new Error("[LspClient] process already attached");this._ownsProcess=!0,this.process=t,this.bindProcessEvents(n?.stderrAsError??!0,!0),m.info("[LspClient] attached to external process")}bindProcessEvents(t=!0,n=!0){this.process&&(n&&this.process.stdout?.on("data",i=>{this.handleData(i)}),this.process.stderr?.on("data",i=>{let o=i.toString("utf8").trim();m.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",i=>{m.info(`[LSP EXIT] code=${i}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${i}`))}))}sendRaw(t,n){let i=this.buildLspMessage(t);if(this.socket&&!this.socket.destroyed&&this.socket.writable){m.debug(`[LspClient] [SOCKET SEND] ${n}: ${t.slice(0,200)}`),this.socket.write(i,"utf8");return}if(!this.process?.stdin?.writable){m.warn("[LspClient] Cannot send message, no writable transport");return}m.debug(`[LspClient] send message: ${n}`),this.process.stdin.write(i,"utf8")}send(t,n,i){let o={jsonrpc:"2.0",method:t,params:n};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,n){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:n}),t)}sendRequest(t,n,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:n}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1338
|
+
\r
|
|
1339
|
+
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
|
|
1340
|
+
\r
|
|
1341
|
+
`);if(n===-1)break;let o=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){m.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(o[1],10);if(!Number.isFinite(s)||s<0||s>sj){m.warn(`[LspClient] Invalid Content-Length: ${o[1]}, drop until next packet`),this.buffer=this.buffer.slice(n+4);continue}let a=n+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){m.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.logSocketRecv(d.json),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.logSocketRecv(l),this.emit("message",l),this.buffer=this.buffer.slice(c)}}logSocketRecv(t){this.socket&&m.debug(`[LspClient] [SOCKET RECV] ${t.slice(0,200)}`)}waitForExitOrTimeout(t){let n=this.process;return!n||n.exitCode!==null||n.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),n.off("exit",a),i())},a=()=>s();n.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let n=t.search(/\S/);if(n<0||t[n]!=="{"&&t[n]!=="[")return null;let i=0,o=!1,s=!1;for(let a=n;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(n,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){if(this.isClosing=!0,this.socket){this.socket.destroy(),this.socket=null,this.process=null;return}let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var kn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,n){return new Promise((i,o)=>{let s;n>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${n}ms`))},n),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let n=this.pending.get(e);return n?(n.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let n=this.pending.get(e);return n?(n.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,n){m.debug(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)try{i(t,n)}finally{this.callbacks.delete(e)}else{let o=[...this.callbacks.keys()].map(s=>String(s));m.debug(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,n,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{m.debug(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{i()}finally{this.timeouts.delete(e)}},n);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var Dd=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Lo=class{map=new Map;register(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}unregister(e,t){let n=this.map.get(e);n&&(t!==void 0?n.delete(t):n.clear(),n.size===0&&this.map.delete(e))}invoke(e,...t){let n=this.map.get(e);if(n)for(let i of n)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function O(r){return typeof r=="object"&&r!==null}var IP=20*1e3,fj=30*1e3,AP=300,mj=300;function hj(){let r=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(r===void 0||r==="")return AP;let e=parseInt(r,10);return Number.isFinite(e)?Math.max(mj,e):AP}var xd=class{client;nextRequestId=1;stopOnce=null;callbacks=new Lo;requestCallbacks=new kn;diagnosticMap=new Map;initProgressReset=null;notificationWaiters=new Map;get lspPid(){return this.client.pid}constructor(e){this.client=new Cn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{m.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(b.SHUTDOWN,null,this.nextRequestId++),m.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(b.EXIT,null),m.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(hj()),m.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(b.BROADCAST),this.callbacks.register(b.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(b.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,n=this.requestCallbacks.registerPending(t,b.INITIALIZE,it);return this.client.sendRequest(b.INITIALIZE,e,t),n}sendInitializeResettable(e,t){let n=this.nextRequestId++,i=this.requestCallbacks.registerPending(n,b.INITIALIZE,0);return this.client.sendRequest(b.INITIALIZE,e,n),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(b.INITIALIZED,{})}sendInitializeAndWaitForNotification(e,t,n,i,o){return new Promise((s,a)=>{let c={initializeResolved:!1,notificationResolved:!1},l=this.startInitTimer(t,n,a);this.initProgressReset=()=>{l.reset(),o?.()};let d=()=>{c.initializeResolved&&c.notificationResolved&&(l.clear(),s())};this.notificationWaiters.set(t,()=>{c.notificationResolved=!0,d()});let h=this.nextRequestId++;this.client.sendRequest(b.INITIALIZE,e,h),this.requestCallbacks.registerPending(h,b.INITIALIZE,0).then(()=>{c.initializeResolved=!0;try{i()}catch(y){l.clear(),a(y instanceof Error?y:new Error(String(y)));return}d()},y=>{l.clear(),a(y)})})}startInitTimer(e,t,n){let i,o=()=>{clearTimeout(i),this.initProgressReset=null,this.notificationWaiters.delete(e)},s=()=>{i=setTimeout(()=>{o(),n(new Error(`LSP initialization timeout after ${t}ms`))},t)},a=()=>{clearTimeout(i),s()};return s(),{reset:a,clear:o}}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new Dd(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(b.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(b.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(b.DID_CLOSE,e)}sendLspRequest(e,t,n=fj){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,n);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(b.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(b.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:String(n);m.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):m.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let n=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(n,i)}else this.requestCallbacks.resolvePending(n,e.result)}handleNotificationOrRequest(e){let t=e.method;if(!t)return;this.initProgressReset?.();let n=this.notificationWaiters.get(t);if(n){this.notificationWaiters.delete(t),n();return}switch(t){case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case b.PROGRESS:this.handleProgress(e.params);break;case b.WINDOW_SHOW_MESSAGE:m.debug(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case b.WINDOW_LOG_MESSAGE:m.debug(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,n=this.diagnosticMap.get(t);if(!n)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),n.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let n={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=n[t.severity]||"Unknown"}}handleProgress(e){O(e)&&this.broadcastToClients({jsonrpc:L,method:b.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,b.PUBLISH_DIAGNOSTICS,IP,()=>{let t=this.diagnosticMap.get(e),n=t?t.get():[];this.finalizeDiagnostic(e,n,n.length>0?void 0:`received no diagnostics within ${IP}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,n){let i={uri:e,diagnostics:t,...n?{errorMessage:n}:{}};this.requestCallbacks.emit(e,b.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(n=>this.requestCallbacks.hasCallback(n));if(t.length>0){let n={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[n]);return}this.broadcastToClients({jsonrpc:L,method:b.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Id=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let n=`${e}:${t}`;if(this.uniqueMessages.has(n)){m.info(`[LegacyDiagnostic] addMessage: duplicate message=${n}`);return}this.uniqueMessages.add(n),this.messages.push(new ph(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},ph=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var gj={EXIT:"exit",INITIALIZED:"initialized",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"aceProject/onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"aceProject/onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"aceProject/onAsyncDidChange",DID_CLOSE:"textDocument/didClose",ON_ASYNC_HOVER:"aceProject/onAsyncHover",ON_ASYNC_DEFINITION:"aceProject/onAsyncDefinition",ON_ASYNC_FIND_USAGES:"aceProject/onAsyncFindUsages"},yj={MODULE_INIT_FINISH:Yi.MODULE_INIT_FINISH,INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},F={...gj,...yj},Rn={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"},TP=new Set([1e3,2e3,3e3,3001]);function wj(r){if(!O(r))return!1;let e=r.textDocument;return O(e)&&typeof e.uri=="string"}function vj(r){return O(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}function bj(r){return O(r)&&typeof r.moduleName=="string"&&typeof r.current=="number"&&typeof r.total=="number"?`indexing module '${r.moduleName}', ${r.current} of total ${r.total} modules`:`params=${JSON.stringify(r??null)}`}var Ad=class r{client;isInitialized=!1;stopOnce=null;callbacks=new Lo;requestCallbacks=new kn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new Cn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{m.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:F.EXIT,params:{}}),Rn.EXIT),m.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),m.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(F.BROADCAST),this.callbacks.register(F.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(F.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(F.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(F.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:L,method:F.INITIALIZED,params:{editors:e}}),Rn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:L,id:0,result:{}}),Rn.EMPTY)}sendAsyncRequest(e,t,n,i){if(!O(t)){m.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!wj(t)){m.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof n!="number"){m.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(n)}`);return}let o=t.textDocument.uri,s=Ut(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;m.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(m.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!vj(n)){m.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:L,method:F.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),F.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!O(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){m.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;m.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:F.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Rn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=Ut(t);e.textDocument.uri=i,m.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Id(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,F.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:F.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Rn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Ut(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,F.PUBLISH_DIAGNOSTICS)),m.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:F.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Rn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=Ut(e);m.info(`[LSP] didClose, uri: ${n}`);let i=this.diagnosticMap.get(n);if(!t&&(!i||i.isFromEditor)){m.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:L,method:F.DID_CLOSE,params:{textDocument:{uri:n}}}),Rn.DID_CLOSE)}getDiagnosticMessage(e){let t=Ut(e),n=this.diagnosticMap.get(t);return n?n.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let n=t instanceof Error?t.message:String(t);m.error(`[LSP] JSON parse error: ${n}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let n=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,F.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:L,method:F.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case F.MODULE_INIT_FINISH:return m.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(F.MODULE_INIT_FINISH),this.callbacks.unregister(F.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case F.INDEXING_PROGRESS_UPDATE:return m.info(`[LSP] onIndexingProgressUpdate: ${bj(t.params)}`),this.callbacks.invoke(F.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case F.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case F.ON_PACKAGE_CHANGE_FINISH:m.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case F.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case F.ON_ASYNC_HOVER:this.handleAsyncResponse(t,F.HOVER);return;case F.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,F.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case F.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,F.REFERENCES);return;default:m.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){m.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;O(t)&&O(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){m.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:L,method:F.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){m.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(n);return}if(!(t.length>0&&t[0]===!0)){m.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(n);return}m.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){m.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let n=e.params;if(!O(n)){m.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=n.requestId;if(typeof i!="number"){m.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,n)}handleForceOpenFile(e){if(!e){m.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,F.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){m.info("[LSP] publishDiagnostics uri is null");return}let n=e.version??-1;if(n===-1)return;let i=this.diagnosticMap.get(t);if(!i){m.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(n,JSON.stringify(s))}):i.setReceivedType(n),i.hasReceivedAllTypes(TP)&&this.finalizeDiagnostic(t,F.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let n=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[n]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let n=e[t];n&&typeof n.line=="number"&&(n.line=n.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,r.DIAGNOSTIC_TIMEOUT_MS,()=>{let n=this.diagnosticMap.get(e),i=n?n.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${r.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,n,i){let o={uri:e,diagnostics:n,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import fh from"path";import*as Fd from"path";var Td=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Nd=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var _d=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Md=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Od=class{typeSetting=new _d;parameterNames=new Md};var Ld=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=ge(Fd.dirname(t)),this.indexingDataLocation=ge(i),this.loggerPath=ge(Fd.join(n,"lspLog"))}modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Td;gutterIconsSetting=new Nd;inlayHintsSetting=new Od;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as NP from"path";var Ca=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(ge(NP.join(e,"src","main","resources")))}};var Sj="OS",Fo=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${Sj}`;moduleName;moduleType;compileMode="jsbundle";crossPlatform=!1;ignoreCrossPlatform=!1;packageManagerType="ohpm";permissions=[];testPermissions=[];buildProfileParam;appParam={bundleType:"app"};packageName;projectType="OHOS";projectName;moduleDependencies;moduleJsonParam=null;globalDeclarationFiles=[];constructor(e){e?(this.modulePath=e,this.buildProfileParam=new Ca(e)):this.buildProfileParam=new Ca}toString(){return JSON.stringify(this)}};var $o=class{constructor(e=[]){this.pages=e}pagesFileName="main_pages.json";metaDataList=[]};import*as Ye from"path";import*as Uo from"fs";var $d=class{modulePath;dependencies={};dynamicDependencies={}};var Si=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var jo=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Kr from"path";import*as jd from"fs";var Ho=class{name="";version="";storePath="";dependencyPath="";path=""};var G={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Ce.OH_PACKAGE_JSON5},ka=`${G.HVIGOR_CACHE}/${G.DEPENDENCY}`,Ei=`${G.DEPENDENCY}${G.JSON5}`,uce=Ce.SYNC_OUTPUT_PATH;var Ra=class r{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,n){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new r(e,t,n),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,n){this.dependencyPath=e,this.modulePath=t,this.projectPath=n,this.fileSpecPattern=r.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Kr.join(this.dependencyPath,G.OH_PACKAGE_JSON5),n=gt(t);n&&(this.dependencies=this.getDependencyList(n,G.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,G.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,G.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!O(e))return n;let i=e[t];if(!O(i))return n;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){m.error(`${o} package dependency value is not String ${t}`);continue}let a=new Ho;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,i){if(!(!e||!t))try{let o=Kr.normalize(Kr.join(this.modulePath,G.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=o;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=o;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),Kr.isAbsolute(s)){n.dependencyPath=o;return}i||(o=Kr.resolve(this.modulePath,s)),jd.existsSync(o)&&jd.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){m.error("parser dependency path is invalid",o)}}};import*as Pi from"fs";import*as Dn from"path";import Ej from"json5";var Hd=class r{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let n=this.validateLockFile(t);return n.valid?(this.lockFileCache={modules:n.modules,storePathMap:this.parseStorePathMap(n.packages)},!0):!1}getLockFilePath(){return Dn.join(this.projectPath,G.OH_MODULES_PATH,G.OHPM_PATH,G.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,n=0){if(n>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let i of e)if(!r.checkObjectDepth(i,t,n+1))return!1;return!0}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&!r.checkObjectDepth(e[i],t,n+1))return!1;return!0}readLockFile(e){if(!Pi.existsSync(e))return m.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Pi.statSync(e);if(t.size>r.MAX_LOCK_FILE_SIZE)return m.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return m.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=Pi.readFileSync(e,"utf8"),n=Ej.parse(t);return n?r.checkObjectDepth(n,r.MAX_JSON_DEPTH)?n:(m.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(m.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return m.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!O(e))return m.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return m.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(m.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,G.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,G.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,G.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!O(e))return t;let n=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!O(o)){m.error(`${i} value is not json object`);continue}if(++n>r.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof o.storePath=="string"&&t.set(i,o.storePath)}return t}getDependencyList(e,t,n){if(!O(e))return[];let i=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(++i>r.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(O(s)){let a=typeof s.name=="string"?s.name:"";if(n==="."&&a===""||a===n)return this.getFinalDependencyList(e,t,o)}}return[]}getFinalDependencyList(e,t,n){let i=e[n];if(!O(i))return m.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!O(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>r.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!O(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",h=typeof l.version=="string"?l.version:"",y=new Ho;y.name=c,y.version=h.startsWith(r.FILE_DEPENDENCY_PREFIX)?h.substring(r.FILE_DEPENDENCY_PREFIX.length):h,this.parseDependencyPath(y,n,c,d,h);let D=`${c}@${h}`;this.storePathMap.has(D)&&(y.storePath=this.storePathMap.get(D)||""),o.push(y)}return o}parseDependencyPath(e,t,n,i,o){let s=Dn.resolve(this.projectPath,Dn.join(t,G.OH_MODULES_PATH,n));try{let a=o.startsWith(r.FILE_DEPENDENCY_PREFIX)?o.substring(r.FILE_DEPENDENCY_PREFIX.length):o,c=Dn.isAbsolute(a)?a:Dn.resolve(this.projectPath,a);Pi.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){m.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function _P(r){return O(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Ci=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Ar(this.projectPath)}moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e,t){let n=this.projectPath,i=Ye.join(n,ka),o=Ye.join(i,Ei);if(!Uo.existsSync(i)||!Uo.existsSync(o)){let l="Dependency map or JSON not found";return m.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:`${l}, please rebuild project`}}let s=new jo(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,s),this.parseLockJson(s);let a=this.moduleInfoParse.getAllModuleInfo();if(a.length===0){let l="No modules found in build-profile.json5";return m.warn(`[Parser] getAllDependencyMap failed: ${l}.`),{status:"ERROR",message:l}}let c=Date.now();for(let l=0;l<a.length;l++){let d=a[l];if(_P(d)){try{E.assertModuleName(d.name)}catch{m.warn(`[Parser] Skipping module with invalid name: ${d.name}`);continue}this.parseSingleModule(d,i,s,e),((l+1)%50===0||l+1===a.length)&&(m.info(`[Parser] getAllDependencyMap progress: ${l+1}/${a.length} (${Date.now()-c}ms)`),t?.(l+1,a.length))}}return m.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-c}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=Ye.join(n,ka),o=Ye.join(i,Ei);if(!Uo.existsSync(i)||!Uo.existsSync(o))return m.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new jo(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return m.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!_P(l))continue;let d=l.name;try{E.assertModuleName(d)}catch{m.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let h=Ye.resolve(this.projectPath,l.srcPath),y=Ye.join(i,d),D=ge(h),K=this.buildModuleDependencies(d,D,y,a);K.moduleName=d,t.push(K)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=Ye.resolve(this.projectPath,e.srcPath),a=Ye.join(t,o),c=ge(s),l=new Fo(c),d=this.buildModuleDependencies(o,c,a,n);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new $o(h),i.push(l)}buildModuleDependencies(e,t,n,i){let o=new jo(this.projectPath,e,t);Ra.getInstance(n,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new $d;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let n={},i={};for(let o of e.finalDependencies)n[o.name]=new Si(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Si(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=Ye.join(e,G.OH_PACKAGE_JSON5);if(!Uo.existsSync(n))return;Ra.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new Hd(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let n=Ye.join(e,"src","main","module.json5"),i=gt(n);if(!O(i)||!O(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(O(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)O(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=Ye.join(e,"src","main","resources","base","profile","main_pages.json"),n=gt(t);return!O(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!O(t)||!O(t.data))){if(typeof t.data.apiVersion=="string"){let n=parseInt(t.data.apiVersion,10);!Number.isNaN(n)&&n>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=Ye.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=gt(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!O(t)||!O(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let n=t.app.products[0];if(!O(n)||typeof n.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(n.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Ye.join(this.projectPath,"build-profile.json5");this.buildProfileCache=gt(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!O(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Ud=class{constructor(e=[]){this.valueSet=e}};var Bo=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var MP=(x=>(x[x.File=1]="File",x[x.Module=2]="Module",x[x.Namespace=3]="Namespace",x[x.Package=4]="Package",x[x.Class=5]="Class",x[x.Method=6]="Method",x[x.Property=7]="Property",x[x.Field=8]="Field",x[x.Constructor=9]="Constructor",x[x.Enum=10]="Enum",x[x.Interface=11]="Interface",x[x.Function=12]="Function",x[x.Variable=13]="Variable",x[x.Constant=14]="Constant",x[x.String=15]="String",x[x.Number=16]="Number",x[x.Boolean=17]="Boolean",x[x.Array=18]="Array",x[x.Object=19]="Object",x[x.Key=20]="Key",x[x.Null=21]="Null",x[x.EnumMember=22]="EnumMember",x[x.Struct=23]="Struct",x[x.Event=24]="Event",x[x.Operator=25]="Operator",x[x.TypeParameter=26]="TypeParameter",x))(MP||{}),OP=()=>Object.values(MP).filter(r=>typeof r=="number");var Bd=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Wd=class{applyEdit=!0;workspaceEdit=new Bd;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ud(OP());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Bo;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Vd=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Gd=class{constructor(e=[]){this.valueSet=e}};var qd=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var LP=(A=>(A[A.Text=1]="Text",A[A.Method=2]="Method",A[A.Function=3]="Function",A[A.Constructor=4]="Constructor",A[A.Field=5]="Field",A[A.Variable=6]="Variable",A[A.Class=7]="Class",A[A.Interface=8]="Interface",A[A.Module=9]="Module",A[A.Property=10]="Property",A[A.Unit=11]="Unit",A[A.Value=12]="Value",A[A.Enum=13]="Enum",A[A.Keyword=14]="Keyword",A[A.Snippet=15]="Snippet",A[A.Color=16]="Color",A[A.File=17]="File",A[A.Reference=18]="Reference",A[A.Folder=19]="Folder",A[A.EnumMember=20]="EnumMember",A[A.Constant=21]="Constant",A[A.Struct=22]="Struct",A[A.Event=23]="Event",A[A.Operator=24]="Operator",A[A.TypeParameter=25]="TypeParameter",A))(LP||{}),FP=()=>Object.values(LP).filter(r=>typeof r=="number");var zd=class{completionItemKind=new Gd(FP());completionItem=new qd;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Jd=class{synchronization=new Vd;completion=new zd;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new Bo;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Kd=class{workspace=new Wd;textDocument=new Jd;notebookDocument=null;window=null;general=null;experimental=null};var Yd=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}};var Xd=class{constructor(e,t,n,i,o,s=!0,a,c=!1){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.nodePath=a;this.useSocket=c;this.serverPath=Mi(t,this.useStandardProtocol),this.logPath=hw(),this.indexLogPath=i||this.logPath,m.debug(`[LspServerProxy] arktsLangServer=${t}`),m.debug(`[LspServerProxy] useStandardProtocol=${this.useStandardProtocol}, useSocket=${this.useSocket}`),m.debug(`[LspServerProxy] serverPath=${this.serverPath}`);let l={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,projectPath:this.rootUri,useSocket:this.useSocket,nodePath:this.nodePath};this.messageHandle=this.useStandardProtocol?new xd(l):new Ad(l),this.messageHandle.setBroadcastToClients(d=>this.onLspMessage(d))}messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}get lspPid(){return this.messageHandle.lspPid}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t,n){let i=!1;try{m.debug(`serverPath: ${this.serverPath}`),m.debug(`rootUri: ${this.rootUri}`),m.debug(`sdkPath: ${this.sdkPath}`),m.debug(`logPath: ${this.logPath}`);let o=Ut(this.rootUri),s=new Ld(o,this.serverPath,this.logPath,this.indexLogPath),a=[],l=new Ci(this.rootUri,this.sdkPath).getAllDependencyMap(a,n);if(l.status==="ERROR")throw new Error(`${l.message}`);this.fillModuleModelsPaths(a),s.modules=a;let d=jc(a.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new Yd(o,s,new Kd),this.useStandardProtocol?await this.startStandardProtocol(this.currentParams):await this.startLegacy(this.currentParams,e),i=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),m.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(i)}async startStandardProtocol(e){let t=this.messageHandle,n=()=>t.broadcastToClients({jsonrpc:L,method:b.ARKTS_INDEXING_PROGRESS,params:{}});this.useSocket?(m.info("[LSP] socket mode: waiting for initialize response + aceProject/onModuleInitFinish"),await t.sendInitializeAndWaitForNotification(e,Yi.MODULE_INIT_FINISH,it,()=>{m.info("[LSP] initialize response received"),n(),t.sendInitialized()},n),m.info("[LSP] initialize response + onModuleInitFinish received, initialization complete")):(await t.sendInitializeResettable(e,it),m.info("[LSP] initialize response received"),n(),t.sendInitialized())}async startLegacy(e,t){let n=this.messageHandle;n.sendInitialize(e,1),n.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:L,method:b.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{n.onIndexingProgressUpdate(o),n.onInitializationCompleted(i)},"LSP initialization",it),n.sendInitialized(t)}withResettableTimeout(e,t,n){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${n}ms`))},n)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){m.debug(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,n)=>{let i=O(n)?n:{};m.debug(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:L,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(b.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(b.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(b.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(b.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(b.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(b.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Ci(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){m.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=n.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),m.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return m.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];m.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=n.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),m.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),n=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,n),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,h)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}getOldDepsForModule(e,t,n){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=n.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,n){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||n(i,e[i])}makeDeleteEntry(e,t){return new Si({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Fo(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new $o([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let i=new Map(n.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=Zi(fh.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Zi(fh.join(t,"default/openharmony/ets/api")),o=Zi(fh.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case b.HOVER:this.stdHandle.sendLspRequest(b.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:L,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:L,id:e.id,error:{code:-32603,message:t.message}}));break;case b.DEFINITION:this.stdHandle.sendLspRequest(b.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:L,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:L,id:e.id,error:{code:-32603,message:t.message}}));break;case b.REFERENCES:this.stdHandle.sendLspRequest(b.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:L,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:L,id:e.id,error:{code:-32603,message:t.message}}));break;default:m.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!kP(e)){m.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case b.DID_OPEN:this.handleDidOpenNotification(e);break;case b.DID_CHANGE:this.handleDidChangeNotification(e);break;case b.DID_CLOSE:this.handleDidCloseNotification(e);break;case b.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case b.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case b.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:m.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){m.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){m.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){m.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(b.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(b.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Yr from"fs";import*as ct from"path";import{createHash as Cj}from"crypto";import{EventEmitter as kj}from"events";var Zd=class extends kj{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),n=new Set(this.watchers.keys());for(let i of t)n.has(i)||this.watchFile(i);for(let i of n)t.has(i)||(this.unwatchFile(i),m.info(`[ConfigFileWatcher] Stopped watching: ${i}`));m.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Yr.existsSync(t)){m.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Yr.watch(t,n=>{n==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",n=>{m.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${n.message}`)}),m.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(n){m.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${n instanceof Error?n.message:String(n)}`)}}emitModuleAddedEvents(t,n){for(let i of t){let o=ct.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:n,moduleName:i.name})}}emitModuleRemovedEvents(t,n){for(let i of t){let o=ct.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:n,removedModuleName:i.name})}}emitModuleRenamedEvents(t,n){for(let i of t){let o=ct.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,n){for(let i of t){let o=ct.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){m.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,m.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=gt(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return m.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=ct.join(this.projectRoot,G.OH_PACKAGE_JSON5);Yr.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=ct.resolve(this.projectRoot,o.srcPath),a=ct.join(s,G.OH_PACKAGE_JSON5);Yr.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return ct.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=Yr.readFileSync(t,"utf-8");return Cj("sha256").update(n).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let n=this.computeFileHash(t);n&&this.contentHashes.set(t,n);let i=Yr.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{m.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(n){m.error(`[ConfigFileWatcher] Failed to watch ${t}: ${n instanceof Error?n.message:String(n)}`)}}unwatchFile(t){let n=this.watchers.get(t);n&&(n.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){m.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){m.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),m.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:ct.basename(t),relativePath:ct.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),m.info("[ConfigFileWatcher] All watchers stopped")}};import*as xn from"fs";import*as Zt from"path";import{createHash as Rj}from"crypto";import{EventEmitter as Dj}from"events";var Qd=class extends Dj{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=Zt.join(t,ka)}dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!xn.existsSync(this.depMapDir)){m.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=xn.watch(this.depMapDir,{recursive:!0},(t,n)=>this.onDirEvent(t,n)),this.dirWatcher.on("error",t=>{m.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){m.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),m.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return ge(Zt.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===G.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Ei)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Zt.join(this.depMapDir,n);xn.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,m.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Zt.join(this.depMapDir,G.OH_PACKAGE_JSON5),n=Zt.join(this.depMapDir,Ei),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:(E.assertModuleName(s.name),Zt.join(this.depMapDir,s.name,G.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!xn.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),m.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Zt.join(this.depMapDir,Ei);try{let n=gt(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return m.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of n)i.add(o.info.newName);return i}emitIncrementalReload(t,n,i,o,s){m.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(m.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){m.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(n,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){m.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return ge(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let n=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:n,bySrcPath:i}}detectModuleRenames(t,n,i,o){for(let[s,a]of t){let c=n.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=(E.assertModuleName(a.name),Zt.join(this.depMapDir,a.name,G.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),m.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=n.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),m.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,i){for(let[o]of t)i.has(o)||n.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,n,i){for(let[o]of t)if(!i.has(o)&&!n.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=(E.assertModuleName(o),Zt.join(this.depMapDir,o,G.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),n=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);m.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(n,o,a,c),this.detectAddedModules(o,n,c),this.detectRemovedModules(n,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=xn.readFileSync(t,"utf-8");return Rj("sha256").update(n).digest("hex")}catch{return null}}};import*as Er from"fs";import*as eu from"path";import{EventEmitter as xj}from"events";var mh={Created:1,Changed:2,Deleted:3},Ij=new Set(["oh_modules","node_modules","build",".hvigor",".git",".idea",".cxx",".preview"]);function Aj(r){let e=r.replace(/\\/g,"/");return e.endsWith("/ets")&&e.includes("/src/")}var tu=class extends xj{projectRoot;debounceMs;pollMs;sourceDirs=[];watchers=new Map;snapshot=new Map;debounceTimer=null;pollInterval=null;initialScanDone=!1;constructor(e,t=500,n=1e4){super(),this.projectRoot=e,this.debounceMs=t,this.pollMs=n}start(){if(this.sourceDirs=this.discoverSourceDirs(),this.sourceDirs.length===0){m.warn("[SourceFileWatcher] No src/main/ets dir found, skip watching");return}this.refreshSnapshot(),this.initialScanDone=!0;for(let e of this.sourceDirs)this.addSourceDirWatcher(e);this.pollInterval=setInterval(()=>this.scanAndEmit(),this.pollMs),m.info(`[SourceFileWatcher] Started, watching ${this.sourceDirs.length} source dir(s), ${this.snapshot.size} ets file(s)`)}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);for(let[,e]of this.watchers)e.close();this.watchers.clear(),this.snapshot.clear(),this.initialScanDone=!1,m.info("[SourceFileWatcher] Stopped")}addSourceDirWatcher(e){if(!this.watchers.has(e))try{let t=Er.watch(e,{recursive:!0},(n,i)=>this.onFsEvent(i));t.on("error",n=>{m.error(`[SourceFileWatcher] watch error for ${e}: ${n.message}`)}),this.watchers.set(e,t)}catch(t){m.error(`[SourceFileWatcher] Failed to watch ${e}: ${t instanceof Error?t.message:String(t)}`)}}refreshSourceDirs(){if(!this.initialScanDone)return;let e=this.discoverSourceDirs(),t=new Set(this.sourceDirs),n=new Set(e),i=e.filter(s=>!t.has(s)),o=[...t].filter(s=>!n.has(s));if(!(i.length===0&&o.length===0)){for(let s of i)this.addSourceDirWatcher(s);for(let s of o){let a=this.watchers.get(s);a&&(a.close(),this.watchers.delete(s))}this.sourceDirs=e,this.refreshSnapshot(),m.info(`[SourceFileWatcher] Module dirs changed: +${i.length} -${o.length}, now ${this.sourceDirs.length} source dir(s)`)}}discoverSourceDirs(){let e=[];return this.collectSourceDirs(eu.resolve(this.projectRoot),e,new Set,new Set),e}collectSourceDirs(e,t,n,i){let o;try{o=Er.realpathSync(e)}catch{return}if(i.has(o))return;i.add(o);let s;try{s=Er.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of s){if(!a.isDirectory()||Ij.has(a.name))continue;let c=eu.resolve(e,a.name);if(!Aj(c)){this.collectSourceDirs(c,t,n,i);continue}n.has(c)||(n.add(c),t.push(c))}}onFsEvent(e){!e||typeof e!="string"||e.replace(/\\/g,"/").toLowerCase().endsWith(".ets")&&this.scheduleScan()}scheduleScan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scanAndEmit()},this.debounceMs)}scanAndEmit(){if(!this.initialScanDone)return;let e=this.diffScan();e.length>0&&this.emit("sourceChanged",{changes:e})}refreshSnapshot(){let e=new Map;for(let t of this.sourceDirs)this.collectEtsFiles(t,e);this.snapshot=e}diffScan(){let e=new Map;for(let n of this.sourceDirs)this.collectEtsFiles(n,e);let t=[];for(let[n,i]of e){let o=this.snapshot.get(n);o?(o.mtimeMs!==i.mtimeMs||o.size!==i.size)&&t.push({uri:Mt(n),type:mh.Changed}):t.push({uri:Mt(n),type:mh.Created})}for(let[n]of this.snapshot)e.has(n)||t.push({uri:Mt(n),type:mh.Deleted});return this.snapshot=e,t}collectEtsFiles(e,t){this.collectEtsFilesInto(e,t,new Set)}collectEtsFilesInto(e,t,n){let i;try{i=Er.realpathSync(e)}catch{return}if(n.has(i))return;n.add(i);let o;try{o=Er.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of o){let a=eu.resolve(e,s.name);if(s.isDirectory()){this.collectEtsFilesInto(a,t,n);continue}!s.isFile()||!s.name.toLowerCase().endsWith(".ets")||this.recordSnapshot(a,t)}}recordSnapshot(e,t){let n;try{n=Er.statSync(e)}catch{return}t.set(e,{mtimeMs:n.mtimeMs,size:n.size})}};import{spawn as Tj}from"child_process";var $P=["install","--all"];function jP(r,e){let t=r.split(/\r?\n/),n=t.pop()??"";for(let i of t)i&&(m.info("[ohpm] %s",i),e?.(i));return n}async function Nj(r,e,t,n,i){return new Promise(o=>{m.info("[ohpm] spawning: %s %s %s, cwd=%s",r,e,$P.join(" "),t);let s=Tj(r,[e,...$P],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),a="",c="";s.stdout?.on("data",l=>{a=jP(a+l.toString(),i)}),s.stderr?.on("data",l=>{c=jP(c+l.toString(),i)}),s.on("close",l=>{a&&(m.info("[ohpm] %s",a),i?.(a)),c&&(m.info("[ohpm] %s",c),i?.(c)),m.info("[ohpm] process exited, code=%s",l),o({exitCode:l??-1})}),s.on("error",l=>{m.error("[ohpm] process error: %s",l.message),o({exitCode:-1})})})}async function HP(r,e,t,n,i){try{if(!t)return m.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!n)return m.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o}=await Nj(t,n,r,e,i);return o===0?(m.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(m.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),!1)}catch(o){return m.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var UP={UNINITIALIZED:-32099,UNKNOWN:-32e3},Da=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,UP.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,UP.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Wo=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;sourceFileWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;get aceServerPid(){return this.lspProxy?.lspPid??null}constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[],t){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e,t)}catch(n){throw m.error(`[ArktsLspManager] start() synchronous failure: ${n instanceof Error?n.message:String(n)}`),n}}sendNotification(e){if(!this.lspProxy){m.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){m.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,n,i,o,s,a,c){if(m.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return m.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let l=s?.skipHvigorSync===!0,d=await Oc(e,async()=>await HP(e,t,n??"",i??"",a)?l?(m.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Sw(e,t,n??"",o??"",c)?(m.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(m.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(m.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return d.acquired?d.result:(m.info("[ArktsLspManager] 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}async performDispose(){try{this.configWatcher?.stop()}catch(e){m.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){m.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}try{this.sourceFileWatcher?.stop()}catch(e){m.warn(`[ArktsLspManager] sourceFileWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.sourceFileWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){m.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e,t){let n=new Xd(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol,this.config.nodePath,this.config.useSocket??!1);n.setOnMessage(i=>this.handleLspMessage(i)),n.start(e,i=>this.handleLspInitialized(i),t),this.lspProxy=n}handleLspInitialized=e=>{if(this.isInitialized=e,e)m.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.startSourceFileWatcher(),this.onMessage({jsonrpc:L,method:b.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();m.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?Da.uninitialized(t):Da.unknown();this.onMessage({jsonrpc:L,method:b.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(m.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:L,method:b.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Zd(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Qd(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){m.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let n=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:L,method:b.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:n}})}),this.depMapWatcher.start())}startSourceFileWatcher(){this.sourceFileWatcher||(this.sourceFileWatcher=new tu(this.config.workspaceRoot),this.sourceFileWatcher.on("sourceChanged",e=>{if(!this.lspProxy){m.warn("[ArktsLspManager] LspServerProxy not initialized, skip didChangeWatchedFiles");return}this.sendNotification({jsonrpc:L,method:b.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:e.changes}}),m.info(`[ArktsLspManager] Notified didChangeWatchedFiles: ${e.changes.length} change(s)`)}),this.sourceFileWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){m.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),e.kind!==4&&this.sourceFileWatcher?.refreshSourceDirs(),this.onConfigChanged?.()}};var _j=10080*60*1e3,Mj=7200*60*1e3,Oj=120*1e3,Vo=class r{manager=null;get aceServerPid(){return this.manager?.aceServerPid??null}initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodePath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;onInitProgress=null;onDepParseProgress=null;useStandardProtocol=!0;useSocket;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:b.HOVER,definition:b.DEFINITION,declaration:b.DECLARATION,references:b.REFERENCES,implementation:b.IMPLEMENTATION,completion:b.COMPLETION,signatureHelp:b.SIGNATURE_HELP,documentHighlight:b.DOCUMENT_HIGHLIGHT};constructor(e,t,n,i,o,s=!1){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=n,this.nodeMaxOldSpaceSize=i,this.nodePath=o,this.useSocket=s}setOnConfigChanged(e){this.onConfigChangedCallback=e}setOnInitProgress(e){this.onInitProgress=e}setOnDepParseProgress(e){this.onDepParseProgress=e}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:n}=this.resolveProjectAndDeveco();this.useStandardProtocol=n;let i=Ie(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Ku(s,_j,"[ArkTS-Check]"),Ku(o,Mj,"[ArkTS-Check]")}),$c(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;g.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${n}, useSocket=${this.useSocket}`),this.manager=new Wo({sdkPath:l,arktsLangServerPath:t,workspaceRoot:ge(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:n,nodePath:this.nodePath,useSocket:this.useSocket}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,h)=>{this.initResolve=d,this.initReject=h,this.armInitTimer(it),this.manager.start([],this.onDepParseProgress??void 0).catch(y=>{let D=y instanceof Error?y:new Error(String(y));this.failInit(D)})})}resolveProjectAndDeveco(){let e=kr(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let n=tc(t);return{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol:n}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let n=Mt(e),i=await Nt.promises.readFile(e,"utf8"),s=`deveco.apptool.${je.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,n,i,s):this.checkFileLegacy(t,e,n,i,s)}async checkFileStandard(e,t,n,i){g.debug(`textDocument/didOpen uri=${t} content_len=${n.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:n,languageId:i,version:++this.documentVersion}});try{g.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return Lj(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,n,i,o){let s=n;e.registerDiagnosticCallback(n);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},Oj);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.debug(`textDocument/didOpen(legacy) uri=${n} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:n,text:i,languageId:o,version:i.length},editorFiles:[n],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(n,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],n=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1342
|
+
`):"No valid .ets files"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,n),this.formatCallResult(t,n))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let n=this.resolveSingleFile(t.file);if(!n)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${t.file}`}],isError:!0};let i=r.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(n,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(b.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let n=t instanceof Error?t.message:String(t);return g.error(`handleWorkspaceSymbol failed: ${n}`),{content:[{type:"text",text:`workspaceSymbol failed: ${n}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(b.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e}`}],isError:!0};g.info(`handleDocumentSymbol: file=${t}`);try{let n=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(b.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){let i=n instanceof Error?n.message:String(n);return g.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a .ets file: ${e.file}`}],isError:!0};g.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(b.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?b.INCOMING_CALLS:b.OUTGOING_CALLS,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){let i=n instanceof Error?n.message:String(n);return g.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async withOpenFile(e,t){let n=Mt(e),i=await Nt.promises.readFile(e,"utf8"),s=`deveco.apptool.${je.extname(e).replace(/^\./,"")||"plaintext"}`;g.debug(`withOpenFile didOpen uri=${n} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,text:i,languageId:s,version:++this.documentVersion}});try{return await t(n)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}resolveSingleFile(e){let t=je.isAbsolute(e)?e:je.join(this.projectPath,e);return!Nt.existsSync(t)||!Nt.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP is initializing, please retry later":this.projectPath?"LSP not initialized":"No project path configured; set the PROJECT_PATH parameter"}],isError:!0}}collectValidFiles(e,t){let n=je.resolve(this.projectPath),i=[];for(let o of e){let s=je.resolve(je.isAbsolute(o)?o:je.join(n,o));if(!Nt.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Nt.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`Not a .ets file: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,n){for(let i of e){await Gg(500);try{let o=await this.checkFile(i);n.push(Fj(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let n=[];e.length>0&&n.push(e.join(`
|
|
1343
|
+
`)),t.length>0&&n.push(t.join(`
|
|
1344
|
+
`));let i=n.join(`
|
|
1345
|
+
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="No diagnostics collected"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.handleIndexingProgress(t.params);break;case Yi.INDEXING_PROGRESS_UPDATE:this.handleIndexingProgress(t.params);break;case b.PROGRESS:this.handleProgressNotification(t.params);break;case"arkts/initialized":{g.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";g.error(`LSP initialization failed: ${i}`);let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":g.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleIndexingProgress(e){let t=e;if(t?.current!=null&&t?.total!=null&&t.total>0){let n=Math.round(t.current/t.total*100),i=`indexing ${t.current}/${t.total} modules`+(t.moduleName?` (${t.moduleName})`:"");this.onInitProgress?.(i,n)}this.initResolve&&this.armInitTimer(it)}handleProgressNotification(e){let t=e?.value;if(t&&(t.kind==="report"||t.kind==="begin")){let n=typeof t.percentage=="number"?Math.round(t.percentage):null,i=t.message??(n!==null?`${n}%`:"indexing");this.onInitProgress?.(i,n)}this.initResolve&&this.armInitTimer(it)}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let n=this.popDiagnosticWaiter(t);if(!n&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;n=this.popDiagnosticWaiter(s)}if(!n)return;if(typeof e.errorMessage=="string"){g.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),n.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;g.debug(`diagnostics received uri=${t} count=${o}`),n.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=je.join(Qr(),"ArkTSCheck"),n=je.join(t,"mapping-config.properties"),i=qg(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=je.join(t,"lsp-log",String(i),o),a=je.join(t,"lsp-index",String(i));return Nt.mkdirSync(s,{recursive:!0}),Nt.mkdirSync(a,{recursive:!0}),{logPath:Ie(s),indexPath:Ie(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function Lj(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function Fj(r,e){if(Array.isArray(e))return e.length===0?`${r} => no diagnostics`:`${r} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${r} diagnostic failed, error_message: ${t}`}return`${r} => diagnostic failed, result: ${JSON.stringify(e)}`}import*as In from"fs";import*as ki from"path";import{z as hh}from"zod";function Go(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function ru(r,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${r} failed: ${t}`),{content:[{type:"text",text:`${r} failed: ${t}`}],isError:!0}}var $j=500,qo=class{manager;constructor(e){this.manager=e}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:hh.object({files:hh.array(hh.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Go();let t=[],n=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1346
|
+
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await Hj($j);try{let l=await this.checkFile(c);n.push(jj(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1347
|
+
`)),n.length>0&&s.push(n.join(`
|
|
1326
1348
|
`));let a=s.join(`
|
|
1327
|
-
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=vt(e),r=await Nr.promises.readFile(e,"utf8"),i=es(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=yn.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=yn.resolve(yn.isAbsolute(o)?o:yn.join(r,o));if(!Nr.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Nr.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!qr(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Nr.realpathSync(s))}catch{i.push(s)}}return i}};function fT(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 hT(n){return new Promise(e=>setTimeout(e,n))}import*as wi from"fs";import*as oc from"path";var vi=class n{manager;static FEATURE_METHOD_MAP={hover:v.HOVER,definition:v.DEFINITION,declaration:v.DECLARATION,references:v.REFERENCES,implementation:v.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return gi();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 i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=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(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return ic(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(v.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return gi();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};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(v.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return ic("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return gi();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};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return ic("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(v.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}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(v.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=vt(e),i=await wi.promises.readFile(e,"utf8"),o=es(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=oc.isAbsolute(e)?e:oc.join(this.manager.projectRoot,e);return!wi.existsSync(t)||!wi.statSync(t).isFile()||!qr(t)?null:t}};import{spawn as gT}from"child_process";import*as ac from"fs";import*as pv from"path";var yT=30*1e3,vT=30*1e3,sc=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Dr;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{u.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),u.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),u.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};this.client=new Ar(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(v.INITIALIZE,i,Ve),u.info("[ClangdLspProxy] initialize response received"),this.sendNotification(v.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),u.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(v.HOVER,e)}async definition(e){return this.sendLspRequest(v.DEFINITION,e)}async declaration(e){return this.sendLspRequest(v.DECLARATION,e)}async references(e){return this.sendLspRequest(v.REFERENCES,e)}async implementation(e){return this.sendLspRequest(v.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(v.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(v.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(v.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(v.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(v.DID_OPEN,e)}sendDidChange(e){this.sendNotification(v.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(v.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){u.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){u.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,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},vT);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}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(v.SHUTDOWN,null,3e3).catch(e=>{u.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(v.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){u.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=${de(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];u.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=gT(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=xn(this.config.workspaceRoot),t=St(e),r=pv.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.5-Test.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=yT){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);u.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):u.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&&e.error!==null){let i=e.error;u.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case v.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case v.PROGRESS:this.onMessage({jsonrpc:x,method:v.PROGRESS,params:e.params});break;case v.WINDOW_SHOW_MESSAGE:u.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case v.WINDOW_LOG_MESSAGE:u.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:x,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 i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;u.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:x,method:v.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{ac.existsSync(this.config.logPath)||ac.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)),St(r)}}catch{}return e}};import*as Do from"path";import*as su from"fs";var Ro=class n{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 clangdPid(){return this.proxy?.clangdPid??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){u.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.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,r,i,o){if(u.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return u.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(gr(e).length===0)return u.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await hs(e,a?async()=>(u.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,i));return c.acquired?c.result:(u.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,r,i){try{return await km(e,t,r,i),u.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return u.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}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(Ve);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Wt(this.config.workspaceRoot);this.resolvedRoot=e?Se(e):Se(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();ws(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";u.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??Do.dirname(Gr(this.resolvedRoot));try{su.mkdirSync(i,{recursive:!0})}catch(s){u.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}u.info(`[ClangdLspManager] clangdPath: ${r}`),u.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),u.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new sc({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.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,u.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";u.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(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){u.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case v.DID_OPEN:this.proxy.sendDidOpen(i);break;case v.DID_CHANGE:this.proxy.sendDidChange(i);break;case v.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}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){u.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Do.join(lr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Do.join(e,"lsp-log",t);return su.mkdirSync(r,{recursive:!0}),Se(r)}catch{return"auto"}}};function mv(n){let e=ys(n);return u.info(`[SyncGuard] ${e.reason}`),e}var hv=(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))(hv||{}),Ut=3,au=600*1e3,cu=100,cc=["ohpm","hvigor","dep-parse","lsp-init"],fv={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},To=15,lc=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir;constructor(e={}){this.config=e,zr(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Wt(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,this.cppCustomCompileCommandsDir=Ps(this.config.cppCompileCommandsPath),h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCustomCompileCommandsDir='${this.cppCustomCompileCommandsDir??"(none)"}'`),this.server=new wT({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=tu(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||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). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. 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:we.object({target:we.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:we.object({files:we.array(we.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){h.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=we.object({file:we.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:we.number().describe("Line number (0-based)"),character:we.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));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:we.object({query:we.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:we.object({file:we.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:we.object({file:we.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:we.number().describe("Line number (0-based)"),character:we.number().describe("Character offset in the line (0-based)"),direction:we.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Qo(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await xp(e,Kr(this.nodePath)),h.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>cu)return h.warn(`check tool called with ${t.length} files (max: ${cu})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${cu}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=bT(t);o.length>0&&h.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.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),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1349
|
+
`).trim();return!o&&n.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Mt(e),n=await In.promises.readFile(e,"utf8"),i=rc(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:n,languageId:i,version:n.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let n=ki.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=ki.resolve(ki.isAbsolute(o)?o:ki.join(n,o));if(!In.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!In.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!qn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(In.realpathSync(s))}catch{i.push(s)}}return i}};function jj(r,e){if(Array.isArray(e))return e.length===0?`${r} => no diagnostics`:`${r} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${r} diagnostic failed, error_message: ${t}`}return`${r} => diagnostic failed, result: ${JSON.stringify(e)}`}function Hj(r){return new Promise(e=>setTimeout(e,r))}import*as Jo from"fs";import*as nu from"path";var zo=class r{manager;static FEATURE_METHOD_MAP={hover:b.HOVER,definition:b.DEFINITION,declaration:b.DECLARATION,references:b.REFERENCES,implementation:b.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Go();let n=this.resolveSingleFile(t.file);if(!n)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=r.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(n,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return ru(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(b.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 Go();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 n=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(b.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){return ru("documentSymbol",n)}}async handleCallHierarchy(e){if(!this.manager.ready)return Go();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 n=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){return ru("callHierarchy",n)}}async fetchCallHierarchyResult(e,t){let n=await this.manager.sendFeatureRequest(b.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(n);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let n of e)t.push(...await this.fetchIncomingCalls(n));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(b.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let n=Mt(e),i=await Jo.promises.readFile(e,"utf8"),o=rc(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${n} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:n,text:i,languageId:o,version:i.length}}});try{return await t(n)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:n}}})}}resolveSingleFile(e){let t=nu.isAbsolute(e)?e:nu.join(this.manager.projectRoot,e);return!Jo.existsSync(t)||!Jo.statSync(t).isFile()||!qn(t)?null:t}};import{spawn as Uj}from"child_process";import*as ou from"fs";import*as BP from"path";var Bj=30*1e3,Wj=30*1e3,iu=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new kn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{m.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),m.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),m.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let n={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new Cn(n),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(b.INITIALIZE,i,it),m.info("[ClangdLspProxy] initialize response received"),this.sendNotification(b.INITIALIZED,{}),t=!0}catch(n){this.lastStartErrorMessage=n instanceof Error?n.message:String(n),m.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(b.HOVER,e)}async definition(e){return this.sendLspRequest(b.DEFINITION,e)}async declaration(e){return this.sendLspRequest(b.DECLARATION,e)}async references(e){return this.sendLspRequest(b.REFERENCES,e)}async implementation(e){return this.sendLspRequest(b.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(b.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(b.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(b.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(b.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(b.DID_OPEN,e)}sendDidChange(e){this.sendNotification(b.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(b.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){m.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){m.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let n=this.diagnosticWaiters.get(t);clearTimeout(n.timer),this.diagnosticWaiters.delete(t)}return new Promise((n,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},Wj);this.diagnosticWaiters.set(t,{resolve:n,reject:i,timer:o})})}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(b.SHUTDOWN,null,3e3).catch(e=>{m.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(b.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){m.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=${ge(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];m.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=Uj(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=Zi(this.config.workspaceRoot),t=Ut(e),n=BP.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.10-Test.1"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:n}],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,n=Bj){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,n);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:String(n);m.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):m.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 n=t;if(e.error!==void 0&&e.error!==null){let i=e.error;m.warn(`[ClangdLspProxy] LSP error id=${n}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(n,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(n,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case b.PROGRESS:this.onMessage({jsonrpc:L,method:b.PROGRESS,params:e.params});break;case b.WINDOW_SHOW_MESSAGE:m.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case b.WINDOW_LOG_MESSAGE:m.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:L,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),n=this.diagnosticWaiters.get(t);if(!n&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;n=this.diagnosticWaiters.get(s),n&&this.diagnosticWaiters.delete(s)}else n&&this.diagnosticWaiters.delete(t);if(!n)return;clearTimeout(n.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;m.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),n.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:L,method:b.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{ou.existsSync(this.config.logPath)||ou.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(n)&&(n=n.slice(1)),Ut(n)}}catch{}return e}};import*as xa from"path";import*as gh from"fs";var Ia=class r{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 clangdPid(){return this.proxy?.clangdPid??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){m.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.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,n,i,o){if(m.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return m.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ln(e).length===0)return m.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await Oc(e,a?async()=>(m.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>r.executeCompileNative(e,t,n,i));return c.acquired?c.result:(m.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,n,i){try{return await kw(e,t,n,i),m.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return m.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}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(it);try{this.startProxy()}catch(n){this.failInit(n instanceof Error?n:new Error(String(n)))}})}startProxy(){let e=kr(this.config.workspaceRoot);this.resolvedRoot=e?Ie(e):Ie(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();$c(t);let n=this.config.clangdPath;if(!n){let s="clangd not found (install DevEco Studio / CLT)";m.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??xa.dirname(Gn(this.resolvedRoot));try{gh.mkdirSync(i,{recursive:!0})}catch(s){m.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}m.info(`[ClangdLspManager] clangdPath: ${n}`),m.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),m.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new iu({clangdPath:n,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.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,m.info("[ClangdLspManager] clangd initialized");let n=this.initResolve;this.clearInitHandlers(),n?.()}else{let n=t??this.proxy?.consumeStartErrorMessage()??"unknown error";m.error(`[ClangdLspManager] clangd initialization failed: ${n}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${n}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,n=t.method;if(!n){m.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(n){case b.DID_OPEN:this.proxy.sendDidOpen(i);break;case b.DID_CHANGE:this.proxy.sendDidChange(i);break;case b.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(n,i)}}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){m.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=xa.join(Qr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,n=xa.join(e,"lsp-log",t);return gh.mkdirSync(n,{recursive:!0}),Ie(n)}catch{return"auto"}}};function WP(r){let e=Lc(r);return m.info(`[SyncGuard] ${e.reason}`),e}var GP=(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))(GP||{}),Pr=3,yh=600*1e3,wh=100,su=["ohpm","hvigor","dep-parse","lsp-init"],VP={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},Aa=15,au=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir=null;cppCustomDirResolvedFor="";constructor(e={}){this.config=e,zn(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=kr(t);g.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,g.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new Vj({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=uh(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||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). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. 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:De.object({target:De.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:De.object({files:De.array(De.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=De.object({file:De.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:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:n,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:n,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));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:De.object({query:De.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:De.object({file:De.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:De.object({file:De.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:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)"),direction:De.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=tc(e);return g.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await Vg(e,Zn(this.nodePath)),g.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}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>wh)return g.warn(`check tool called with ${t.length} files (max: ${wh})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${wh}.`}],isError:!0};let{etsFiles:n,cppFiles:i,unsupported:o}=qj(t);o.length>0&&g.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];n.length>0&&this.mergeCheckResult(await this.callArktsCheck(n),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1328
1350
|
`),s.join(`
|
|
1329
1351
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1330
|
-
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return
|
|
1331
|
-
`)}buildPipelineLine(e){return`Pipeline: ${
|
|
1332
|
-
`);i&&(e.isError?t.push(i):r.push(i))}assertRestartAllowed(e){if(e==="arkts"||e==="all"){let t=this.projectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`ArkTS project state: ${this.describeArktsState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}if(e==="cpp"||e==="all"){let t=this.cppProjectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`C++ project state: ${this.describeCppState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}return null}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";if(r==="cpp"&&!this.cppEnabled)return{content:[{type:"text",text:"C++ LSP is disabled, cannot restart. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};let i=this.assertRestartAllowed(r);return i||(this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~${To}s.`}]})}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}async start(){await this.detectSocketAvailable(),this.registerTools(),this.toolRouter.registerToServer(this.server);let e=new ST;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Fp();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Wt(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Wt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Wt(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject())return;if(this.arktsPipelineStartedAt=Date.now(),this.arktsInitProgress={phase:"ohpm",detail:"installing dependencies",percent:null,startedAt:Date.now(),updatedAt:Date.now()},!await this.ensureProjectSynced()){this.arktsInitProgress=null;return}this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsInitProgress={phase:"dep-parse",detail:"parsing dependency map",percent:null,startedAt:Date.now(),updatedAt:Date.now()},this.arktsCheckTool=this.createArktsCheckTool();let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,this.arktsInitProgress=null,h.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){h.error("LSP initialization failed:",t);let r=V(t),i=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.arktsInitProgress=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,r,i)}}createArktsCheckTool(){let e=new hi(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize,this.nodePath,this.socketAvailable);return e.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0}),e.setOnInitProgress((t,r)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="lsp-init",this.arktsInitProgress.detail=t,this.arktsInitProgress.percent=r,this.arktsInitProgress.updatedAt=Date.now())}),e.setOnDepParseProgress((t,r)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="dep-parse",this.arktsInitProgress.detail=`${t}/${r} modules`,this.arktsInitProgress.percent=r>0?Math.round(t/r*100):null,this.arktsInitProgress.updatedAt=Date.now())}),e}async ensureProjectSynced(){let e=this.config.projectPath,t=mv(e),r=xo.existsSync(Si.join(e,"oh-package-lock.json5")),i=xo.existsSync(Si.join(e,"oh_modules"))&&xo.readdirSync(Si.join(e,"oh_modules")).length>0;if(r&&i)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return h.info(`Sync check: skipHvigor=${o}, ohpm install forced (lock=${r}, ohModules=${i}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:o})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="ohpm",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},i=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="hvigor",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},o=await fi.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t,r,i);return this.handleSyncResult(o)}handleSyncResult(e){switch(e.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let t=Date.now()-this.syncSkipStartedAt,r=Math.round(t/1e3);return t>=au?(h.error(`Sync skipped for ${r}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${e.reason}, resetting to IDLE for retry (elapsed ${r}s / ${au/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${e.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${e.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){h.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}if(this.cppCustomCompileCommandsDir){h.info(`[Cpp] Custom compile_commands.json configured, skipping compileNative sync (dir: ${this.cppCustomCompileCommandsDir})`),this.cppHasNoCppCode=!1,await this.initCppLsp(e);return}this.cppProjectState=1;let t=gr(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(o=>o.name).join(", ")}`);let r=Rm(e),i=!r.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${i}, reason=${r.reason}`),await this.runSyncCpp(e,{skipCompileNative:i})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new Ro({workspaceRoot:e,clangdPath:this.clangdPath??"",...this.cppCustomCompileCommandsDir?{compileCommandsDir:this.cppCustomCompileCommandsDir}:{}});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new yi(this.cppLspManager),this.cppLspTool=new vi(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r);let i=V(r),o=this.cppLspManager?.clangdPid??null;this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5,await this.trackInit("init_cpp",t,!1,i,o)}}async trackInit(e,t,r,i,o){if(!this.config.telemetry)return;let s="unknown";if(o!==null){let l=await et(o);l!==null&&(s=ne(Number(l)*1024))}let a={event:b.McpToolCall,subAction:e,mcpMemory:ne(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:r,error_code:i};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let r=await Ro.handleSyncCppProject(e,this.sdkPath,this.nodePath,this.hvigorJsPath,t);switch(r.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let i=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(i/1e3);return i>=au?(h.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${r.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${r.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),_p(),Op()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function bT(n){let e=[],t=[],r=[];for(let i of n)Si.extname(i).toLowerCase()===".ets"?e.push(i):qr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function lu(n={}){return new lc(n)}import*as du from"fs";import*as No from"path";import{spawn as ET}from"child_process";async function gv(n){zr(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o,nodePath:s}=await PT(n),a=IT(e,t,r,i,o,s);h.info("ace-server started, bridging stdio (initialize is left to the client)"),AT(a),await pu(a.pid,uu("--arkts",n))}function uu(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function pu(n,e){let t="unknown";if(n!==null){let i=await et(n);i!==null&&(t=ne(Number(i)*1024))}let r={event:b.ServeLsp,args:e,lspMemory:t};await k.track(r)}async function PT(n){let e=await P.new(),t;if(n.projectPath)t=Se(No.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=Zo(process.cwd());t=Se(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=Se(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.arktsLangServerPath;i||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=Cn(i,!0),s=No.join(lr(),"lsp-server",String(Date.now()));du.mkdirSync(s,{recursive:!0});let a=CT(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${i}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a,nodePath:e.nodePath}}function CT(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=kT(n,e),s=Ss(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function kT(n,e){try{let t=[];return new gn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Vt(n).getAllModuleInfo().length}catch{return 0}}function IT(n,e,t,r,i,o){let s=No.join(e,"lspLog");du.mkdirSync(s,{recursive:!0});let a=$i({serverPath:n,lspLogPath:s,serverMaxSize:i,projectPath:t,sdkPath:r}),c=Kr(o);return h.info(`[serve-lsp] spawn: ${c} ${a.join(" ")}`),ET(c,a,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function AT(n){n.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as yv from"fs";import*as vn from"path";import{spawn as DT}from"child_process";async function vv(n){zr(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await RT(n),i=vn.join(t,"compile_commands.json");yv.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=xT(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),LT(o),await pu(o.pid,uu("--cpp",n))}async function RT(n){let e=await TT();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=Se(vn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=Zo(process.cwd());t=Se(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=Se(vn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,i=e.clangdPath,o=Gr(t),s=vn.dirname(o),a=Ps(process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS);return a&&(h.info(`Using custom compile_commands dir: ${a}`),s=a),h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function TT(){try{return await P.new()}catch{let n=Tp();if(!n)return null;try{return P.fromIDE(n)}catch{return null}}}function xT(n,e,t){let r=NT(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),DT(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function NT(n){return[`--compile-commands-dir=${de(n)}`,"--log=info","--pch-storage=memory"]}function LT(n){n.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),n.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),n.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function OT(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=process.env.DEVECO_CLI_CPP_ENABLED!=="false"&&process.env.DEVECO_CLI_CPP_ENABLED!=="0",i=process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS?.trim()||"",o=n,s=await P.new(),a=lu({projectPath:o,sdkPath:s.sdkPath,arktsLangServerPath:s.arktsLangServerPath??void 0,nodePath:s.nodePath,ohpmJsPath:s.ohpmJsPath,hvigorJsPath:s.hvigorJsPath,clangdPath:s.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:r,cppCompileCommandsPath:i||void 0,telemetry:k}),c,l=new Promise(g=>{c=g}),d=async()=>{await a.shutdown(),c()};process.once("SIGINT",d),process.once("SIGTERM",d),process.platform==="win32"&&process.once("SIGBREAK",d);try{await a.start()}catch(g){console.error("Failed to start MCP server:",g instanceof Error?g.message:String(g)),process.exit(1)}await l}var mu=new MT("serve").description("Host bundled auxiliary protocol servers");mu.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await OT()});mu.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await gv({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await vv({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var wv=mu;import{Command as BT,InvalidArgumentError as Pv}from"commander";import{red as WT,dim as VT}from"colorette";import{Command as _T}from"commander";import{cyan as dc,yellow as bi}from"colorette";import*as Sv from"path";function uc(n){return bi(`If you want the latest docs(${n}), please update CLI first: run \`devecocli update\` to update`)}function FT(n){console.log(bi(`Latest docs v${n.version} (apiVersion ${n.apiVersion}) is incompatible with current CLI, and no compatible historical version was found.`)),console.log(uc(n.version))}function $T(n,e,t,r,i){console.log(t?dc(`New docs version ${n} found (current v${e??"none"})`):dc(`Documentation is already up to date v${n}`)),r||console.log(uc(i))}function jT(n,e,t,r){e?console.log(bi(`Docs successfully upgrade to ${n}`)):(console.log(bi(`Docs latest version ${t} is incompatible with your current CLI (v${r})`)),console.log(bi(`Docs has been upgraded to the compatible version ${n}`)),console.log(uc(t)))}async function HT(n){let e=Pt();console.log(dc("Checking for documentation updates..."));let{latest:t,compatible:r}=await qn(e);if(!r){FT(t);return}let i=await Gn(),o=r.version===t.version,s=!i||dr(r.version,i)>0;if(n.check){$T(r.version,i,s,o,t.version);return}if(!n.force&&!s){console.log(bi(`Docs is already up to date v${r.version}`)),o||console.log(uc(t.version));return}console.log(dc(`Downloading documentation package v${r.version}...`)),await Xs({version:r.version,apiVersion:r.apiVersion,dist:r.dist},Sv.join(W(),"doc-data"),"docs-update"),jT(r.version,o,t.version,mt())}var UT=new _T("update").description("Update documentation to the latest compatible version").option("--force","Force re-download even if up to date").option("--check","Check for updates without installing").action(async n=>{await HT(n)}),bv=UT;async function fu(n,e){let t=Date.now();try{let r=await e();return await Ev(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await Ev(n,Date.now()-t,!1,i),r}}async function Ev(n,e,t,r){await k.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function GT(n){return n instanceof Error&&(n.name==="CacheDirError"||n.name==="DocPathSafetyError")}function hu(n){console.error(WT(qT(n))),process.exitCode=1}function qT(n){let e=n instanceof Error?n.message:String(n);return GT(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}function Cv(...n){return e=>{if(!n.includes(e))throw new Pv(`Allowed values: ${n.join(", ")}`);return e}}function zT(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Pv("Must be a positive integer.");return e}var JT=Cv("json","default"),YT=Cv("json","default");function KT(n){let e=n.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function XT(n){for(let e=0;e<n.length;e++){let t=n[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<n.length-1&&console.log()}}var Lo=new BT("docs").description("HarmonyOS documentation commands (search, read, catalog, update)");Lo.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)","all").option("--format <fmt>","Output format (default, json)",JT,"default").option("--limit <n>","Max number of results",zT,10).action(async(n,e)=>{let t={event:b.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await fu(t,async()=>{let r=KT(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Ys(),s=o.CATALOG_NAMES;if(i&&s&&!s.includes(i))throw new Error(`Invalid catalog "${e.catalog}". Allowed: all, ${s.join(", ")}`);let a=await o.createDocsEngine({cacheDir:W()});try{let c=await a.search({keywords:r,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):XT(c)}finally{await a.close()}})}catch(r){hu(r)}});Lo.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:b.DocOperation,subAction:"read",documentId:e};try{await fu(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await Ys()).createDocsEngine({cacheDir:W()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(r){hu(r)}});Lo.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",YT,"default").action(async n=>{let e={event:b.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await fu(e,async()=>{let r=await(await Ys()).createDocsEngine({cacheDir:W()});try{let i=await r.catalog();if(n.format==="json")console.log(JSON.stringify(i.map(o=>({name:o.nodeId,title:o.nodeName})),null,2));else for(let o of i)console.log(` ${o.nodeId.padEnd(20)} ${VT(o.nodeName)}`)}finally{await r.close()}})}catch(t){hu(t)}});Lo.addCommand(bv);var kv=Lo;import{Command as Hx}from"commander";import{Command as ZT,InvalidArgumentError as QT,Option as gu}from"commander";import ex from"ora";function tx(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new QT("depth must be a non-negative integer");return e}function rx(n){let e=[];(n.type||n.id)&&e.push(n.type?n.id?`${n.type}#${n.id}`:n.type:`#${n.id}`),e.push(n.bounds?`[${n.bounds.join(",")}]`:"[]"),n.text&&e.push(`"${JSON.stringify(n.text).slice(1,-1)}"`);let t=[];return n.clickable&&t.push("clickable"),n.longClickable&&t.push("longClickable"),n.scrollable&&t.push("scrollable"),n.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function Iv(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${rx(i)}`),i.children.length>0&&t.push(...Iv(i.children,e+1).split(`
|
|
1352
|
+
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return g.warn(`ArkTS check rejected: project is DISCOVERING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS check rejected: project is SYNCING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let n=t.file,i=t.line,o=t.character;return typeof n!="string"||typeof i!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(n,e,async()=>{if(n.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:n,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:n,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,n=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!n){let a=this.describeArktsState(),c=this.describeCppState();return g.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(n)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,n=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${n}:${i}:${o}`}mergeSymbolItems(e,t,n){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),n.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return`syncing (retry ${Aa}s)`;case 3:return`initializing (retry ${Aa}s)`;case 5:return`error (${this.initRetryCount}/${Pr})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${Pr})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;return typeof t!="string"?{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0}:this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,n=e.line,i=e.character,o=e.direction;return typeof t!="string"||typeof n!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:o!=="incoming"&&o!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:n,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:n,character:i,direction:o}))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return g.warn(`ArkTS ${e} rejected: project is DISCOVERING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS ${e} rejected: project is SYNCING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return g.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e=this.arktsInitProgress?this.buildInitRetryMessage():`Config file changed, resyncing project.${this.buildRetrySuffix()}`,t="config changed",this.configChangedTriggeredResync=!1):(e=this.arktsInitProgress?this.buildInitRetryMessage():`ArkTS project detected, syncing.${this.buildRetrySuffix()}`,t="initial"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:`Initializing.${this.buildRetrySuffix()}`}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Pr?(g.error(`Init retry limit reached (${this.initRetryCount}/${Pr}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Pr}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${Pr})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${Aa}s. Expected total: 30s\u201310min (depends on project size).`}buildInitRetryMessage(){let e=this.arktsInitProgress;if(!e)return`ArkTS init in progress.${this.buildRetrySuffix()}`;let t=su.indexOf(e.phase)+1,n=Math.round((Date.now()-e.startedAt)/1e3),i=this.arktsPipelineStartedAt?Math.round((Date.now()-this.arktsPipelineStartedAt)/1e3):n,o=e.percent!==null?` (${e.percent}%)`:"";return[`ArkTS init [${t}/4] ${VP[e.phase]}: ${e.detail}${o} [${n}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${Aa}s. Expected total: 30s\u201310min (depends on project size).`].join(`
|
|
1353
|
+
`)}buildPipelineLine(e){return`Pipeline: ${su.map(n=>{let i=su.indexOf(n)<su.indexOf(e),o=n===e,s=VP[n];return i?`${s} \u2713`:o?`${s}(\u2026)`:s}).join(" \u2192 ")}`}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return g.warn(`C++ ${e} rejected: C++ project is ${GP[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppEnabled?this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}:{content:[{type:"text",text:"C++ LSP is disabled. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};default:return g.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,n){return e.endsWith(".ets")?this.routeArktsRequest(t,n):qn(e)?this.routeCppRequest(t,n):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=Pr?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Pr}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Pr}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Pr})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,n){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1354
|
+
`);i&&(e.isError?t.push(i):n.push(i))}assertRestartAllowed(e){if(e==="arkts"||e==="all"){let t=this.projectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`ArkTS project state: ${this.describeArktsState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}if(e==="cpp"||e==="all"){let t=this.cppProjectState;if(t!==4&&t!==0&&t!==5)return{content:[{type:"text",text:`C++ project state: ${this.describeCppState()}, sync/init in progress, restart unavailable (would interrupt the current flow). Wait for the state to become ready and retry other tools directly\u2014no restart needed. restart is only available in ready/idle/error states.`}],isError:!0}}return null}async handleRestartCall(e){let t=e.target,n=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";if(n==="cpp"&&!this.cppEnabled)return{content:[{type:"text",text:"C++ LSP is disabled, cannot restart. Set DEVECO_CLI_CPP_ENABLED=true to enable."}],isError:!0};let i=this.assertRestartAllowed(n);return i||(this.restartProject(n),{content:[{type:"text",text:`MCP server is restarting in-place (${n==="all"?"ArkTS + C++":n==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~${Aa}s.`}]})}restartProject(e){g.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.cppEnabled&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>g.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}async start(){await this.detectSocketAvailable(),this.registerTools(),this.toolRouter.registerToServer(this.server);let e=new Gj;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Yg();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let n=kr(t);n?(g.info(`Detected project path from client root: ${n}`),this.config.projectPath=n):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{g.error("shutdown failed:",n),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?kr(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=kr(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject())return;if(this.arktsPipelineStartedAt=Date.now(),this.arktsInitProgress={phase:"ohpm",detail:"installing dependencies",percent:null,startedAt:Date.now(),updatedAt:Date.now()},!await this.ensureProjectSynced()){this.arktsInitProgress=null;return}this.ensureCppProjectReady().catch(t=>{g.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsInitProgress={phase:"dep-parse",detail:"parsing dependency map",percent:null,startedAt:Date.now(),updatedAt:Date.now()},this.arktsCheckTool=this.createArktsCheckTool();let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,this.arktsInitProgress=null,g.info("Project fully initialized, check tool is available"),await this.trackInit("init_arkts",e,!0,null,this.arktsCheckTool?.aceServerPid??null)}catch(t){g.error("LSP initialization failed:",t);let n=Z(t),i=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.arktsInitProgress=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,n,i)}}createArktsCheckTool(){let e=new Vo(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize,this.nodePath,this.socketAvailable);return e.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0}),e.setOnInitProgress((t,n)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="lsp-init",this.arktsInitProgress.detail=t,this.arktsInitProgress.percent=n,this.arktsInitProgress.updatedAt=Date.now())}),e.setOnDepParseProgress((t,n)=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="dep-parse",this.arktsInitProgress.detail=`${t}/${n} modules`,this.arktsInitProgress.percent=n>0?Math.round(t/n*100):null,this.arktsInitProgress.updatedAt=Date.now())}),e}async ensureProjectSynced(){let e=this.config.projectPath,t=WP(e),n=Ta.existsSync(Ko.join(e,"oh-package-lock.json5")),i=Ta.existsSync(Ko.join(e,"oh_modules"))&&Ta.readdirSync(Ko.join(e,"oh_modules")).length>0;if(n&&i)return t.required?(g.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(g.info(`Sync skipped: ${t.reason}`),!0);let o=!t.required;return g.info(`Sync check: skipHvigor=${o}, ohpm install forced (lock=${n}, ohModules=${i}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:o})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let n=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="ohpm",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},i=s=>{this.arktsInitProgress&&(this.arktsInitProgress.phase="hvigor",this.arktsInitProgress.detail=s,this.arktsInitProgress.percent=null,this.arktsInitProgress.updatedAt=Date.now())},o=await Wo.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t,n,i);return this.handleSyncResult(o)}handleSyncResult(e){switch(e.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let t=Date.now()-this.syncSkipStartedAt,n=Math.round(t/1e3);return t>=yh?(g.error(`Sync skipped for ${n}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${e.reason}, resetting to IDLE for retry (elapsed ${n}s / ${yh/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${e.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${e.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppEnabled){g.info("[Cpp] C++ LSP disabled by config, skipping initialization"),this.cppHasNoCppCode=!0,this.cppProjectState=4;return}if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}resolveCppCustomDir(){let e=`${this.config.cppCompileCommandsPath??""}|${this.config.projectPath??""}`;return e!==this.cppCustomDirResolvedFor&&(this.cppCustomDirResolvedFor=e,this.cppCustomCompileCommandsDir=Bc(this.config.cppCompileCommandsPath,this.config.projectPath),this.cppCustomCompileCommandsDir&&g.info(`[Cpp] Custom compile_commands dir resolved: ${this.cppCustomCompileCommandsDir}`)),this.cppCustomCompileCommandsDir}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}let t=this.resolveCppCustomDir();if(t){g.info(`[Cpp] Custom compile_commands.json configured, skipping compileNative sync (dir: ${t})`),this.cppHasNoCppCode=!1,await this.initCppLsp(e);return}this.cppProjectState=1;let n=ln(e);if(n.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${n.length} C++ module(s): ${n.map(s=>s.name).join(", ")}`);let i=Iw(e),o=!i.required;g.info(`[Cpp] C++ sync check: skipCompileNative=${o}, reason=${i.reason}`),await this.runSyncCpp(e,{skipCompileNative:o})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new Ia({workspaceRoot:e,clangdPath:this.clangdPath??"",...this.cppCustomCompileCommandsDir?{compileCommandsDir:this.cppCustomCompileCommandsDir}:{}});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new qo(this.cppLspManager),this.cppLspTool=new zo(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available"),await this.trackInit("init_cpp",t,!0,null,this.cppLspManager?.clangdPid??null)}catch(n){g.error("[Cpp] C++ LSP initialization failed:",n);let i=Z(n),o=this.cppLspManager?.clangdPid??null;this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5,await this.trackInit("init_cpp",t,!1,i,o)}}async trackInit(e,t,n,i,o){if(!this.config.telemetry)return;let s="unknown";if(o!==null){let l=await mt(o);l!==null&&(s=ae(Number(l)*1024))}let a={event:v.McpToolCall,subAction:e,mcpMemory:ae(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:n,error_code:i};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let n=await Ia.handleSyncCppProject(e,this.sdkPath,this.nodePath,this.hvigorJsPath,t);switch(n.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let i=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(i/1e3);return i>=yh?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${n.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${n.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),Kg(),Jg()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function qj(r){let e=[],t=[],n=[];for(let i of r)Ko.extname(i).toLowerCase()===".ets"?e.push(i):qn(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function vh(r={}){return new au(r)}import*as bh from"fs";import*as Na from"path";import{spawn as zj}from"child_process";async function qP(r){zn(!1);let{serverPath:e,logPath:t,projectPath:n,sdkPath:i,serverMaxSize:o,nodePath:s}=await Jj(r),a=Xj(e,t,n,i,o,s);g.info("ace-server started, bridging stdio (initialize is left to the client)"),Zj(a),await Eh(a.pid,Sh("--arkts",r))}function Sh(r,e){return[r,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function Eh(r,e){let t="unknown";if(r!==null){let i=await mt(r);i!==null&&(t=ae(Number(i)*1024))}let n={event:v.ServeLsp,args:e,lspMemory:t};await R.track(n)}async function Jj(r){let e=await P.new(),t;if(r.projectPath)t=Ie(Na.resolve(r.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(r.autoDetect){let c=ec(process.cwd());t=Ie(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=Ie(process.cwd()),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let n=e.sdkPath,i=e.arktsLangServerPath;i||(g.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let o=Mi(i,!0),s=Na.join(Qr(),"lsp-server",String(Date.now()));bh.mkdirSync(s,{recursive:!0});let a=Kj(t,n);return g.info(`projectPath=${t}, sdkPath=${n}, arktsLangServerPath=${i}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:n,serverPath:o,logPath:s,serverMaxSize:a,nodePath:e.nodePath}}function Kj(r,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=t?parseInt(t,10):NaN,i=Number.isFinite(n)&&n>0?n:void 0,o=Yj(r,e),s=jc(o,i);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function Yj(r,e){try{let t=[];return new Ci(r,e).getAllDependencyMap(t).status==="OK"?t.length:new Ar(r).getAllModuleInfo().length}catch{return 0}}function Xj(r,e,t,n,i,o){let s=Na.join(e,"lspLog");bh.mkdirSync(s,{recursive:!0});let a=Ss({serverPath:r,lspLogPath:s,serverMaxSize:i,projectPath:t,sdkPath:n}),c=Zn(o);return g.info(`[serve-lsp] spawn: ${c} ${a.join(" ")}`),zj(c,a,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function Zj(r){r.on("error",e=>{g.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),r.stdout?.on("error",e=>{g.error(`[ace-server] stdout error: ${e.message}`)}),r.stdout?.on("data",e=>process.stdout.write(e)),r.stderr?.on("error",e=>{g.error(`[ace-server] stderr error: ${e.message}`)}),r.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),r.stdin?.on("error",e=>{g.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{r.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),r.kill(),process.exit(0)}),r.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as zP from"fs";import*as Ri from"path";import{spawn as Qj}from"child_process";async function JP(r){zn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:n}=await eH(r),i=Ri.join(t,"compile_commands.json");zP.existsSync(i)||g.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=rH(e,t,n);g.info("clangd started, bridging stdio (initialize is left to the client)"),iH(o),await Eh(o.pid,Sh("--cpp",r))}async function eH(r){let e=await tH();e?.clangdPath||(g.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(r.projectPath)t=Ie(Ri.resolve(r.projectPath)),g.info(`projectPath=specified ('${t}'), no search`);else if(r.autoDetect){let c=ec(process.cwd());t=Ie(c??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=Ie(Ri.resolve(process.cwd())),g.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let n=e.sdkPath,i=e.clangdPath,o=Gn(t),s=Ri.dirname(o),a=Bc(process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS,t);return a&&(g.info(`Using custom compile_commands dir: ${a}`),s=a),g.info(`projectPath=${t}, sdkPath=${n}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}async function tH(){try{return await P.new()}catch{let r=Wg();if(!r)return null;try{return P.fromIDE(r)}catch{return null}}}function rH(r,e,t){let n=nH(e);return g.info(`[serve-lsp-cpp] spawn: ${r} ${n.join(" ")}`),Qj(r,n,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function nH(r){return[`--compile-commands-dir=${ge(r)}`,"--log=info","--pch-storage=memory"]}function iH(r){r.on("error",e=>{g.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),r.stdout?.on("error",e=>{g.error(`[clangd] stdout error: ${e.message}`)}),r.stdout?.on("data",e=>process.stdout.write(e)),r.stderr?.on("error",e=>{g.error(`[clangd] stderr error: ${e.message}`)}),r.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),r.stdin?.on("error",e=>{g.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{r.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),r.kill(),process.exit(0)}),r.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function sH(){let r=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",n=process.env.DEVECO_CLI_CPP_ENABLED!=="false"&&process.env.DEVECO_CLI_CPP_ENABLED!=="0",i=process.env.DEVECO_CLI_CPP_COMPILE_COMMANDS?.trim()||"",o=r,s=await P.new(),a=vh({projectPath:o,sdkPath:s.sdkPath,arktsLangServerPath:s.arktsLangServerPath??void 0,nodePath:s.nodePath,ohpmJsPath:s.ohpmJsPath,hvigorJsPath:s.hvigorJsPath,clangdPath:s.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:n,cppCompileCommandsPath:i||void 0,telemetry:R}),c,l=new Promise(h=>{c=h}),d=async()=>{await a.shutdown(),c()};process.once("SIGINT",d),process.once("SIGTERM",d),process.platform==="win32"&&process.once("SIGBREAK",d);try{await a.start()}catch(h){console.error("Failed to start MCP server:",h instanceof Error?h.message:String(h)),process.exit(1)}await l}var Ph=new oH("serve").description("Host bundled auxiliary protocol servers");Ph.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await sH()});Ph.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async r=>{r.arkts&&r.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),r.arkts?await qP({projectPath:r.projectPath,autoDetect:r.autoDetect}):r.cpp?await JP({projectPath:r.projectPath,autoDetect:r.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var KP=Ph;import{Command as fH,InvalidArgumentError as QP}from"commander";import{red as mH,dim as hH}from"colorette";import{Command as aH}from"commander";import{cyan as cu,yellow as lu}from"colorette";import*as YP from"path";function cH(r){return lu(`If you want the latest docs(${r}), please update CLI first: run \`devecocli update\` to update`)}function lH(r){console.log(lu(`Latest docs v${r.version} (apiVersion ${r.apiVersion}) is incompatible with current CLI.`)),console.log(cH(r.version))}function dH(r,e,t){console.log(t?cu(`New docs version ${r} found (current v${e??"none"})`):cu(`Documentation is already up to date v${r}`))}async function uH(r){let e=$t();console.log(cu("Checking for documentation updates..."));let{latest:t,compatible:n}=await uo(e);if(!n){lH(t);return}let i=await Bi(),o=!i||nn(n.version,i)>0;if(r.check){dH(n.version,i,o);return}if(!r.force&&!o){console.log(lu(`Docs is already up to date v${n.version}`));return}console.log(cu(`Downloading documentation package v${n.version}...`)),await Cl({version:n.version,apiVersion:n.apiVersion,dist:n.dist},YP.join(j(),"doc-data"),"docs-update"),console.log(lu(`Docs successfully upgrade to ${n.version}`))}var pH=new aH("update").description("Update documentation to the latest compatible version").option("--force","Force re-download even if up to date").option("--check","Check for updates without installing").action(async r=>{await uH(r)}),XP=pH;async function Ch(r,e){let t=Date.now();try{let n=await e();return await ZP(r,Date.now()-t,!0,null),n}catch(n){let i=n instanceof Error?n.code??n.name:"UnknownError";throw await ZP(r,Date.now()-t,!1,i),n}}async function ZP(r,e,t,n){await R.track(r,{duration_ms:e,success:t,error_code:n}).catch(()=>{})}function gH(r){return r instanceof Error&&(r.name==="CacheDirError"||r.name==="DocPathSafetyError")}function kh(r){console.error(mH(yH(r))),process.exitCode=1}function yH(r){let e=r instanceof Error?r.message:String(r);return gH(r)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}function eC(...r){return e=>{if(!r.includes(e))throw new QP(`Allowed values: ${r.join(", ")}`);return e}}function wH(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new QP("Must be a positive integer.");return e}var vH=eC("json","default"),bH=eC("json","default");function SH(r){let e=r.map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");return e}function EH(r){for(let e=0;e<r.length;e++){let t=r[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<r.length-1&&console.log()}}var _a=new fH("docs").description("HarmonyOS documentation commands (search, read, catalog, update)");_a.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)","all").option("--format <fmt>","Output format (default, json)",vH,"default").option("--limit <n>","Max number of results",wH,10).action(async(r,e)=>{let t={event:v.DocOperation,subAction:"search",keywords:r,queryLen:r.join(" ").length,catalog:e.catalog??"all"};try{await Ch(t,async()=>{let n=SH(r),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Ec(),s=o.CATALOG_NAMES;if(i&&s&&!s.includes(i))throw new Error(`Invalid catalog "${e.catalog}". Allowed: all, ${s.join(", ")}`);let a=await o.createDocsEngine({cacheDir:j()});try{let c=await a.search({keywords:n,catalog:i,limit:e.limit});e.format==="json"?console.log(JSON.stringify(c,null,2)):EH(c)}finally{await a.close()}})}catch(n){kh(n)}});_a.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{let e=r.trim(),t={event:v.DocOperation,subAction:"read",documentId:e};try{await Ch(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let i=await(await Ec()).createDocsEngine({cacheDir:j()});try{let o=await i.read({relativePath:e});console.log(o)}finally{await i.close()}})}catch(n){kh(n)}});_a.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",bH,"default").action(async r=>{let e={event:v.DocOperation,subAction:"catalog",fmt:r.format??"default"};try{await Ch(e,async()=>{let n=await(await Ec()).createDocsEngine({cacheDir:j()});try{let i=await n.catalog();if(r.format==="json")console.log(JSON.stringify(i.map(o=>({name:o.nodeId,title:o.nodeName})),null,2));else for(let o of i)console.log(` ${o.nodeId.padEnd(20)} ${hH(o.nodeName)}`)}finally{await n.close()}})}catch(t){kh(t)}});_a.addCommand(XP);var tC=_a;import{Command as fU}from"commander";import{Command as xh,InvalidArgumentError as Rh,Option as Ma}from"commander";import Ih from"ora";var nC=["Selector DSL (common cases):"," key=value exact text=Login"," key*=value contains text*=Log"," key^=value prefix text^=Log"," key$=value suffix text$=in"," key/=regex[/flags] regex search text/=^Login$ text/=login/i"," a,b AND text=Login,type=Button"," [n] nth match (at end) text=Login[0] [last]/[-1]"," keys: text key desc id type enabled focused checked selected visible clickable scrollable",' value with , [ ] or quotes -> quote it: text="a,b" text="a[b]"'," regex backslashes must be doubled",' xpath= prefix -> use xpath expression: xpath=//Button[@id="login"]'," base64= prefix -> base64-encoded selector for shell-safe special chars"," shell special chars -> wrap whole selector in quotes, or use base64= prefix"].join(`
|
|
1355
|
+
`);function PH(r){let e=parseInt(r,10);if(!Number.isInteger(e)||e<0||String(e)!==r.trim())throw new Rh("depth must be a non-negative integer");return e}function Dh(r){let e=Number(r);if(!Number.isFinite(e)||e<=0)throw new Rh("timeout must be a positive number");if(e>36e4)throw new Rh("timeout must not exceed 360000ms");return e}function iC(r){let e=[];(r.type||r.id)&&e.push(r.type?r.id?`${r.type}#${r.id}`:r.type:`#${r.id}`),e.push(r.bounds?`[${r.bounds.join(",")}]`:"[]"),r.text&&e.push(`"${JSON.stringify(r.text).slice(1,-1)}"`);let t=[];return r.clickable&&t.push("clickable"),r.longClickable&&t.push("longClickable"),r.scrollable&&t.push("scrollable"),r.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function oC(r,e=0){let t=[],n=" ".repeat(e);for(let i of r)t.push(`${n}${iC(i)}`),i.children.length>0&&t.push(...oC(i.children,e+1).split(`
|
|
1333
1356
|
`));return t.join(`
|
|
1334
|
-
`)}function nx(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function ix(n,e){let t=_n(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));return JSON.stringify(r,null,2)}function ox(n,e){return e.id?ix(n,e.id):e.format==="json"?JSON.stringify(n,null,2):Iv(n)}async function sx(n){nx(n);let e=ex({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await P.new(),o=await nt(i,n.device),s=new tn(i.hdcPath);t=n.mode==="full"?await s.dumpFullTree(o,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(o,n.depth,n.window,n.allWindows)}catch(i){throw e.stop(),new Error(`Failed to dump layout: ${i.message}`,{cause:i})}e.stop();let r=ox(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function ax(n){return{event:b.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function cx(n){let e=ax(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await sx(n)}catch(o){throw r=!1,i=V(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var Av=new ZT("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new gu("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(tx).default(0)).addOption(new gu("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new gu("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await cx(n)});import{Command as lx,Option as dx}from"commander";import{yellow as ux}from"colorette";import px from"ora";var mx=["Id","Name","Pid","DisplayId","Focused"];function fx(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(Xt(mx,t))}async function hx(n){let e=px({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await P.new(),i=await nt(r,n.device);t=await new qt(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(ux(" No windows found."));return}fx(t,n.format)}function gx(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:b.CommandExecuted,args:["ui","window","list",...e]}}async function yx(n){let e=gx(n),t=Date.now(),r=!0,i=null;try{await hx(n)}catch(o){throw r=!1,i=V(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var yu=new lx("window").description("Manage device windows");yu.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new dx("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await yx(n)});import{Command as vx}from"commander";import{green as wx}from"colorette";function Sx(n){return{event:b.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function bx(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function Ex(n){let e=Sx(n),t=Date.now(),r=!0,i=null;try{if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let o=n.display!==void 0?bx(n.display):void 0,s=await P.new(),a=new rn(s),c=a.resolveDestinationPath(n.path),l=await nt(s,n.device);await a.captureToPath(l,c,o),console.log(wx(`Screenshot saved to ${c}`))}catch(o){throw r=!1,i=V(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}}var Dv=new vx("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Required directory or PNG file path; destination must be writable").action(Ex);import{Command as pc,Option as Px}from"commander";import{green as vu,yellow as Cx}from"colorette";import Tv from"ora";var mc=["--device <name|serial>","Target physical device name or serial; required when multiple devices are connected"],xv=["--path <dir|file.mp4>","Required writable destination: existing directory or a new .mp4 file"];function fc(n){return new w("INVALID_ARGUMENT",n)}function Rv(n){if(n!==void 0&&!n.trim())throw fc("--device must not be empty.")}function hc(n,e){let t=n.parent?.opts()?.device;if(Rv(t),Rv(e),t&&e&&t!==e)throw fc(`Conflicting --device values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function Nv(n,e){if(n.parent?.opts()?.path!==void 0)throw fc(`--path is not valid for ui screenrecord ${e}.`)}function Lv(n,e){let t=n.parent?.opts()?.path;if(t!==void 0&&e!==void 0&&t!==e)throw fc(`Conflicting --path values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function gc(n,e){let t=n.parent?.opts();return e.filter(r=>r.value!==void 0||t?.[r.name.slice(2)]!==void 0).map(r=>r.name)}function kx(n,e){return n.getOptionValueSource(e)==="cli"}async function yc(n,e,t){let r={event:b.CommandExecuted,args:["ui","screenrecord",...n,...e]},i=Date.now(),o=!0,s=null;try{await t()}catch(a){throw o=!1,s=V(a),a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await k.track(r,a)}}function Mv(n){if(n.kind==="saved"){console.log(vu(`Saved successfully to ${n.localPath}`));for(let e of n.warnings??[])console.error(Cx(`Warning: ${e}`))}else n.kind==="external-stopped"&&console.log(vu("Recording stopped. View the file in the device gallery; this CLI cannot retrieve it."))}async function Ix(n,e){let t=gc(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await yc([],t,async()=>{let r=hc(e,n.device),i=Lv(e,n.path),o=new wr(await P.new()),s,a;try{a=await o.recordInteractively(r,i,{onStarted:()=>{console.log("Recording... press Ctrl+C to stop and save")},onStopRequested:()=>{s=Tv({text:"Stopping and saving the recording\u2026",color:"cyan"}).start()}})}finally{s?.stop()}Mv(a)})}async function Ax(n,e){let t=gc(e,[{name:"--device",value:n.device},{name:"--path",value:n.path}]);await yc(["start"],t,async()=>{let r=hc(e,n.device),i=Lv(e,n.path);await new wr(await P.new()).startDetached(r,i),console.log(vu("Recording started. Stop with devecocli ui screenrecord stop"))})}async function Dx(n,e){let t=[...gc(e,[{name:"--device",value:n.device}]),...n.force?["--force"]:[]];await yc(["stop"],t,async()=>{let r=hc(e,n.device);Nv(e,"stop");let i=new wr(await P.new()),o=Tv({text:"Stopping recording\u2026",color:"cyan"}).start(),s;try{s=await i.stopRecording(r,n.force??!1)}finally{o.stop()}Mv(s)})}var Rx={recording:"Status: recording - a recording started by this CLI is in progress",busy:"Status: busy - a recording started outside this CLI is in progress",idle:"Status: idle - no recording is in progress"};async function Tx(n,e){let t=[...gc(e,[{name:"--device",value:n.device}]),...kx(e,"format")?["--format"]:[]];await yc(["status"],t,async()=>{let r=hc(e,n.device);Nv(e,"status");let o=await new wr(await P.new()).getRecordingStatus(r);if(n.format==="json"){console.log(JSON.stringify(o));return}console.log(Rx[o.status]),o.status==="idle"&&o.note&&console.log(o.note)})}var Mo=new pc("screenrecord").description("Record the screen of a physical device to an MP4 file").option(...mc).option(...xv).action(Ix);Mo.addCommand(new pc("start").description("Start recording and return immediately (detached)").option(...mc).option(...xv).action(Ax));Mo.addCommand(new pc("stop").description("Stop the current recording and save the file").option(...mc).option("--force","Stop a recording that was not started by this CLI (no download)").action(Dx));Mo.addCommand(new pc("status").description("Show the recording status without changing it").option(...mc).addOption(new Px("--format <format>","Output format").choices(["table","json"]).default("table")).action(Tx));import{Command as Lr}from"commander";function Mr(n,e){let t=[];return"device"in e&&e.device&&t.push("--device"),"id"in e&&e.id&&t.push("--id"),"window"in e&&e.window&&t.push("--window"),"speed"in e&&e.speed&&t.push("--speed"),{event:b.CommandExecuted,args:["ui",n,...t]}}function xx(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return p(`escapeShellText: ${n} -> ${t}`),t}async function Or(n,e,t,r){let i=new it;i.start(n);let o=Date.now(),s=!0,a=null;try{await r(i)}catch(c){throw i.stop(),s=!1,a=V(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await k.track(t,c)}}async function Nx(n,e,t){let r=Mr("click",t);await Or("Executing click...","click failed",r,async i=>{jn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await $t(t.device),{x:a,y:c}=await Hn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await pt(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function Lx(n,e,t){let r=Mr("doubleclick",t);await Or("Executing doubleclick...","doubleclick failed",r,async i=>{jn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await $t(t.device),{x:a,y:c}=await Hn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await pt(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function Mx(n,e,t){let r=Mr("longclick",t);await Or("Executing longclick...","longclick failed",r,async i=>{jn(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await $t(t.device),{x:a,y:c}=await Hn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await pt(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function Ox(n,e,t,r,i){let o=Mr("swipe",i);await Or("Executing swipe...","swipe failed",o,async s=>{Me(n,"x1"),Me(e,"y1"),Me(t,"x2"),Me(r,"y2");let a=Ji(i.speed),{hdcPath:c,deviceId:l}=await $t(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await pt(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function _x(n,e,t,r,i){let o=Mr("fling",i);await Or("Executing fling...","fling failed",o,async s=>{Me(n,"x1"),Me(e,"y1"),Me(t,"x2"),Me(r,"y2");let a=Ji(i.speed),{hdcPath:c,deviceId:l}=await $t(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await pt(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function Fx(n,e,t,r,i){let o=Mr("drag",i);await Or("Executing drag...","drag failed",o,async s=>{Me(n,"x1"),Me(e,"y1"),Me(t,"x2"),Me(r,"y2");let a=Ji(i.speed),{hdcPath:c,deviceId:l}=await $t(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await pt(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function $x(n,e){let t=Mr("dircfling",e);await Or("Executing dircfling...","dircfling failed",t,async r=>{let i=Hs[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Hs).join(", ")}`);let{hdcPath:o,deviceId:s}=await $t(e.device);await pt(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function jx(n,e,t,r){let i=Mr("text",r);await Or("Executing text input...","input failed",i,async o=>{jn(e,t,r.id,r.window,!1),Us(n,"text");let{hdcPath:s,deviceId:a}=await $t(r.device),c=xx(n);if(e!==void 0)await pt(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await Hn(s,a,void 0,void 0,r.id,r.window);await pt(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),o.succeed(`input ${n} at (${l}, ${d})`)}else await pt(s,a,[`uitest uiInput text ${c}`]),o.succeed(`input ${n}`)})}var Ov=new Lr("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Nx),_v=new Lr("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Lx),Fv=new Lr("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(Mx),$v=new Lr("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(Ox),jv=new Lr("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(_x),Hv=new Lr("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(Fx),Uv=new Lr("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action($x),Bv=new Lr("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(jx);var ot=new Hx("ui").description("Inspect and interact with UI on a connected device");ot.addCommand(Av);ot.addCommand(yu);ot.addCommand(Dv);ot.addCommand(Mo);ot.addCommand(Ov);ot.addCommand(_v);ot.addCommand(Fv);ot.addCommand($v);ot.addCommand(jv);ot.addCommand(Hv);ot.addCommand(Uv);ot.addCommand(Bv);var Wv=ot;import{Command as Cw,InvalidArgumentError as _L}from"commander";import{execa as dN}from"execa";import Bt from"fs";import*as Pu from"os";import*as _ from"path";var Ux=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),Bx=/\r/g,Wx=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,Vx=/^<+\s*/,Gx=/\s*>+$/,qx=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/],zx=new Set([1]);function Su(n){if(!n)return"";let e=n.replace(Ux,"").replace(Bx,`
|
|
1357
|
+
`)}function CH(r){if(r.allWindows&&r.window)throw new Error("--all-windows and --window are mutually exclusive.")}function kH(r,e){let t=no(r,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let n=t.map(i=>({...i,children:[]}));return JSON.stringify(n,null,2)}function RH(r,e){return e.id?kH(r,e.id):e.format==="json"?JSON.stringify(r,null,2):oC(r)}async function DH(r){CH(r);let e=Ih({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await P.new(),o=await T(i,r.device),s=new _r(i.hdcPath);t=r.mode==="full"?await s.dumpFullTree(o,r.depth,r.window,r.allWindows):await s.dumpCollapsedTree(o,r.depth,r.window,r.allWindows)}catch(i){throw e.stop(),new Error(`Failed to dump layout: ${i.message}`,{cause:i})}e.stop();let n=RH(t,r);return console.log(n),Buffer.byteLength(n,"utf8")}function xH(r){return{event:v.CommandExecuted,args:["ui","layout",...r.device?["--device"]:[]],mode:r.mode,outputSize:0}}async function IH(r){let e=xH(r),t=Date.now(),n=!0,i=null;try{e.outputSize=await DH(r)}catch(o){throw n=!1,i=Z(o),o}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(e,o)}}var sC=new xh("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new Ma("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(PH).default(0)).addOption(new Ma("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Ma("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async r=>{await IH(r)});function aC(r){let e={id:r.id,type:r.type,text:r.text,bounds:r.bounds,clickable:r.clickable==="true"||void 0,longClickable:r.longClickable==="true"||void 0,scrollable:r.scrollable==="true"||void 0,checkable:r.checkable==="true"||void 0,children:[]};return iC(e)}function rC(r){let e={};return r.id!==void 0&&(e.id=r.id),r.type!==void 0&&(e.type=r.type),r.text!==void 0&&(e.text=r.text),r.bounds!==void 0&&(e.bounds=r.bounds),r.clickable!==void 0&&(e.clickable=r.clickable==="true"),r.longClickable!==void 0&&(e.longClickable=r.longClickable==="true"),r.scrollable!==void 0&&(e.scrollable=r.scrollable==="true"),r.checkable!==void 0&&(e.checkable=r.checkable==="true"),r.checked!==void 0&&(e.checked=r.checked==="true"),e}function Oa(){for(let r of df())console.warn(r)}async function AH(r){if(!r.selector)throw new Error("Provide a selector expression.");let e=Ih({text:"Finding element\u2026",color:"cyan"}).start(),t;try{let n=await P.new(),i=await T(n,r.device);t=await new oo(n.hdcPath).find(i,r.selector,{window:r.window,all:r.all,timeoutMs:r.timeout})}catch(n){throw e.stop(),Oa(),new Error(`Failed to find element: ${n.message}`,{cause:n})}if(e.stop(),Oa(),r.format==="json"){let n=r.all?t.map(i=>rC(i)):rC(t[0]);console.log(JSON.stringify(n,null,2))}else{let n=r.all===!0;for(let i of t){let o=aC(i);console.log(n?`#${i.index} ${o}`:o)}}}var cC=new xh("find").description('Find on-screen element(s) by a selector (e.g. "text=Login,type=Button")').argument("[selector]","Selector DSL, xpath=, or base64= expression").option("--device <name|serial>","Target device (name or serial)").option("--window <windowId>","Target window id").option("--all","Print all matches instead of the first/indexed one").addOption(new Ma("--timeout <ms>","Max wait time in milliseconds for the element to appear").argParser(Dh).default(3e3)).addOption(new Ma("--format <format>","Output format").choices(["default","json"]).default("default")).action(async(r,e)=>{await AH({...e,selector:r})}).addHelpText("after",nC);function TH(r){return aC(r)}async function NH(r){await new Promise(e=>setTimeout(e,r)),console.log(`Waited ${r}ms`)}async function _H(r,e,t,n,i){await r.waitForDisappear(e,t,n,i),console.log(`Element disappeared: ${t}`)}async function MH(r,e,t,n,i){let o=await r.waitForAppearance(e,t,n,i);console.log(TH(o))}async function OH(r,e){if(r.length===0)throw new Error("Usage: ui wait [timeoutMs] | ui wait <selector> [timeoutMs]");let t=r[0];if(/^\d+$/.test(t)){if(e.disappear)throw new Error("--disappear requires a selector.");let a=Dh(t);Oa(),await NH(a);return}let i=t,o=r[1]?Dh(r[1]):3e3,s=Ih({text:"Waiting\u2026",color:"cyan"}).start();try{let a=await P.new(),c=await T(a,e.device),l=new oo(a.hdcPath);e.disappear?await _H(l,c,i,o,e.window):await MH(l,c,i,o,e.window),s.stop(),Oa()}catch(a){throw s.stop(),Oa(),new Error(`Failed to wait: ${a.message}`,{cause:a})}}var lC=new xh("wait").description("Wait: sleep [timeoutMs], or wait for element <selector> [timeoutMs] [--disappear]").argument("[args...]","Args: [timeoutMs] for sleep, or <selector> [timeoutMs] for element wait").option("--disappear","Wait for element to disappear (requires selector)").option("--device <name|serial>","Target device (name or serial)").option("--window <windowId>","Target window id").action(async(r,e)=>{await OH(r,e)}).addHelpText("after",nC);import{Command as LH,Option as FH}from"commander";import{yellow as $H}from"colorette";import jH from"ora";var HH=["Id","Name","Pid","DisplayId","Focused"];function UH(r,e){if(e==="json"){let n=r.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(n,null,2));return}let t=r.map(n=>({cells:[String(n.id),n.name,String(n.pid),String(n.displayId),String(n.focused)],highlight:n.focused}));console.log(jr(HH,t))}async function BH(r){let e=jH({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let n=await P.new(),i=await T(n,r.device);t=await new Nr(n.hdcPath,i).listWindows({all:r.all})}catch(n){throw e.stop(),new Error(`Failed to list windows: ${n.message}`,{cause:n})}if(e.stop(),t.length===0){console.log($H(" No windows found."));return}UH(t,r.format)}function WH(r){let e=[];return r.device&&e.push("--device"),r.format!=="default"&&e.push("--format"),r.all&&e.push("--all"),{event:v.CommandExecuted,args:["ui","window","list",...e]}}async function VH(r){let e=WH(r),t=Date.now(),n=!0,i=null;try{await BH(r)}catch(o){throw n=!1,i=Z(o),o}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(e,o)}}var Ah=new LH("window").description("Manage device windows");Ah.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new FH("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async r=>{await VH(r)});import{Command as GH}from"commander";import{green as qH}from"colorette";function zH(r){return{event:v.CommandExecuted,args:["ui","screenshot",...r.device?["--device"]:[]]}}function JH(r){let e=r.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function KH(r){let e=zH(r),t=Date.now(),n=!0,i=null;try{if(r.device!==void 0&&!r.device.trim())throw new Error("--device must not be empty.");let o=r.display!==void 0?JH(r.display):void 0,s=await P.new(),a=new ni(s),c=a.resolveDestinationPath(r.path),l=await T(s,r.device);await a.captureToPath(l,c,o),console.log(qH(`Screenshot saved to ${c}`))}catch(o){throw n=!1,i=Z(o),o}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(e,o)}}var dC=new GH("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Required directory or PNG file path; destination must be writable").action(KH);import{Command as du,Option as YH}from"commander";import{green as Th,yellow as XH}from"colorette";import pC from"ora";var uu=["--device <name|serial>","Target physical device name or serial; required when multiple devices are connected"],fC=["--path <dir|file.mp4>","Required writable destination: existing directory or a new .mp4 file"];function pu(r){return new S("INVALID_ARGUMENT",r)}function uC(r){if(r!==void 0&&!r.trim())throw pu("--device must not be empty.")}function fu(r,e){let t=r.parent?.opts()?.device;if(uC(t),uC(e),t&&e&&t!==e)throw pu(`Conflicting --device values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function mC(r,e){if(r.parent?.opts()?.path!==void 0)throw pu(`--path is not valid for ui screenrecord ${e}.`)}function hC(r,e){let t=r.parent?.opts()?.path;if(t!==void 0&&e!==void 0&&t!==e)throw pu(`Conflicting --path values: ${JSON.stringify(t)} and ${JSON.stringify(e)}`);return e??t}function mu(r,e){let t=r.parent?.opts();return e.filter(n=>n.value!==void 0||t?.[n.name.slice(2)]!==void 0).map(n=>n.name)}function ZH(r,e){return r.getOptionValueSource(e)==="cli"}async function hu(r,e,t){let n={event:v.CommandExecuted,args:["ui","screenrecord",...r,...e]},i=Date.now(),o=!0,s=null;try{await t()}catch(a){throw o=!1,s=Z(a),a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await R.track(n,a)}}function gC(r){if(r.kind==="saved"){console.log(Th(`Saved successfully to ${r.localPath}`));for(let e of r.warnings??[])console.error(XH(`Warning: ${e}`))}else r.kind==="external-stopped"&&console.log(Th("Recording stopped. View the file in the device gallery; this CLI cannot retrieve it."))}async function QH(r,e){let t=mu(e,[{name:"--device",value:r.device},{name:"--path",value:r.path}]);await hu([],t,async()=>{let n=fu(e,r.device),i=hC(e,r.path),o=new pn(await P.new()),s,a;try{a=await o.recordInteractively(n,i,{onStarted:()=>{console.log("Recording... press Ctrl+C to stop and save")},onStopRequested:()=>{s=pC({text:"Stopping and saving the recording\u2026",color:"cyan"}).start()}})}finally{s?.stop()}gC(a)})}async function eU(r,e){let t=mu(e,[{name:"--device",value:r.device},{name:"--path",value:r.path}]);await hu(["start"],t,async()=>{let n=fu(e,r.device),i=hC(e,r.path);await new pn(await P.new()).startDetached(n,i),console.log(Th("Recording started. Stop with devecocli ui screenrecord stop"))})}async function tU(r,e){let t=[...mu(e,[{name:"--device",value:r.device}]),...r.force?["--force"]:[]];await hu(["stop"],t,async()=>{let n=fu(e,r.device);mC(e,"stop");let i=new pn(await P.new()),o=pC({text:"Stopping recording\u2026",color:"cyan"}).start(),s;try{s=await i.stopRecording(n,r.force??!1)}finally{o.stop()}gC(s)})}var rU={recording:"Status: recording - a recording started by this CLI is in progress",busy:"Status: busy - a recording started outside this CLI is in progress",idle:"Status: idle - no recording is in progress"};async function nU(r,e){let t=[...mu(e,[{name:"--device",value:r.device}]),...ZH(e,"format")?["--format"]:[]];await hu(["status"],t,async()=>{let n=fu(e,r.device);mC(e,"status");let o=await new pn(await P.new()).getRecordingStatus(n);if(r.format==="json"){console.log(JSON.stringify(o));return}console.log(rU[o.status]),o.status==="idle"&&o.note&&console.log(o.note)})}var La=new du("screenrecord").description("Record the screen of a physical device to an MP4 file").option(...uu).option(...fC).action(QH);La.addCommand(new du("start").description("Start recording and return immediately (detached)").option(...uu).option(...fC).action(eU));La.addCommand(new du("stop").description("Stop the current recording and save the file").option(...uu).option("--force","Stop a recording that was not started by this CLI (no download)").action(tU));La.addCommand(new du("status").description("Show the recording status without changing it").option(...uu).addOption(new YH("--format <format>","Output format").choices(["table","json"]).default("table")).action(nU));import{Command as An}from"commander";function Tn(r,e){let t=[];return"device"in e&&e.device&&t.push("--device"),"id"in e&&e.id&&t.push("--id"),"window"in e&&e.window&&t.push("--window"),"speed"in e&&e.speed&&t.push("--speed"),{event:v.CommandExecuted,args:["ui",r,...t]}}function iU(r){let t=`"$(printf '%s' '${Buffer.from(r,"utf8").toString("base64")}' | base64 -d)"`;return f(`escapeShellText: ${r} -> ${t}`),t}async function Nn(r,e,t,n){let i=new vt;i.start(r);let o=Date.now(),s=!0,a=null;try{await n(i)}catch(c){throw i.stop(),s=!1,a=Z(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await R.track(t,c)}}async function oU(r,e,t){let n=Tn("click",t);await Nn("Executing click...","click failed",n,async i=>{co(r,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await fr(t.device),{x:a,y:c}=await lo(o,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Rt(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function sU(r,e,t){let n=Tn("doubleclick",t);await Nn("Executing doubleclick...","doubleclick failed",n,async i=>{co(r,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await fr(t.device),{x:a,y:c}=await lo(o,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Rt(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function aU(r,e,t){let n=Tn("longclick",t);await Nn("Executing longclick...","longclick failed",n,async i=>{co(r,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await fr(t.device),{x:a,y:c}=await lo(o,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Rt(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function cU(r,e,t,n,i){let o=Tn("swipe",i);await Nn("Executing swipe...","swipe failed",o,async s=>{We(r,"x1"),We(e,"y1"),We(t,"x2"),We(n,"y2");let a=Ns(i.speed),{hdcPath:c,deviceId:l}=await fr(i.device),d=["uitest","uiInput","swipe",r,e,t,n];a&&d.push(a),await Rt(c,l,d),s.succeed(`swipe from (${r}, ${e}) to (${t}, ${n})`)})}async function lU(r,e,t,n,i){let o=Tn("fling",i);await Nn("Executing fling...","fling failed",o,async s=>{We(r,"x1"),We(e,"y1"),We(t,"x2"),We(n,"y2");let a=Ns(i.speed),{hdcPath:c,deviceId:l}=await fr(i.device),d=["uitest","uiInput","fling",r,e,t,n];a&&d.push(a),await Rt(c,l,d),s.succeed(`fling from (${r}, ${e}) to (${t}, ${n})`)})}async function dU(r,e,t,n,i){let o=Tn("drag",i);await Nn("Executing drag...","drag failed",o,async s=>{We(r,"x1"),We(e,"y1"),We(t,"x2"),We(n,"y2");let a=Ns(i.speed),{hdcPath:c,deviceId:l}=await fr(i.device),d=["uitest","uiInput","drag",r,e,t,n];a&&d.push(a),await Rt(c,l,d),s.succeed(`drag from (${r}, ${e}) to (${t}, ${n})`)})}async function uU(r,e){let t=Tn("dircfling",e);await Nn("Executing dircfling...","dircfling failed",t,async n=>{let i=ml[r];if(i===void 0)throw new Error(`Invalid direction "${r}". Valid values: ${Object.keys(ml).join(", ")}`);let{hdcPath:o,deviceId:s}=await fr(e.device);await Rt(o,s,["uitest","uiInput","dircFling",i]),n.succeed(`dircfling ${r}`)})}async function pU(r,e,t,n){let i=Tn("text",n);await Nn("Executing text input...","input failed",i,async o=>{co(e,t,n.id,n.window,!1),hl(r,"text");let{hdcPath:s,deviceId:a}=await fr(n.device),c=iU(r);if(e!==void 0)await Rt(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),o.succeed(`input ${r} at (${e}, ${t})`);else if(n.id){let{x:l,y:d}=await lo(s,a,void 0,void 0,n.id,n.window);await Rt(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),o.succeed(`input ${r} at (${l}, ${d})`)}else await Rt(s,a,[`uitest uiInput text ${c}`]),o.succeed(`input ${r}`)})}var yC=new An("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(oU),wC=new An("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(sU),vC=new An("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(aU),bC=new An("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(cU),SC=new An("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(lU),EC=new An("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(dU),PC=new An("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(uU),CC=new An("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(pU);var Xe=new fU("ui").description("Inspect and interact with UI on a connected device");Xe.addCommand(sC);Xe.addCommand(cC);Xe.addCommand(lC);Xe.addCommand(Ah);Xe.addCommand(dC);Xe.addCommand(La);Xe.addCommand(yC);Xe.addCommand(wC);Xe.addCommand(vC);Xe.addCommand(bC);Xe.addCommand(SC);Xe.addCommand(EC);Xe.addCommand(PC);Xe.addCommand(CC);var kC=Xe;import{Command as sk,InvalidArgumentError as lB}from"commander";import{execa as FU}from"execa";import Cr from"fs";import*as Lh from"os";import*as V from"path";var mU=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),hU=/\r/g,gU=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,yU=/^<+\s*/,wU=/\s*>+$/,vU=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/],bU=new Set([1]);function _h(r){if(!r)return"";let e=r.replace(mU,"").replace(hU,`
|
|
1335
1358
|
`).split(`
|
|
1336
|
-
`).map(
|
|
1359
|
+
`).map(SU).map(t=>t.trimEnd()).filter(t=>PU(t));return e.length>0?`${e.join(`
|
|
1337
1360
|
`)}
|
|
1338
|
-
`:""}function
|
|
1339
|
-
[output truncated: exceeded ${
|
|
1340
|
-
`};if(
|
|
1341
|
-
`);if(t.length>1&&t.every(
|
|
1342
|
-
`};let i=[e.slice(0,
|
|
1343
|
-
`);return{jsonText:e.slice(
|
|
1344
|
-
`:""}}function
|
|
1345
|
-
${
|
|
1346
|
-
`;let t=e===void 0?
|
|
1361
|
+
`:""}function SU(r){let e=r.trim();if(!e.startsWith("{"))return r;try{let t=JSON.parse(e);return typeof t.content!="string"||typeof t.messageType!="number"?r:bU.has(t.messageType)?"":t.content}catch{return r}}var RC=50*1024*1024;function AC(r){let e=_h(r).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>RC)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
|
|
1362
|
+
[output truncated: exceeded ${RC} bytes]
|
|
1363
|
+
`};if(Nh(e))return{jsonText:e,diagnostics:""};let t=e.split(`
|
|
1364
|
+
`);if(t.length>1&&t.every(Nh))return{jsonText:JSON.stringify(t.map(o=>JSON.parse(o))),diagnostics:""};let n=CU(e);if(!n)return{jsonText:void 0,diagnostics:`${e}
|
|
1365
|
+
`};let i=[e.slice(0,n.start).trim(),e.slice(n.end).trim()].filter(Boolean).join(`
|
|
1366
|
+
`);return{jsonText:e.slice(n.start,n.end),diagnostics:i?`${i}
|
|
1367
|
+
`:""}}function EU(r){return gU.test(r.trim())}function PU(r){let e=r.trim();return!!e&&!EU(e)&&!vU.some(t=>t.test(e))}function Nh(r){try{return JSON.parse(r),!0}catch{return!1}}function CU(r){for(let e=0;e<r.length;e++){let t=r[e];if(t!=="["&&t!=="{")continue;let i=kU(r,e,t,t==="["?"]":"}");if(i!==-1&&Nh(r.slice(e,i+1)))return{start:e,end:i+1}}}function kU(r,e,t,n){let i=0,o=!1,s=!1;for(let a=e;a<r.length;a++){let c=r[a];if(s){s=!1;continue}if(c==="\\"&&o){s=!0;continue}if(c==='"'){o=!o;continue}if(!o){if(c===t)i++;else if(c===n&&(i--,i===0))return a}}return-1}var DC=["Error","Warning","Suggestion","Info","Off","Unknown"];function TC(r){let e=Mh(r);return{issues:IU(e),summary:RU(r,e)}}function RU(r,e){let t=TU(e);return{filesChecked:NU(r).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Mh(r,e=""){if(Array.isArray(r))return r.flatMap(o=>Mh(o,e));if(!NC(r))return[];let t=Fa(r,["filePath","file","path"])??e,n=DU(r,t);if(n.length>0)return n;let i=xU(r,t);return i?[i]:[]}function DU(r,e){let t=["messages","defects","issues","results","files"];for(let n of t){let i=r[n];if(Array.isArray(i)){let o=i.flatMap(s=>Mh(s,e));if(o.length>0)return o}}return[]}function xU(r,e){let t=Fa(r,["message","description","desc","detail"])??"",n=LU(Fa(r,["rule","ruleId","ruleName"])),i=MU(r,["severity","level"]),o=Fa(r,["filePath","file","path"])??e;if(!(!t&&!n&&i==="Unknown"))return{file:o,line:IC(r,["line","reportLine"]),column:IC(r,["column","reportColumn"]),severity:i,rule:n,message:t}}function IU(r){return[...r].sort((e,t)=>{let n=xC(e.severity)-xC(t.severity);return n===0?AU(e,t):n})}function AU(r,e){let t=r.file.localeCompare(e.file);if(t!==0)return t;let n=(r.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return n!==0?n:(r.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function TU(r){let e=new Map;for(let t of r){let n=t.severity;e.set(n,(e.get(n)??0)+1)}return e}function NU(r){let e=new Set;return Oh(e,r,""),e}function Oh(r,e,t){if(Array.isArray(e)){for(let i of e)Oh(r,i,t);return}if(!NC(e))return;let n=Fa(e,["filePath","file","path"])??t;n&&r.add(n),_U(r,e,n)}function _U(r,e,t){let n=["messages","defects","issues","results","files"];for(let i of n){let o=e[i];if(Array.isArray(o))for(let s of o)Oh(r,s,t)}}function MU(r,e){for(let t of e){let n=r[t];if(typeof n=="string"||typeof n=="number")return OU(n)}return"Unknown"}function OU(r){let e=String(r).normalize("NFKC").trim().toLowerCase();return e==="2"||e==="error"||e==="err"?"Error":e==="1"||e==="warn"||e==="warning"?"Warning":e==="3"||e==="suggest"||e==="suggestion"?"Suggestion":e==="info"||e==="information"?"Info":e==="0"||e==="off"?"Off":"Unknown"}function LU(r){let e=r?.normalize("NFKC").trim();if(e)return e.replace(yU,"").replace(wU,"").toLowerCase()}function xC(r){let e=DC.indexOf(r);return e===-1?DC.length:e}function Fa(r,e){for(let t of e){let n=r[t];if(typeof n=="string")return n}}function IC(r,e){for(let t of e){let n=r[t];if(typeof n=="number")return n}}function NC(r){return typeof r=="object"&&r!==null}var _n=class extends Error{code;constructor(e,t,n){super(t,n),this.name="ValidationError",this.code=e}},_C="deveco-codelinter-",MC=[".ets",".ts",".js"],$a=class r{resolution;cwd;toolProvider;constructor(e,t){this.toolProvider=e,this.resolution=r.resolveWithToolProvider(e),this.cwd=t}get supportsReportOptions(){return!this.resolution.isLegacyStudioArgs}static resolveProjectRoot(e){try{return W.discover(e).rootDir}catch{return e}}async check(e){let t=Cr.mkdtempSync(V.join(Lh.tmpdir(),_C)),n=V.join(t,"report.json");try{let i=r.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i);await rt.warnInvalidBundledLinks(o.projectRoot??i);let s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,n,t,o.projectRoot??i),c=await this.run(a),l=AC(c.stdout),d=l.diagnostics+_h(c.stderr);try{let h=this.readJsonReport(n,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:TC(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let n=e?V.resolve(this.cwd,e):t,i=this.resolveRealPath(n,"Lint path"),o=Cr.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new _n("errorCode",`Lint path must be a file or directory: ${n}`);if(o.isFile()){let a=V.extname(i).toLowerCase();if(!MC.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${MC.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new _n("errorCode",`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let n=e?V.resolve(this.cwd,e):V.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(n,"`--config-path`");if(!Cr.statSync(i).isFile())throw new _n("errorCode",`--config-path must point to a file: ${n}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||V.relative(t.projectRoot,o)!=="")throw new _n("errorCode",`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let n=t?e:V.dirname(e);try{return Cr.realpathSync(W.discover(n).rootDir)}catch{return}}resolveRealPath(e,t){try{return Cr.realpathSync(e)}catch(n){throw new _n("errorCode",`${t} does not exist or cannot be resolved: ${e}`,{cause:n})}}buildNativeArgs(e,t,n,i,o,s){if(this.resolution.isLegacyStudioArgs)return this.buildLegacyNativeArgs(e,t,n,o,s);let a=["--config",n];return e.fix&&a.push("--fix"),e.incremental&&a.push("--incremental"),a.push("--product",e.product,"--format","json","--output",i,t),a}buildLegacyNativeArgs(e,t,n,i,o){let s=String(this.toolProvider.getMaxApiLevel()),a=this.toolProvider.getSdkPlatformVersion(),c=V.join(i,"check-paths.json");Cr.writeFileSync(c,JSON.stringify([t]),"utf8");let l=["--dir",c,"--isTooManyFiles","true","--config",n,"--product",e.product,"--sdkPath",this.toolProvider.sdkPath,"--sdkNumberVersion",s,"--sdkStringVersion",a,"--project",o,"--logPath",V.join(i,"codelinter.log"),"--workdir",V.dirname(this.toolProvider.codelinterPath),"--inIde","true"];return e.fix&&l.push("--fix","true"),e.incremental&&l.push("--incremental","true"),l}async run(e){let t=this.resolution.isLegacyStudioArgs?[this.resolution.argsPrefix[0],...e]:[...this.resolution.argsPrefix,...e],n=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),f(`Executing: ${this.resolution.command} ${t.join(" ")}`),f(`[CodelinterAdapter] Working directory: ${n}`);let i=await FU(this.resolution.command,t,{cwd:n,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Cr.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Cr.existsSync(e)?Cr.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new _n("errorCode","Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=V.resolve(e),n=V.resolve(Lh.tmpdir());!(t.startsWith(`${n}${V.sep}`)||t===n)||!V.basename(t).startsWith(_C)||Cr.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],n=V.normalize(e).split(V.sep).slice(-t.length);return t.every((i,o)=>n[o]?.toLowerCase()===i)}static resolveWithToolProvider(e){let t=r.getSource(e),n=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=r.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c=t==="ide"&&!r.isModernStudioEntry(i),l={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(V.delimiter),DEVECO_SDK_HOME:o},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=n,l.runtimeDirectories=[r.getResultDirectory(i)]),f(`[CodelinterAdapter] Selected ${a} entry: ${i}`),l}static getPathEntries(e,t){let n=[V.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&n.unshift(V.dirname(e.javaPath)),n}static getResultDirectory(e){return V.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as yu,yellow as BC}from"colorette";import{Argument as JU,Command as KU,InvalidArgumentError as On}from"commander";import Ha from"fs";import*as lt from"path";import*as ja from"path";var OC="n/a",LC=/\\/g,$U=/\|/g,jU=/\r?\n/g;function FC(r,e){if(r.issues.length===0)return`No defects found.
|
|
1368
|
+
${Fh(r.summary)}
|
|
1369
|
+
`;let t=e===void 0?r.issues:r.issues.slice(0,e),n=[UU(t),Fh(r.summary)];return e!==void 0&&t.length<r.issues.length&&n.push(HU(r.issues.length,t.length)),`${n.join(`
|
|
1347
1370
|
`)}
|
|
1348
|
-
`}function
|
|
1349
|
-
`)}function
|
|
1350
|
-
`)}function
|
|
1351
|
-
`}function
|
|
1352
|
-
`)}function
|
|
1371
|
+
`}function $C(r,e){return[Fh(r.summary),`Full report: ${$h(e)}`,""].join(`
|
|
1372
|
+
`)}function jC(r){let e=["# CodeLinter report",""];return r.issues.length===0?e.push("No defects found.",""):e.push(...BU(r.issues),""),e.push("## Summary","",...VU(r.summary),""),e.join(`
|
|
1373
|
+
`)}function HC(r){return`${JSON.stringify(r,null,2)}
|
|
1374
|
+
`}function Fh(r){return`Summary: Issues: ${_t(r.issues)} | Errors: ${_t(r.errors)} | Warnings: ${_t(r.warnings)} | Suggestions: ${_t(r.suggestions)} | Files checked: ${_t(r.filesChecked)}`}function HU(r,e){return`Showing ${_t(e)} of ${_t(r)} issues. Use --output-path <path> to write all results.`}function UU(r){let e=["No","File","Line","Column","Severity","Rule","Message"],t=r.map((n,i)=>({cells:qU(n,i+1)}));return["CodeLinter report","",jr(e,t)].join(`
|
|
1375
|
+
`)}function BU(r){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,n]of r.entries())e.push(WU(n,t+1));return e}function WU(r,e){return`| ${[String(e),$h(Mn(r.file)),gu(r.line),gu(r.column),Mn(r.severity),Mn(r.rule),Mn(r.message)].map(GU).join(" | ")} |`}function VU(r){return[`- Issues: ${_t(r.issues)}`,`- Errors: ${_t(r.errors)}`,`- Warnings: ${_t(r.warnings)}`,`- Suggestions: ${_t(r.suggestions)}`,`- Files checked: ${_t(r.filesChecked)}`]}function GU(r){return r.replace(LC,"\\\\").replace($U,"\\|").replace(jU,"<br>")}function qU(r,e){return[String(e),$h(Mn(zU(r.file))),gu(r.line),gu(r.column),Mn(r.severity),Mn(r.rule),Mn(r.message)]}function zU(r){if(!ja.isAbsolute(r))return r;let e=ja.relative(process.cwd(),r);return!e||e.startsWith("..")||ja.isAbsolute(e)?r:e}function $h(r){return r.replace(LC,"/")}function Mn(r){let e=r?.trim();return e||OC}function gu(r){return r===void 0?OC:String(r)}function _t(r){return r.toLocaleString("en-US")}var jh=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function YU(r){let e=r;return r instanceof jh?r.code:e.code??e.name??"UnknownError"}async function UC(r,e,t,n){let i=await mt(process.pid),o=i!==null?ae(Number(i)*1024):"unknown",s={event:v.CheckCommand,args:n,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await R.track(s,a).catch(()=>{})}var XU=/^-?\d+$/;function Hh(){return new KU("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new JU("[path]","File or directory to lint").argParser(r1)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",QU).option("--product <product>","Product name defined in build-profile.json5",e1,"default").option("--format <format>","Report format (choices: default, json)",ZU,"default").option("--output-path <path>","Complete report file or directory",t1).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",n1).action(i1)}function ZU(r){if(r==="default"||r==="json")return r;throw new On("Invalid --format. Expected one of: default, json.")}function QU(r){Uh(r,"--config-path");let e=lt.extname(r).toLowerCase();if(e!==".json"&&e!==".json5")throw new On("`--config-path` must point to a .json or .json5 file.");return r}function e1(r){return WC(r,"product"),r}function t1(r){return Uh(r,"--output-path"),r}function r1(r){return Uh(r,"path"),r}function n1(r){if(WC(r,"limit"),!XU.test(r))throw new On("`--limit` must be a positive integer.");let e=Number.parseInt(r,10);if(e<=0||!Number.isSafeInteger(e))throw new On("`--limit` must be an integer greater than 0.");return e}function WC(r,e){if(r.trim().length===0||qC(r))throw new On(`Invalid --${e} value.`)}function Uh(r,e){let t=`\`${e}\``;if(r.length===0||qC(r))throw new On(`${t} must be a non-empty path without control characters.`)}async function i1(r,e,t){let n=Date.now(),i=["check","lint"];try{let o=process.cwd(),s=await P.new(),a=new $a(s,o),c=a1(s,a,t,e),l=u1(c.outputPath,c.format,o);e.fix&&console.warn(BC("Running codelinter with --fix. Ensure your project source is trusted."));let d=await o1(a,r,e);g1(d.diagnostics),process.exitCode=l1(d,l,c.format,e.limit,o),await UC(n,!0,null,i)}catch(o){let s=YU(o);throw await UC(n,!1,s,i),o}}async function o1(r,e,t){return c1(r,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function s1(r){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>r.getOptionValueSource(e)==="cli").map(([,e])=>e)}function a1(r,e,t,n){let i=s1(t);if(i.length===0||e.supportsReportOptions)return n;let o=an(r.toolchainRoot),s=i.length===1?"option":"options";return console.warn(BC(`Warning: The detected DevEco Studio version is: ${o??"unknown"}. The bundled legacy Code Linter does not support ${s}: ${i.join(", ")}. Action: ignore the unsupported ${s} and continue the lint check with default terminal output.`)),{format:i.includes("--format")?"default":n.format,outputPath:i.includes("--output-path")?void 0:n.outputPath}}async function c1(r,e){let t=new vt;process.stderr.isTTY&&t.start("Checking code...");try{let n=await r.check(e);return t.stop(),n}catch(n){throw t.fail("Code check failed"),n}}function l1(r,e,t,n,i){if(!r.report)return console.error(yu("Failed to generate Code Linter report.")),console.error(yu(r.reportError?.message??"Native JSON report was not generated.")),r.exitCode===0?1:r.exitCode;try{if(e){d1(e,t,r.report);let o=GC(e,i);process.stdout.write($C(r.report,o))}else process.stdout.write(FC(r.report,n));return r.exitCode}catch(o){return console.error(yu("Failed to generate Code Linter report.")),console.error(yu(o.message)),r.exitCode===0?1:r.exitCode}}function d1(r,e,t){Ha.mkdirSync(lt.dirname(r),{recursive:!0});let n=e==="json"?HC(t):jC(t);try{Ha.writeFileSync(r,n,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${r}`,{cause:i}):i}}function u1(r,e,t){if(!r)return;let n=m1(r,t),i=f1(r,n),o=i?lt.join(n,h1(e)):n;if(i||p1(r,e),Ha.existsSync(o))throw new On(`Output file already exists: ${GC(o,t)}`);return o}function p1(r,e){let t=VC(e);if(lt.extname(r).toLowerCase()!==t)throw new On(`--output-path must use the ${t} extension for --format ${e}.`)}function f1(r,e){return Ha.existsSync(e)?Ha.statSync(e).isDirectory():r.endsWith("/")||r.endsWith("\\")||lt.extname(r)===""}function m1(r,e){return lt.resolve(e,r)}function h1(r){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),n=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${i}${VC(r)}`}function VC(r){return r==="json"?".json":".md"}function GC(r,e){let t=lt.relative(e,r);return t&&!t.startsWith("..")&&!lt.isAbsolute(t)?t:r}function g1(r){r&&process.stderr.write(r)}function qC(r){for(let e of r){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as y1}from"execa";import Xr from"fs";import w1 from"os";import*as re from"path";import{fileURLToPath as v1}from"url";var zC=re.join("resources","arkts-check.cjs"),Ua=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files);await rt.warnInvalidBundledLinks(t);let n=this.resolveFiles(t,e.files),i=this.resolveScriptPath(),o=this.buildArgs(i,t,n,e.fix),s=this.buildEnv();f(`Executing: ${this.toolProvider.nodePath} ${o.join(" ")}`);let a=await y1(this.toolProvider.nodePath,o,{cwd:t,env:s,stdout:"pipe",stderr:"pipe",reject:!1});return this.parseResult(a.stdout,a.stderr,a.exitCode??1)}resolveProjectRoot(e,t){if(e){let i=re.resolve(this.cwd,e);if(!Xr.existsSync(i))throw new Error(`Project path not found: ${i}`);if(Xr.statSync(i).isFile()){let s=this.discoverRootFrom(re.dirname(i));if(s)return s;throw new Error(`--project path is a file, not a project root: ${i}
|
|
1353
1376
|
Could not find a project-level build-profile.json5 above it. Pass the project root directory instead.`)}if(this.discoverRootFrom(i)!==i)throw new Error(`Not a valid Harmony project root: ${i}
|
|
1354
|
-
(project-level build-profile.json5 not found).`);return i}if(t&&t.length>0)for(let i of t){let o=
|
|
1377
|
+
(project-level build-profile.json5 not found).`);return i}if(t&&t.length>0)for(let i of t){let o=re.isAbsolute(i)?i:re.resolve(this.cwd,i),s=this.discoverRootFrom(re.dirname(o));if(s)return s}let n=this.discoverRootFrom(this.cwd);if(n)return n;throw new Error("Not in a valid Harmony project directory (project-level build-profile.json5 not found). Run this command inside a project, or pass --project <path>.")}discoverRootFrom(e){try{return W.discover(e).rootDir}catch{return}}resolveFiles(e,t){if(t.length===0)return[];let n=t.map(a=>{if(re.isAbsolute(a))return a;let c=re.resolve(this.cwd,a);return Xr.existsSync(c)?c:re.resolve(e,a)}),i=n.filter(a=>!Xr.existsSync(a));if(i.length>0)throw new Error(`File(s) not found:
|
|
1355
1378
|
`+i.map(a=>` ${a}`).join(`
|
|
1356
|
-
`));let o=
|
|
1379
|
+
`));let o=n.filter(a=>{let c=re.relative(e,a);return c.startsWith("..")||re.isAbsolute(c)});if(o.length>0)throw new Error(`File(s) outside the project root ${e}:
|
|
1357
1380
|
`+o.map(a=>` ${a}`).join(`
|
|
1358
|
-
`));let s=
|
|
1359
|
-
`+
|
|
1360
|
-
`));return s}buildArgs(e,t,
|
|
1361
|
-
Warnings (${
|
|
1362
|
-
`))}await
|
|
1363
|
-
`?(t.push(
|
|
1381
|
+
`));let s=n.filter(a=>Xr.statSync(a).isFile()&&a.endsWith(".ets")&&!a.endsWith(".d.ets"));if(s.length===0)throw new Error(`No .ets files found in the given file(s):
|
|
1382
|
+
`+n.map(a=>` ${a}`).join(`
|
|
1383
|
+
`));return s}buildArgs(e,t,n,i){let o=[e,"--project",t];return o.push(i?"--fix":"--no-fix"),n.length>0&&o.push("--files",...n),o}buildEnv(){return{...process.env,DEVECO_HOME:this.resolveDevecoHome()}}resolveDevecoHome(){let e=this.toolProvider.toolchainRoot;if(w1.platform()==="darwin"&&!Xr.existsSync(re.join(e,"sdk"))){let t=re.join(e,"Contents");if(Xr.existsSync(re.join(t,"sdk")))return t}return e}parseResult(e,t,n){let i=e.trim();if(!i){let o=t.trim();throw new Error(`arkts-check exited with code ${n} but produced no output`+(o?`: ${o}`:""))}try{let o=JSON.parse(i);return{success:o.success??!1,error:o.error,errors:o.errors??[],fixed:o.fixed??[],alsoModified:o.alsoModified??[],summary:{errorCount:o.summary?.errorCount??0,warnCount:o.summary?.warnCount??0,fixedCount:o.summary?.fixedCount??0,checkerDiagCount:o.summary?.checkerDiagCount,fileCount:o.summary?.fileCount??0}}}catch(o){throw new Error(`Failed to parse arkts-check output: ${i.slice(0,500)}`,{cause:o})}}resolveScriptPath(){let e=v1(import.meta.url),t=re.dirname(e);if(e.includes("dist")){let s=re.dirname(t),a=re.join(s,"src",zC);if(Xr.existsSync(a))return a}let n=re.dirname(t),i=re.dirname(n),o=re.join(i,"src",zC);if(Xr.existsSync(o))return o;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as Wh,yellow as Vh,green as JC}from"colorette";import{Command as b1}from"commander";function S1(r){let e=r;return e.code??e.name??"UnknownError"}async function Bh(r,e,t,n){let i=await mt(process.pid),o=i!==null?ae(Number(i)*1024):"unknown",s={event:v.CheckCommand,args:n,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await R.track(s,a).catch(()=>{})}function Gh(){return new b1("arkts").description("Run ArkTS static checks on .ets source files").arguments("[files...]").option("--fix","Auto-fix high-confidence errors before reporting").option("--project <path>","Project root directory (default: auto-detected from cwd)").action(async(r,e)=>{await E1(r,e)})}async function E1(r,e){let t=Date.now(),n=["check","arkts"];try{let i=await P.new(),o=new Ua(i,process.cwd()),s=new vt;process.stderr.isTTY&&s.start("Checking ArkTS...");let a;try{a=await o.check({files:r,fix:e.fix,projectRoot:e.project})}catch(c){throw s.fail("ArkTS check failed"),c}if(a.error&&a.errors.length===0){s.fail("ArkTS check failed"),console.error(Wh(a.error)),process.exitCode=1,await Bh(t,!1,"CheckFailed",n);return}s.stop(),P1(a),await Bh(t,!0,null,n)}catch(i){throw await Bh(t,!1,S1(i),n),i}}function P1(r){let{errorCount:e,warnCount:t,fixedCount:n,fileCount:i}=r.summary;if(C1(r.fixed,n,r.alsoModified),e===0){console.log(JC(`No errors found in ${i} file(s).`)),KC(r.errors);return}k1(r.errors,e,t),process.exitCode=1}function C1(r,e,t){if(r.length!==0){console.log(JC(`\u2713 Auto-fixed ${e} issue(s):`));for(let n of r)console.log(` ${n.file}:${n.line}:${n.column} - ${n.message}`);if(t.length>0){console.log(Vh(`Note: auto-fix also modified ${t.length} file(s) outside the checked list (added missing 'export'):`));for(let n of t)console.log(` ${n}`)}console.log()}}function k1(r,e,t){let n=r.filter(i=>i.severity==="error");console.error(Wh(`ArkTS check found ${e} error(s):`));for(let i of n){let o=i.rule?` (${i.rule})`:"";console.error(Wh(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}KC(r,t)}function KC(r,e){let t=r.filter(i=>i.severity!=="error");if(t.length===0)return;let n=e??t.length;console.warn(Vh(`
|
|
1384
|
+
Warnings (${n}):`));for(let i of t){let o=i.rule?` (${i.rule})`:"";console.warn(Vh(`${i.file}:${i.line}:${i.column} - ${i.severity}: ${i.message}${o}`))}}import{InvalidArgumentError as R1}from"commander";import*as ie from"path";import*as qh from"os";import{readdirSync as D1,existsSync as wu,readFileSync as x1,unlinkSync as I1,copyFileSync as QC,writeFileSync as ek}from"fs";import{execa as A1}from"execa";import{cyan as Te,yellow as tk}from"colorette";import T1 from"ora";var pe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function zh(r){let e=r;return r instanceof pe?r.code:e.code??e.name??"UnknownError"}async function Yo(r,e,t,n){let i=await mt(process.pid),o=i!==null?ae(Number(i)*1024):"unknown",s={event:v.CheckCommand,args:n,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await R.track(s,a).catch(()=>{})}var N1=["default","csv","json"],YC=["default","json"];function _1(r){return[...r].sort((e,t)=>{let n=XC(e),i=XC(t);return n.apiVersion-i.apiVersion||n.suffix.localeCompare(i.suffix)})}function XC(r){let e=r.match(/\((\d+)\)/),t=e?Number(e[1]):0,n=r.lastIndexOf("_"),i=n>=0?r.slice(n+1):r;return{apiVersion:t,suffix:i}}function rk(r){let t=D1(r,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".json")).map(n=>n.name.slice(0,-5));return _1(t)}async function nk(r){if(r=r===void 0?"default":r,!YC.includes(r))throw new Error(`--format must be ${YC.join(" or ")}. got "${r}"`);let e=Date.now(),t=["check","compat","versions"];try{let n=await P.new(),{apiChangeDir:i}=n.getApiscanPaths();f(Te(`[compat:versions] apiChangeDir: "${i}"`));let o=rk(i);if(r==="json")console.log(JSON.stringify({versions:o,count:o.length},null,2));else{if(o.length===0){console.log("No SDK versions available."),await Yo(e,!0,null,t);return}console.log(o.join(`
|
|
1385
|
+
`))}await Yo(e,!0,null,t)}catch(n){let i=zh(n);throw await Yo(e,!1,i,t),n}}var ZC=new Set([".ets",".c",".cpp"]);function M1(r,e){let t=new Set(r.profile.modules.map(s=>s.name)),n=e.filter(s=>!t.has(s));if(n.length===0)return;let i=r.profile.modules.map(s=>s.name).join(", "),o=n.length>1?"are":"is";throw new pe("errorCode",`Module ${n.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function O1(r){for(let e of r){let t=ie.resolve(e);if(!wu(t))throw new pe("errorCode",`File "${e}" does not exist.`);let n=ie.extname(t).toLowerCase();if(!ZC.has(n)){let i=Array.from(ZC).join(", ");throw new pe("errorCode",`Unsupported file extension "${n}" for "${e}". Supported: ${i}.`)}}}function L1(r){let e=[],t=[];for(let n of r)ie.extname(n).toLowerCase()===".ets"?e.push(n):t.push(n);return{arkTs:e,cpp:t}}function F1(r){let e=[],t=[],n="",i=!1,o=0;for(;o<r.length;){let s=r[o];i?{field:n,inQuotes:i,i:o}=$1(r,o,s,n,i):s==='"'?(i=!0,o+=1):s===","?(t.push(n),n="",o+=1):s===`
|
|
1386
|
+
`?(t.push(n),e.push(t),t=[],n="",o+=1):(s==="\r"||(n+=s),o+=1)}return(n.length>0||t.length>0)&&(t.push(n),e.push(t)),e}function $1(r,e,t,n,i){return t!=='"'?{field:n+t,inQuotes:i,i:e+1}:r[e+1]==='"'?{field:n+'"',inQuotes:i,i:e+2}:{field:n,inQuotes:!1,i:e+1}}function j1(r,e){return e.map(t=>{let n=i=>{let o=r.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:n("Api Definition"),language:n("Language"),changeId:n("ChangeId"),changedInSdk:n("Changed in SDK"),affectedVersions:n("Affected Versions"),title:n("Title"),codeLocation:n("Code Location"),changeType:n("Change Type")}})}function H1(r){let e=x1(r,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,n=F1(t);if(n.length<2)return[];let[i,...o]=n;return j1(i,o)}function U1(r,e){let t=r.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let n=t[1].trim();if(ie.isAbsolute(n))return n;let i=ie.join(e,n);return E.ensurePathWithinRoot(e,i)}function B1(r,e){let t=new Map;for(let o of r){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let n=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...n.map(([o])=>o.length));console.log(Te("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${r.length}`);for(let[o,s]of n)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function W1(r,e){if(console.log(),r.length===0){console.log("No API changes detected.");return}let t=r.slice(0,e),n=r.length-t.length;console.log(Te(`Details (showing ${t.length}${n>0?` of ${r.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}n>0&&console.log(tk(` ... and ${n} more. you can re-run with --output-path <dir> to save the full report.`))}function V1(r,e){let t=r.slice(0,e),n=r.length-t.length;console.log(),console.log(JSON.stringify({records:t,count:r.length},null,2)),n>0&&console.log(tk(`... and ${n} more. you can re-run with --output-path <dir> to save the full report.`))}function G1(r,e){let t=[];for(let n of e){let i=r.profile.modules.find(o=>o.name===n);if(!i)throw new pe("errorCode",`Module "${n}" not found in build-profile.json5.`);t.push(ie.resolve(r.rootDir,i.srcPath))}return t}function q1(r,e,t,n){if(!n.sourceVersion||!n.targetVersion)throw new pe("errorCode","source-version and target-version are required.");let i=[r,"--startVersion",n.sourceVersion,"--endVersion",n.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=L1(e),a=d=>ie.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(n.modules&&n.modules.length>0){let o=G1(t,n.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",qh.tmpdir()),i}async function z1(r,e){let t=ie.dirname(e[0]);try{let i=(await A1(r.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(Te("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
|
|
1364
1387
|
`)||process.stdout.write(`
|
|
1365
|
-
`),console.log(
|
|
1388
|
+
`),console.log(Te("[compat:check] === end stdout ==="))),i}catch(n){let i=n;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(Te("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
|
|
1366
1389
|
`)||process.stdout.write(`
|
|
1367
|
-
`),console.log(
|
|
1368
|
-
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function
|
|
1369
|
-
Run \`devecocli compat versions\` to see all available versions.`)}if(
|
|
1370
|
-
`}function TL(n,e,t,r){r===".csv"?yw(n,t):vw(t,Ew(e),"utf8"),p(Pe(`[compat:check] saved report: "${t}"`))}function xL(n,e,t,r){if(r==="json"){let o=Z.basename(n,".csv"),s=Z.join(t,`${o}.json`);return vw(s,Ew(e),"utf8"),p(Pe(`[compat:check] saved report: "${s}"`)),s}let i=Z.join(t,Z.basename(n));return yw(n,i),p(Pe(`[compat:check] saved report: "${i}"`)),i}async function NL(n,e){let t=new tt(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new ce("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function LL(n,e){bL(n,e);let t=U.discover(process.cwd());e.modules&&e.modules.length>0&&aL(t,e.modules),n.length>0&&cL(n);let r=await P.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();p(Pe(`[compat:check] script: "${o}"`));let s=Sw(i);EL(e,s),e.outputPath&&p(Pe(`[compat:check] outputPath: "${e.outputPath}"`));let a=DL(e.outputPath,e.format);return p(Pe(`[compat:check] outputTarget: ${a.kind}`)),RL(a),{project:t,scriptPath:o,target:a,toolProvider:r}}function ML(n,e,t,r){if(t.kind==="file")return TL(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return xL(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new ce("errorCode",`Unexpected output target kind: ${t.kind}`)}async function OL(n,e,t,r,i){let o=iL({text:"Running compatibility check...",color:"cyan"}).start();try{await NL(n.toolProvider,t);let s=wL(n.scriptPath,e,n.project,t);CL(n.scriptPath,s);let a=await SL(n.toolProvider,s),c=fL(a,Lu.tmpdir());if(!c)throw new ce("errorCode","Scanner output format unexpected: missing report path.");p(Pe(`[compat:check] tmp csv: "${c}"`));let l=mL(c),d=ML(c,l,n.target,t.format);kL(c),o.stop(),PL(l,d,t.format,t.limit,n.target.kind),await Ei(r,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=Mu(s);throw await Ei(r,!1,a,i),s}}async function Pw(n,e){let t=Date.now(),r=["check","compat"];try{let i=await LL(n,e);await OL(i,n,e,t,r)}catch(i){let o=Mu(i);throw await Ei(t,!1,o,r),i}}function FL(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new _L(`--limit must be a positive integer (got "${n}")`);return e}var Ou=new Cw("compat").description("Compatibility checking utilities.");Ou.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",FL,100).action(async(n,e)=>{await Pw(n,e)});Ou.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async(n,e)=>{let t=e.optsWithGlobals().format;await bw(t)});var $L=new Cw("check").description("Run DevEco project checks").addCommand(Ou).addCommand(Au()).addCommand(Nu()),kw=$L;import{Command as IO}from"commander";import{green as ip,red as AO}from"colorette";import op from"fs";import lS from"path";import dS from"json5";import{readFileSync as mM}from"fs";import{join as jL}from"path";var me={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},Xe={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:jL(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Ce={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},Dt={FORBIDDEN:403,UNAUTHORIZED:401},C={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},he={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function bc(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function _u(n){let e=n.replace(Xe.TEAM_ID_INVALID_CHARS,"");return`${Xe.CERT_NAME_PREFIX}${e}.cer`}function Pi(n,e,t){if(n===Dt.FORBIDDEN)return e===Ce.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN);if(n===Dt.UNAUTHORIZED)return new Error(C.ERR_UNAUTHORIZED);if(t.includes(Ce.USER_NOT_HARMONY_CODE))return new Error(C.ERR_USER_NOT_HARMONY);if(t.includes(Ce.CERT_LIMIT_CODE))return new Error(C.ERR_CERT_LIMIT_REACHED);let r=HL(t);return new Error(r??C.ERR_DOWNLOAD_CER)}function HL(n){let e=Iw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Iw(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function Iw(n){try{return JSON.parse(n)}catch{return null}}function Fu(n){return JSON.parse(n)}async function Aw(n){let e=`${me.BASE_URL}${me.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:bc(n)});if(t.statusCode!==200)throw Pi(t.statusCode,t.statusText,t.data);return Fu(t.data)?.certList??[]}async function Ec(n,e){return(await Aw(n)).find(r=>r.certName===e)??null}async function $u(n,e){let t=`${me.BASE_URL}${me.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:bc(n),params:{certIds:[e]}});if(r.statusCode!==200)throw Pi(r.statusCode,r.statusText,r.data);return Fu(r.data)?.ret?.code===0}async function ju(n,e,t){let r=`${me.BASE_URL}${me.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Xe.CERT_TYPE_DEBUG},o=await L.postAllowFailure(r,{headers:bc(n),params:i});if(o.statusCode!==200)throw Pi(o.statusCode,o.statusText,o.data);if(!o.data.includes(Ce.SUCCESS_MARKER))throw Pi(void 0,o.statusText,o.data)}async function Hu(n,e){let t=`${me.BASE_URL}${me.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:bc(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw Pi(r.statusCode,r.statusText,r.data);return Fu(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as UL,writeFileSync as BL,existsSync as WL}from"fs";import{dirname as VL}from"path";import{createHash as GL}from"crypto";function qL(n){let e;try{e=new URL(n)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(n)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function Ho(n,e,t){qL(n);let{statusCode:r,statusText:i,buffer:o}=await L.getBinaryAllowFailure(n,{timeout:Xe.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===Dt.FORBIDDEN&&i===Ce.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_DOWNLOAD_CER);if(t){let a=GL("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=VL(e);WL(s)||UL(s,{recursive:!0}),BL(e,o)}import dM from"fs/promises";import{readFileSync as uM}from"fs";import Pc from"path";import Tw from"crypto";import zL from"os";import Uo from"fs/promises";var xw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Dw=["ECC","RSA"],Rw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],JL={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},YL=8,Uu=64,KL=/[\\/:*?"<>|=-]/g,Rt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function XL(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>Uu)throw new Error(`The length of keyAlias cannot exceed ${Uu}`);if(!Dw.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Dw.join(" / ")}`);let e=JL[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function ZL(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!Rw.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Rw.join(" / ")}`)}function QL(n){return Tw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function eM(n){let e=n?.trim()??"";return e&&e.replace(KL,"_").replace(/\.+/g,"_").slice(0,Uu)||Rt.productName}async function Nw(){let n=await P.new();n.assertJava();let e=n.javaPath,t=n.sdkPath;u.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=Pc.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Uo.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function tM(n){let{javaPath:e,jarPath:t}=await Nw(),r=["-jar",t,xw.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return u.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function rM(n){let{javaPath:e,jarPath:t}=await Nw(),r=["-jar",t,xw.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":o);return u.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function nM(n){u.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),XL(n);let e=await tM(n),t=await Hi(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return u.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function iM(n){u.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),ZL(n);let e=await rM(n),t=await Hi(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return u.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function oM(n=YL){return Tw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function sM(){let n=zL.homedir();try{await Uo.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Pc.join(n,".ohos","config");try{await Uo.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return u.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function Te(n,e,t){let r=eM(n),i=Pc.basename(e),o=QL(e),s=`${r}_${i}_${o}=.${t}`,a=await sM();return Pc.join(a,s)}function aM(n){let e;try{e=U.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function cM(n){try{await Uo.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function lM(n){try{await Uo.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Bu(n,e,t){let r=process.cwd(),i=aM(r);await cM(i),u.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=oM(),s=await Te(n??"",i,"p12"),a=await Te(n??"",i,"csr");return console.log("Start generating p12"),await nM({keyAlias:e?.keyAlias??Rt.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??Rt.keyAlg,keySize:e?.keySize??Rt.keySize,keystoreFile:s,keystorePwd:o}),await lM(s),console.log("Start generating csr"),await iM({subject:t?.subject??Rt.csrSubject,outFile:a,keyAlias:t?.keyAlias??Rt.keyAlias,keyPwd:o,signAlg:t?.signAlg??Rt.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??Rt.keyAlias}}var pM=["p12","cer","csr","p7b"];async function Wu(n,e){for(let t of pM){let r=await Te(n,e,t);await dM.rm(r,{force:!0})}}function Vu(n){let e;try{e=uM(n,"utf-8")}catch{throw new Error(C.ERR_CERT_INVALIDATE)}if(!Xe.CERT_PATTERN.test(e))throw new Error(C.ERR_CERT_INVALIDATE)}async function Lw(n,e){return{certPath:await Te(n,e,"cer"),csrPath:await Te(n,e,"csr"),p12Path:await Te(n,e,"p12"),profilePath:await Te(n,e,"p7b")}}async function Gu(n,e){let t=e??"",r=U.discover(process.cwd()).rootDir;await Wu(t,r);let i=_u(n.teamId),o=await Ec(n,i);if(o&&!await $u(n,o.id))throw new Error(C.ERR_DOWNLOAD_CER);let s=await Bu(e),a;try{a=mM(s.csrFilePath,"utf-8")}catch{throw new Error(C.ERR_READ_CSR)}console.log("Start generating certificate"),await ju(n,a,i);let c=await Ec(n,i);if(!c)throw new Error(C.ERR_DOWNLOAD_CER);let l=await Hu(n,c.certObjectId);if(!l)throw new Error(C.ERR_DOWNLOAD_CER);let d=await Te(t,r,"cer");await Ho(l.newUrl,d,l.sha256),Vu(d);let g=await Te(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Lc from"crypto";import Br from"fs";import*as Jw from"path";import OM from"json5";import{execa as Gw}from"execa";import qw from"node-forge";import{createCipheriv as fM,createDecipheriv as hM,pbkdf2Sync as gM,randomBytes as Yu}from"crypto";import{promises as Sn}from"fs";import{dirname as yM,join as Tt}from"path";var Cc=3,Bo=16,vM=1e4,Mw="material",wM=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),$w="aes-128-gcm",wn=12,kc=16,jr=4;function qu(n){return new Uint8Array(Yu(n))}function SM(n){return Yu(n).toString("hex")}function bM(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function Ow(n,e,t=vM,r=Bo){let i=[...n,wM],o=bM(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=gM(a,e,t,r,"sha256");return new Uint8Array(c)}function _w(n,e){let t=Yu(wn),r=fM($w,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(jr+wn+s.length);return c.writeUInt32BE(a,0),t.copy(c,jr),s.copy(c,jr+wn),c}function Fw(n,e){if(e.length<jr+wn+kc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(jr,jr+wn),i=e.subarray(jr+wn,jr+wn+t);if(i.length<kc)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-kc),s=i.subarray(i.length-kc),a=hM($w,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function EM(n){try{await Sn.rm(n,{recursive:!0,force:!0})}catch{}}async function zu(n){let e=await Sn.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return Sn.readFile(Tt(n,t[0]))}async function Ju(n,e){let t=SM(Bo),r=Tt(n,t);return await Sn.writeFile(r,e,{mode:384}),t}var Hr=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=Tt(e,Mw);await EM(t);let r=Tt(t,"ac"),i=Tt(t,"ce");await Sn.mkdir(r,{recursive:!0,mode:448}),await Sn.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<Cc;d++)await Sn.mkdir(Tt(t,"fd",String(d)),{recursive:!0,mode:448});let o=qu(Bo),s=[];for(let d=0;d<Cc;d++)s.push(qu(Bo));let a=qu(Bo),c=Ow(s,o),l=_w(c,a);await Ju(r,o),await Ju(i,l);for(let d=0;d<Cc;d++){let g=Tt(t,"fd",String(d));await Ju(g,s[d])}return a}static async readMaterial(e){let t=Tt(e,Mw),r=Tt(t,"ac"),i=new Uint8Array(await zu(r)),o=[];for(let d=0;d<Cc;d++){let g=Tt(t,"fd",String(d)),y=await zu(g);o.push(new Uint8Array(y))}let s=Tt(t,"ce"),a=await zu(s),c=Ow(o,i),l=Fw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(i=>{t=i}),await r;try{let i=yM(e);try{return await this.readMaterial(i)}catch{return await this.generateMaterial(i)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return _w(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return Fw(r,i).toString("utf8")}};import Ww from"fs";import xc from"path";import DM from"json5";import*as Ic from"fs";import*as jw from"path";function Ac(n){let e=jw.resolve(n);if(!Ic.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Ic.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as ki from"fs";import*as Ze from"path";import{debuglog as Ci}from"util";var Hw={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function PM(n){return Object.prototype.hasOwnProperty.call(Hw,n)}function Dc(n){if(PM(n))return Hw[n]}var Uw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as CM}from"url";var Tc=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function Rc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Bw(n){return n==null||n.length===0}function kM(n){return!Bw(n)}function Ku(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function IM(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function AM(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var Ur=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Ze.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=Ze.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Ze.join(t.sdkPath,"default","sdk-pkg.json"),a=Ac(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Ze.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(ki.existsSync(e))return ki.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=CM(e);if(t.includes("dist")){let s=Ze.dirname(t),a=Ze.dirname(s);return Ze.join(a,"src","resources")}let r=Ze.dirname(t),i=Ze.dirname(r),o=Ze.dirname(i);return Ze.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Ci("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Rc(i)?Object.values(i):[]).filter(Rc).map(a=>new Tc(a));s.forEach(a=>{let c=a.permissionInsteadName;kM(c)&&(a.permissionInsteadName=Dc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Ci(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Rc(o))return;let s=o,a=Ku(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Bw(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Ku(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Ku(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:IM(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Tc;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=AM(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Ze.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!ki.existsSync(t))return;let r;try{r=ki.readFileSync(t,"utf-8")}catch(s){Ci(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Rc(s)){Ci("json object is null");return}i=s}catch(s){Ci(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Ci("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Dc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Dc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Nc(n,e){let t=new Set,r=new Set;Ur.handleSpecificAclPermissions(),Ur.initAclPermission(n,e);for(let i of n.profile.modules){let o=Vw(i,n,e,r,xc.join("src","main"));for(let a of o)t.add(a);let s=Vw(i,n,e,r,xc.join("src","ohosTest"));for(let a of s)t.add(a)}return RM(r),t}function RM(n){if(n.size>0)throw new Error(Uw.DUPLICATE_PERMISSION)}function Vw(n,e,t,r,i){let o=xM(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let y of o){if(typeof y!="object"||y===null)continue;let I=TM(y,"name");I&&s.push(I)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=xc.join(t.sdkPath,"default","sdk-pkg.json"),l=Ac(c),d=Ur.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(y=>{let I=Number(y.minSupportApiLevel);return Number.isFinite(I)&&I<=l}).map(y=>y.permissionName));for(let y of Array.from(a))g.has(y)||a.delete(y);return a}function TM(n,e){let t=n[e];return typeof t=="string"?t:""}function xM(n,e,t){let r=xc.join(n,e.srcPath,t,"module.json5"),i=NM(r);if(i==null)return null;let o=LM(i,"module");return o==null?null:MM(o,"requestPermissions")}function NM(n){try{if(!Ww.existsSync(n))return null;let e=Ww.readFileSync(n,"utf-8");return DM.parse(e)}catch{return null}}function LM(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function MM(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Zu=class{verifyStorePassword(e,t){try{let r=Br.readFileSync(e),i=qw.asn1.fromDer(r.toString("binary"));return qw.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Br.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new Lc.X509Certificate(i).fingerprint256));try{return[this.formatFp(new Lc.X509Certificate(Br.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=Br.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new Lc.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function _M(n){let e=Br.readFileSync(n,"utf-8"),t=FM(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Xu(i["bundle-name"]),expiryDate:$M(r?.validity?.["not-after"]),cerFingerprintInProfile:jM(Xu(i["development-certificate"])),deviceUdidsInProfile:HM(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:UM(r?.acls?.["allowed-acls"]),teamIdInProfile:Xu(i["developer-id"])}}function FM(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function $M(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function jM(n){if(!n)return null;try{let t=new Lc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function HM(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function UM(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function Xu(n){return typeof n=="string"?n:null}var Wo=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#r(r)??n.#n(r)??n.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=U.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([BM(o,a),VM(t.hdcPath)]),d=null;if(zw(c).allExist)try{d=_M(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(o),deviceUdids:l,storePassword:await WM(a,o,c.storeFile),localAclPermissions:[...Nc(s,t)].sort(),hapSignTool:new Zu,profileInfo:d}}static#t(e){return e.force?(p("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:st({force:!0})}):null}static#r(e){let t=zw(e.materialPaths);return t.allExist?null:(p(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:st({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(p("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(p(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(p(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(p(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=qM(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(p(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return zM(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(p("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(p("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(p(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(p("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(p("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return p("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:st({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function BM(n,e){let[t,r,i,o]=await Promise.all([Te(n,e,"p12"),Te(n,e,"csr"),Te(n,e,"cer"),Te(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function WM(n,e,t){let r=Jw.join(n,"build-profile.json5");if(!Br.existsSync(r))return;let i;try{i=OM.parse(Br.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Hr.decryptPassword(a,t)}catch{return}}async function VM(n){p(`Executing: ${n} list targets`);let{stdout:e}=await Gw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1371
|
-
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let
|
|
1372
|
-
`);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let
|
|
1373
|
-
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let
|
|
1374
|
-
`);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function ZM(n,e){let{stdout:t}=await ep(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return QM(t)}function QM(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 bn from"fs";import{createHash as eO}from"crypto";import{debuglog as cr}from"util";import{Buffer as rS}from"buffer";import{createPublicKey as tO,X509Certificate as tp}from"crypto";import{readFileSync as rO}from"fs";import En from"node-forge";async function nS(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(C.DEVICE_LIST_EMPTY);let d=`${me.BASE_URL}${me.PROVISION_ADD_TEST_PATH}`,g=nO(t,r),y=await oO(n,d,a||[],r,s,g,o||[]);if(!y||!y.profileInfo||!y.profileInfo.provisionFileUrl)throw cr("add provision failed, the provision file url is null"),new Error(C.ADD_PROFILE_FAIL);let I=y.profileInfo,z=(await lO(n,I.provisionFileUrl)).urlList,xe=y.profileInfo.id;if(z&&z.length>0){let at=await Lw(t,i),xt=at.profilePath;if(!await dO(z,xt))throw await tS(n,xe),new Error(C.ERROR_WHILE_DOWNLOAD_PROFILE);if(await tS(n,xe),bn.existsSync(at.certPath)&&bn.existsSync(xt)&&bn.existsSync(at.p12Path)){let Gc=bn.readFileSync(at.certPath,"utf8"),qc=bn.readFileSync(xt,"utf8");return uO(qc,Gc,at.p12Path,c,l)||cO(xt),xt}}throw new Error(C.ADD_PROFILE_FAIL)}function nO(n,e){let t=n?`${n}_`:"";return`${iO(`${t}${e}_${e}`)}`}function iO(n){return eO("sha256").update(n).digest("hex").substring(0,16)}async function oO(n,e,t,r,i,o,s){sO(r);let a=np(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw cr("add provision failed: response is null"),new Error(C.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw rp(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw cr(`add provision fail: ${l.data}`),aO(l.data,o),new Error(d.ret?.msg||C.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function rp(n,e,t){return n===Dt.FORBIDDEN?e===Ce.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN):n===Dt.UNAUTHORIZED?new Error(C.ERR_UNAUTHORIZED):t.includes(Ce.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(C.TEST_PROVISION_EXCEEDS_LIMIT):new Error(C.ADD_PROFILE_FAIL)}function sO(n){if(!n||n.trim().length===0)throw new Error(C.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Xe.BUNDLE_NAME_REGEX.test(n))throw new Error(C.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function aO(n,e){if(n.includes(Ce.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(C.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(Ce.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(C.PROFILE_NAME_REPEAT)}async function tS(n,e){if(!e||e.trim().length===0)return;let t=`${me.BASE_URL}${me.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:np(n)});if(r.statusCode!==200)throw rp(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&cr(`delete provision failed: ${r.data}`)}function cO(...n){for(let e of n)try{bn.existsSync(e)&&bn.unlinkSync(e)}catch(t){cr(`delete local sign file error: ${t.message}`)}}async function lO(n,e){let t=`${me.BASE_URL}${me.CERT_DOWNLOAD_URL_PATH}`,r=np(n),i={sourceUrls:e},o=await L.postAllowFailure(t,{headers:r,params:i});if(!o)throw cr("get download list failed: response is null"),new Error(C.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw rp(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw cr("download: The application does not exist"),new Error(s.ret?.msg||C.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function dO(n,e){if(!n||n.length===0)return!1;let t=n[0];return await Ho(t.newUrl,e,t.sha256),!0}function uO(n,e,t,r,i){return pO(n,e),r=r||Xe.TARGET_FRIENDLY_NAME,i=i||"",mO(e,t,r,i),!0}function pO(n,e){if(e.lastIndexOf(Xe.CERT_BEGIN_HEADER)<0)throw new Error(C.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Xe.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(C.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function mO(n,e,t,r){let i=n.matchAll(Xe.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=fO(l),g=new Date(d.validFrom),y=new Date(d.validTo);if(s<g||s>y){let I=`Certificate is not valid, Valid from ${g} to ${y}`;throw console.warn(`checkCertificateInValidityPeriod: ${I}`),new Error(C.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(C.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(C.CERTIFICATE_HAS_EXPIRED);if(!gO(e,t,r,o))throw new Error(C.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function fO(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new tp(t);let r=rS.from(t,"base64");return new tp(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function hO(n){if(n.cert){let e=En.pki.publicKeyToPem(n.cert.publicKey);return tO(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=En.asn1.toDer(n.asn1).getBytes(),t=rS.from(e,"binary");return new tp(t).publicKey.export({type:"spki",format:"der"})}catch(e){return cr(`Failed to parse cert from asn1: ${e}`),null}return null}function gO(n,e,t,r){try{let i=rO(n),o=En.asn1.fromDer(En.util.createBuffer(i)),c=En.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:En.pki.oids.certBag})[En.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=hO(l);if(!g)continue;if(r.some(I=>{let le=I.publicKey.export({type:"spki",format:"der"});return g.equals(le)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return cr(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function np(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var oS="https://developer.huawei.com",yO={"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"},vO="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function wO(n){let e=yO[n];return e?`${oS}${e}`:void 0}function SO(){return`${oS}${vO}`}var bO={"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 iS(n,e){return(bO[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function EO(n){return Array.from(n).join(", ")}function sS(n,e){if(n.size===0)return;let t=Ur.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let y=wO(g.permissionName);y!=null&&(g.permissionHelpUrlKey=y)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let y=g.permissionInsteadName??g.permissionDisplayName;o.add(`${y} (${g.permissionHelpUrlKey})`)}let s=SO(),a=iS("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=iS("acl.permissions.warn",[EO(i),l,c]);console.log(d)}var Oc=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=U.discover(process.cwd()),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Project.discover() failed: ${t.message}`),e(he.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return p(`[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 p(`[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:he.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import PO from"fs";import aS from"path";var _c=class{constructor(e){this.toolProvider=e}checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return p(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=aS.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!PO.existsSync(r)){let i=aS.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Fc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await $e.getUserInfo()}catch(e){return p(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await $e.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(he.LOGIN_REQUIRED)}catch(t){return p(`[EnvCheck] Login check failed: ${t.message}`),e(he.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(he.TEAM_INFO_FAILED);try{if((await Cr()).teamList.length>0)return{passed:!0,message:""}}catch(r){return p(`[EnvCheck] Team API error: ${r.message}`),e(he.TEAM_INFO_FAILED)}return p("[EnvCheck] No teams found for current user"),e(he.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(he.REALNAME_REQUIRED):t.isRealName!==!0?(p("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(he.REALNAME_REQUIRED)):{passed:!0,message:""}:e(he.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await Cr();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.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 p(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return p(`[EnvCheck] Team ID check failed: ${i.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(he.REGION_CHINA_ONLY):{passed:!0,message:""}:(p("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(he.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function CO(n){try{let{teamList:e}=await Cr();if(e.length>0)return e[0].id}catch(e){p(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function kO(n){let e=await $e.getUserInfo(),t=await $e.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await CO(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Mc(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var $c=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let r=await kO(t);if(r.length>0)return p(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};p("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await oe.from(this.toolProvider).listDevices();return o.length===0?(p("[EnvCheck] Scenario 4 Device check: no local devices found"),e(he.DEVICE_MISSING)):o.some(a=>Ot(a.serial))?{passed:!0,message:""}:(p("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(he.DEVICE_MISSING))}catch(r){return p(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(he.DEVICE_DETECT_FAILED)}}};var jc=class{projectChecker=new Oc;toolchainChecker=null;authChecker=new Fc;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=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await P.new();return this.toolchainChecker=new _c(e),this.deviceChecker=new $c(e),!0}catch(e){throw p(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(he.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))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 p(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var cS=5*1024*1024;function DO(n){try{let e=op.statSync(n);if(e.size>cS)throw new Error(`Profile file too large: ${e.size} bytes (max ${cS} bytes): ${n}`);let t=op.readFileSync(n,"utf-8");return dS.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function RO(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function TO(n){if(n.keyPwd===n.storePassword){let r=await Hr.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Hr.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Hr.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function xO(n,e,t){let r=lS.join(n,"build-profile.json5"),i=DO(r);RO(i);let o=t??"default",{keyPassword:s,storePassword:a}=await TO(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:Rt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(g=>g.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),op.writeFileSync(r,dS.stringify(i,null,2),"utf-8")}async function NO(n){let e=await $e.getUserInfo(),t=await $e.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 LO(n){let e=n.product||"default";await new jc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await NO(n),i=await P.new(),{shouldRegenerate:o}=await Wo.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(ip("Signature generation completed successfully."));return}await MO(n,r,i),console.log(ip("Signature generation completed successfully."))}async function MO(n,e,t){let r=await Gu(e,n.product),i=OO(n,e,r,t);i.allDeviceIds=await Kw(e,t.hdcPath),await nS(e,i);let o=U.discover(process.cwd()).rootDir;await xO(o,r,n.product??"default"),console.log(ip(`Signing config written to ${lS.join(o,"build-profile.json5")}`))}function OO(n,e,t,r){let i=process.cwd(),o=U.discover(i),s=Nc(o,r);return sS(s,o),{productName:n.product||"default",bundleName:o.getBundleName(n.product||"default"),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var uS=new IO("signature").description("Generate application signature.");uS.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.").action(async n=>{let e={event:b.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,i=null;try{await LO(n)}catch(o){r=!1,i=V(o),console.error(AO(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await k.track(e,o)}});var pS=uS;import{Command as GO}from"commander";import{green as qO,red as fp}from"colorette";import Ii from"fs";import Bc from"path";import zO from"ora";import Hc from"fs";import sp from"path";import{homedir as _O}from"os";function mS(){let n=process.env.DEVECO_CLI_DATA_DIR?W():sp.join(_O(),ge.CONFIG_DIR_NAME,ge.APP_NAME);return sp.join(n,"ui_verification_config.json")}function fS(){let n=mS();if(!Hc.existsSync(n))return{};try{let e=JSON.parse(Hc.readFileSync(n,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function ap(){let n=fS();if(Object.keys(n).length===0)return null;let e;if(Dd(n.encryptedApiKey))try{e=Ad(n.encryptedApiKey)}catch{}return{baseUrl:typeof n.baseUrl=="string"?n.baseUrl:void 0,modelName:typeof n.modelName=="string"?n.modelName:void 0,apiKey:e}}function cp(n){let e=mS();Hc.mkdirSync(sp.dirname(e),{recursive:!0,mode:448});let t=fS();return n.baseUrl!==void 0&&(t.baseUrl=n.baseUrl),n.modelName!==void 0&&(t.modelName=n.modelName),n.apiKey!==void 0&&(t.encryptedApiKey=Id(n.apiKey),delete t.apiKey),Hc.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),e}import Uc from"fs";import FO from"os";import hS from"path";var Pn=hS.join(FO.tmpdir(),"ui-verification","cache"),$O=15;function lp(n=Pn,e=$O){if(!Uc.existsSync(n))return;let t=Uc.readdirSync(n,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>{let i=hS.join(n,r.name);return{entryPath:i,mtime:Uc.statSync(i).mtimeMs}}).sort((r,i)=>r.mtime-i.mtime);for(let r of t.slice(0,Math.max(0,t.length-e)))Uc.rmSync(r.entryPath,{recursive:!0,force:!0})}import{execFile as jO,spawn as HO}from"child_process";import UO from"fs";import dp from"path";import{fileURLToPath as BO}from"url";function WO(){let n=dp.dirname(BO(import.meta.url));for(;;){let e=dp.join(n,"node_modules","ui-verification-mcp","bin","ui-verification-mcp.cjs");if(UO.existsSync(e))return e;let t=dp.dirname(n);if(t===n)break;n=t}throw new Error("ui-verification-mcp is not installed. Run `npm install` and try again.")}var Vo=class n{constructor(e){this.child=e;this.stopped=new Promise(r=>e.once("close",()=>r())),e.stdout?.on("data",r=>{this.buffer+=r.toString();let i=this.buffer.split(`
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1390
|
+
`),console.log(Te("[compat:check] === end stdout ===")));let o=new pe("errorCode",`Compatibility scan failed: ${i.message}`+(i.stderr?`
|
|
1391
|
+
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function J1(r,e){if(!N1.includes(e.format))throw new R1(`--format must be default, csv, or json (console: default|json, file: default|csv|json). got "${e.format}"`);if(r.length>0&&e.modules&&e.modules.length>0)throw new pe("errorCode","Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new pe("errorCode","--source-version is required.");if(!e.targetVersion)throw new pe("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new pe("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function K1(r,e){let t=[];if(r.sourceVersion&&!e.includes(r.sourceVersion)&&t.push(`--source-version "${r.sourceVersion}"`),r.targetVersion&&!e.includes(r.targetVersion)&&t.push(`--target-version "${r.targetVersion}"`),t.length>0){let n=t.length>1?"are":"is";throw new pe("errorCode",`${t.join(" and ")} ${n} not in the available SDK version list.
|
|
1392
|
+
Run \`devecocli compat versions\` to see all available versions.`)}if(r.sourceVersion&&r.targetVersion){let n=e.indexOf(r.sourceVersion),i=e.indexOf(r.targetVersion);if(n>=i)throw new pe("errorCode",`--target-version "${r.targetVersion}" must be later than --source-version "${r.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function Y1(r,e,t,n,i){i==="none"&&(t==="json"?V1(r,n):W1(r,n)),B1(r,e)}function X1(r,e){let t=ie.dirname(r),n=ie.basename(r),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");f(Te(`[compat:check] command: cd "${t}" && node "${n}" ${i}`))}function Z1(r){try{I1(r),f(Te(`[compat:check] cleaned up tmp report: "${r}"`))}catch(e){f(Te(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var Q1=[".csv",".json"];function eB(r){return Q1.includes(r.toLowerCase())}function tB(r,e){if(!r)return{kind:"none"};let t=ie.extname(r).toLowerCase();if(!eB(t))return{kind:"dir",dirPath:ie.resolve(r)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new pe("errorCode",`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:ie.resolve(r),ext:t}}function rB(r){if(r.kind==="file"){if(wu(r.filePath))throw new pe("errorCode",`Target file "${r.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=ie.dirname(r.filePath);if(!wu(e))throw new pe("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(r.kind==="dir"&&!wu(r.dirPath))throw new pe("errorCode",`Target directory "${r.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function ik(r){return JSON.stringify({records:r,count:r.length},null,2)+`
|
|
1393
|
+
`}function nB(r,e,t,n){n===".csv"?QC(r,t):ek(t,ik(e),"utf8"),f(Te(`[compat:check] saved report: "${t}"`))}function iB(r,e,t,n){if(n==="json"){let o=ie.basename(r,".csv"),s=ie.join(t,`${o}.json`);return ek(s,ik(e),"utf8"),f(Te(`[compat:check] saved report: "${s}"`)),s}let i=ie.join(t,ie.basename(r));return QC(r,i),f(Te(`[compat:check] saved report: "${i}"`)),i}async function oB(r,e){let t=new ht(r,process.cwd(),!0),n=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",n)}catch(i){throw new pe("errorCode",`hvigorw compileNative failed (module=${n??"<project>"}): `+i.message,{cause:i})}}async function sB(r,e){J1(r,e);let t=W.discover(process.cwd());await rt.warnInvalidBundledLinks(t.rootDir),e.modules&&e.modules.length>0&&M1(t,e.modules),r.length>0&&O1(r);let n=await P.new(),{apiChangeDir:i,scriptPath:o}=n.getApiscanPaths();f(Te(`[compat:check] script: "${o}"`));let s=rk(i);K1(e,s),e.outputPath&&f(Te(`[compat:check] outputPath: "${e.outputPath}"`));let a=tB(e.outputPath,e.format);return f(Te(`[compat:check] outputTarget: ${a.kind}`)),rB(a),{project:t,scriptPath:o,target:a,toolProvider:n}}function aB(r,e,t,n){if(t.kind==="file")return nB(r,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return iB(r,e,t.dirPath,n);if(t.kind==="none")return null;throw new pe("errorCode",`Unexpected output target kind: ${t.kind}`)}async function cB(r,e,t,n,i){let o=T1({text:"Running compatibility check...",color:"cyan"}).start();try{await oB(r.toolProvider,t);let s=q1(r.scriptPath,e,r.project,t);X1(r.scriptPath,s);let a=await z1(r.toolProvider,s),c=U1(a,qh.tmpdir());if(!c)throw new pe("errorCode","Scanner output format unexpected: missing report path.");f(Te(`[compat:check] tmp csv: "${c}"`));let l=H1(c),d=aB(c,l,r.target,t.format);Z1(c),o.stop(),Y1(l,d,t.format,t.limit,r.target.kind),await Yo(n,!0,null,i)}catch(s){o.fail("Compatibility check failed");let a=zh(s);throw await Yo(n,!1,a,i),s}}async function ok(r,e){let t=Date.now(),n=["check","compat"];try{let i=await sB(r,e);await cB(i,r,e,t,n)}catch(i){let o=zh(i);throw await Yo(t,!1,o,n),i}}function dB(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new lB(`--limit must be a positive integer (got "${r}")`);return e}var Jh=new sk("compat").description("Compatibility checking utilities.");Jh.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",dB,100).action(async(r,e)=>{await ok(r,e)});Jh.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async(r,e)=>{let t=e.optsWithGlobals().format;await nk(t)});var uB=new sk("check").description("Run DevEco project checks").addCommand(Jh).addCommand(Hh()).addCommand(Gh()),ak=uB;import{Command as QW}from"commander";import{green as yg,red as eV,yellow as Gk}from"colorette";import Ni from"fs";import wg from"path";import qk from"json5";import{readFileSync as HB}from"fs";import{join as pB}from"path";var fe={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},xe={CERT_NAME_PREFIX:"auto_debug_",CERT_NAME_PREFIX_RELEASE:"auto_release_",CERT_TYPE_DEBUG:"1",CERT_TYPE_RELEASE:"2",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:pB(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},Ne={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},Qt={FORBIDDEN:403,UNAUTHORIZED:401},k={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},be={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function vu(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}function Kh(r,e=!1){let t=r.replace(xe.TEAM_ID_INVALID_CHARS,"");return`${e?xe.CERT_NAME_PREFIX_RELEASE:xe.CERT_NAME_PREFIX}${t}.cer`}function Xo(r,e,t){if(r===Qt.FORBIDDEN)return e===Ne.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN);if(r===Qt.UNAUTHORIZED)return new Error(k.ERR_UNAUTHORIZED);if(t.includes(Ne.USER_NOT_HARMONY_CODE))return new Error(k.ERR_USER_NOT_HARMONY);if(t.includes(Ne.CERT_LIMIT_CODE))return new Error(k.ERR_CERT_LIMIT_REACHED);let n=fB(t);return new Error(n??k.ERR_DOWNLOAD_CER)}function fB(r){let e=ck(r);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let n=typeof t=="string"?ck(t):t;if(n&&typeof n=="object"){let i=n.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function ck(r){try{return JSON.parse(r)}catch{return null}}function Yh(r){return JSON.parse(r)}async function lk(r){let e=`${fe.BASE_URL}${fe.CERT_LIST_PATH}`,t=await $.postAllowFailure(e,{headers:vu(r)});if(t.statusCode!==200)throw Xo(t.statusCode,t.statusText,t.data);return Yh(t.data)?.certList??[]}async function bu(r,e){return(await lk(r)).find(n=>n.certName===e)??null}async function Xh(r,e){let t=`${fe.BASE_URL}${fe.CERT_DELETE_PATH}`,n=await $.deleteAllowFailure(t,{headers:vu(r),params:{certIds:[e]}});if(n.statusCode!==200)throw Xo(n.statusCode,n.statusText,n.data);return Yh(n.data)?.ret?.code===0}async function Zh(r,e,t,n=xe.CERT_TYPE_DEBUG){let i=`${fe.BASE_URL}${fe.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:n},s=await $.postAllowFailure(i,{headers:vu(r),params:o});if(s.statusCode!==200)throw Xo(s.statusCode,s.statusText,s.data);if(!s.data.includes(Ne.SUCCESS_MARKER))throw Xo(void 0,s.statusText,s.data)}async function Qh(r,e){let t=`${fe.BASE_URL}${fe.CERT_DOWNLOAD_URL_PATH}`,n=await $.postAllowFailure(t,{headers:vu(r),params:{sourceUrls:e}});if(n.statusCode!==200)throw Xo(n.statusCode,n.statusText,n.data);return Yh(n.data)?.urlsInfo?.[0]??null}import{mkdirSync as mB,writeFileSync as hB,existsSync as gB}from"fs";import{dirname as yB}from"path";import{createHash as wB}from"crypto";function vB(r){let e;try{e=new URL(r)}catch{throw new Error(`Invalid download URL: ${JSON.stringify(r)}`)}if(e.protocol!=="https:")throw new Error(`Download URL must use HTTPS: ${e.protocol}`);let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t.startsWith("169.254.")||t.startsWith("10.")||t.startsWith("192.168.")||/^172\.(1[6-9]|2\d|3[0-1])\./.test(t)||t.endsWith(".internal")||t.endsWith(".local"))throw new Error(`Download URL points to internal/private address: ${t}`)}async function Ba(r,e,t){vB(r);let{statusCode:n,statusText:i,buffer:o}=await $.getBinaryAllowFailure(r,{timeout:xe.DOWNLOAD_CONNECT_TIMEOUT_MS});if(n!==200)throw n===Qt.FORBIDDEN&&i===Ne.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_DOWNLOAD_CER);if(t){let a=wB("sha256").update(o).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=yB(e);gB(s)||mB(s,{recursive:!0}),hB(e,o)}import FB from"fs/promises";import{readFileSync as $B}from"fs";import Su from"path";import pk from"crypto";import bB from"os";import Wa from"fs/promises";var fk={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},dk=["ECC","RSA"],uk=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],SB={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},EB=8,eg=64,PB=/[\\/:*?"<>|=-]/g,Zr={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function CB(r){if(!r.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!r.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(r.keyAlias.length>eg)throw new Error(`The length of keyAlias cannot exceed ${eg}`);if(!dk.includes(r.keyAlg))throw new Error(`Invalid key algorithm ${r.keyAlg}, available: ${dk.join(" / ")}`);let e=SB[r.keyAlg];if(!e.includes(r.keySize))throw new Error(`Key algorithm ${r.keyAlg} does not support size ${r.keySize}, available: ${e.join(", ")}`)}function kB(r){if(!r.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!r.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!r.subject.trim())throw new Error("subject cannot be empty");if(!uk.includes(r.signAlg))throw new Error(`Invalid sign algorithm ${r.signAlg}, available: ${uk.join(" / ")}`)}function RB(r){return pk.createHash("sha256").update(r,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function DB(r){let e=r?.trim()??"";return e&&e.replace(PB,"_").replace(/\.+/g,"_").slice(0,eg)||Zr.productName}async function mk(){let r=await P.new();r.assertJava();let e=r.javaPath,t=r.sdkPath;m.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let n=Su.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Wa.access(n)}catch(i){throw new Error(`Sign tool jar not found: ${n}`,{cause:i})}return{javaPath:e,jarPath:n}}async function xB(r){let{javaPath:e,jarPath:t}=await mk(),n=["-jar",t,fk.GENERATE_KEYPAIR,"-keyAlias",r.keyAlias,"-keyAlg",r.keyAlg,"-keySize",r.keySize,"-keystoreFile",r.keystoreFile,"-keystorePwd",r.keystorePwd];r.keyPwd&&n.push("-keyPwd",r.keyPwd),r.pwdInputMode&&n.push("-pwdInputMode",r.pwdInputMode);let i=n.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(n[s-1])?"******":o);return m.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...n]}async function IB(r){let{javaPath:e,jarPath:t}=await mk(),n=["-jar",t,fk.GENERATE_CSR,"-keyAlias",r.keyAlias,"-subject",r.subject,"-signAlg",r.signAlg,"-keystoreFile",r.keystoreFile,"-keystorePwd",r.keystorePwd];r.outFile&&n.push("-outFile",r.outFile),r.keyPwd&&n.push("-keyPwd",r.keyPwd),r.pwdInputMode&&n.push("-pwdInputMode",r.pwdInputMode);let i=n.map((o,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(n[s-1])?"******":o);return m.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...n]}async function AB(r){m.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),CB(r);let e=await xB(r),t=await Ps(e[0],e.slice(1));if(t.exitCode!==0){let n=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${n}`)}return m.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function TB(r){m.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),kB(r);let e=await IB(r),t=await Ps(e[0],e.slice(1));if(t.exitCode!==0){let n=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${n}`)}return m.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function NB(r=EB){return pk.randomBytes(r).toString("base64url").replaceAll(/[-_=]/g,"")}async function _B(){let r=bB.homedir();try{await Wa.access(r)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Su.join(r,".ohos","config");try{await Wa.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return m.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function He(r,e,t,n){let i=DB(r),o=Su.basename(e),s=RB(e),c=`${i}_${o}_${s}${n==="release"?"_release":""}=.${t}`,l=await _B();return Su.join(l,c)}function MB(r){let e;try{e=W.discover(r).rootDir}catch(t){throw new Error(`Current directory ${r} is not a valid project root`,{cause:t})}return e}async function OB(r){try{await Wa.access(r)}catch(e){throw new Error(`Project directory ${r} is not accessible, missing read/write permissions`,{cause:e})}}async function LB(r){try{await Wa.access(r)}catch(e){throw new Error(`P12 file ${r} does not exist, terminating CSR generation.`,{cause:e})}}async function tg(r,e,t,n){let i=process.cwd(),o=MB(i);await OB(o),m.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let s=NB(),a=n==="release",c=a?"releaseKey":Zr.keyAlias,l=a?"CN=ReleaseKey":Zr.csrSubject,d=await He(r??"",o,"p12",n),h=await He(r??"",o,"csr",n);return console.log("Start generating p12"),await AB({keyAlias:e?.keyAlias??c,keyPwd:s,keyAlg:e?.keyAlg??Zr.keyAlg,keySize:e?.keySize??Zr.keySize,keystoreFile:d,keystorePwd:s}),await LB(d),console.log("Start generating csr"),await TB({subject:t?.subject??l,outFile:h,keyAlias:e?.keyAlias??c,keyPwd:s,signAlg:t?.signAlg??Zr.signAlg,keystoreFile:d,keystorePwd:s}),{p12FilePath:d,csrFilePath:h,keyPwd:s,keyAlias:e?.keyAlias??c}}var jB=["p12","cer","csr","p7b"];async function rg(r,e,t){for(let n of jB){let i=await He(r,e,n,t);await FB.rm(i,{force:!0})}}function ng(r){let e;try{e=$B(r,"utf-8")}catch{throw new Error(k.ERR_CERT_INVALIDATE)}if(!xe.CERT_PATTERN.test(e))throw new Error(k.ERR_CERT_INVALIDATE)}async function Eu(r,e,t){return{certPath:await He(r,e,"cer",t),csrPath:await He(r,e,"csr",t),p12Path:await He(r,e,"p12",t),profilePath:await He(r,e,"p7b",t)}}async function ig(r,e,t){let n=e??"",i=W.discover(process.cwd()).rootDir;await rg(n,i,t);let o=Kh(r.teamId,t==="release"),s=await bu(r,o);if(s&&!await Xh(r,s.id))throw new Error(k.ERR_DOWNLOAD_CER);let a=await tg(e,void 0,void 0,t),c;try{c=HB(a.csrFilePath,"utf-8")}catch{throw new Error(k.ERR_READ_CSR)}console.log("Start generating certificate");let l=t==="release"?xe.CERT_TYPE_RELEASE:xe.CERT_TYPE_DEBUG;await Zh(r,c,o,l);let d=await bu(r,o);if(!d)throw new Error(k.ERR_DOWNLOAD_CER);let h=await Qh(r,d.certObjectId);if(!h)throw new Error(k.ERR_DOWNLOAD_CER);let y=await He(n,i,"cer",t);await Ba(h.newUrl,y,h.sha256),ng(y);let D=await He(n,i,"p7b",t);return{p12FilePath:a.p12FilePath,csrFilePath:a.csrFilePath,cerFilePath:y,profileFilePath:D,certId:d.id,keyAlias:a.keyAlias,keyPwd:a.keyPwd,storePassword:a.keyPwd}}import Nu from"crypto";import jn from"fs";import*as Ik from"path";import cW from"json5";import{execa as Rk}from"execa";import Dk from"node-forge";import{createCipheriv as UB,createDecipheriv as BB,pbkdf2Sync as WB,randomBytes as cg}from"crypto";import{promises as xi}from"fs";import{dirname as VB,join as er}from"path";var Pu=3,Va=16,GB=1e4,hk="material",qB=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),vk="aes-128-gcm",Di=12,Cu=16,Ln=4;function og(r){return new Uint8Array(cg(r))}function zB(r){return cg(r).toString("hex")}function JB(...r){if(r.length===0)return new Uint8Array(0);let e=r[0].length,t=new Uint8Array(e);for(let n=0;n<e;n++){let i=0;for(let o of r)i^=o[n];t[n]=i}return t}function gk(r,e,t=GB,n=Va){let i=[...r,qB],o=JB(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=WB(a,e,t,n,"sha256");return new Uint8Array(c)}function yk(r,e){let t=cg(Di),n=UB(vk,r,t),i=Buffer.concat([n.update(e),n.final()]),o=n.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(Ln+Di+s.length);return c.writeUInt32BE(a,0),t.copy(c,Ln),s.copy(c,Ln+Di),c}function wk(r,e){if(e.length<Ln+Di+Cu)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),n=e.subarray(Ln,Ln+Di),i=e.subarray(Ln+Di,Ln+Di+t);if(i.length<Cu)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Cu),s=i.subarray(i.length-Cu),a=BB(vk,r,n);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function KB(r){try{await xi.rm(r,{recursive:!0,force:!0})}catch{}}async function sg(r){let e=await xi.readdir(r),t=e.filter(n=>n!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${r}, but found ${t.length} (filtered from ${e.length})`);return xi.readFile(er(r,t[0]))}async function ag(r,e){let t=zB(Va),n=er(r,t);return await xi.writeFile(n,e,{mode:384}),t}var Fn=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=er(e,hk);await KB(t);let n=er(t,"ac"),i=er(t,"ce");await xi.mkdir(n,{recursive:!0,mode:448}),await xi.mkdir(i,{recursive:!0,mode:448});for(let d=0;d<Pu;d++)await xi.mkdir(er(t,"fd",String(d)),{recursive:!0,mode:448});let o=og(Va),s=[];for(let d=0;d<Pu;d++)s.push(og(Va));let a=og(Va),c=gk(s,o),l=yk(c,a);await ag(n,o),await ag(i,l);for(let d=0;d<Pu;d++){let h=er(t,"fd",String(d));await ag(h,s[d])}return a}static async readMaterial(e){let t=er(e,hk),n=er(t,"ac"),i=new Uint8Array(await sg(n)),o=[];for(let d=0;d<Pu;d++){let h=er(t,"fd",String(d)),y=await sg(h);o.push(new Uint8Array(y))}let s=er(t,"ce"),a=await sg(s),c=gk(o,i),l=wk(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,n=this.keyChain;this.keyChain=new Promise(i=>{t=i}),await n;try{let i=VB(e);try{return await this.readMaterial(i)}catch{return await this.generateMaterial(i)}}finally{t()}}static async encryptedPassword(e,t){let n=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return yk(n,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let n=await this.getStoreKey(t),i=Buffer.from(e,"hex");return wk(n,i).toString("utf8")}};import Ck from"fs";import Au from"path";import tW from"json5";import*as ku from"fs";import*as bk from"path";function Ru(r){let e=bk.resolve(r);if(!ku.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=ku.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let n;try{n=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=n?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as Qo from"fs";import*as dt from"path";import{debuglog as Zo}from"util";var Sk={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function YB(r){return Object.prototype.hasOwnProperty.call(Sk,r)}function Du(r){if(YB(r))return Sk[r]}var Ek={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as XB}from"url";var Iu=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function xu(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Pk(r){return r==null||r.length===0}function ZB(r){return!Pk(r)}function lg(r,e){let t=r[e];return typeof t=="string"?t:t==null?"":String(t)}function QB(r,e){let t=r[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let n=t.trim().toLowerCase();return n==="true"||n==="1"}return!1}function eW(r,e){let t=r[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}return 0}var $n=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=dt.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=dt.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let n=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,n),o=this.getOrCreateSet(this.aclPermissionInfoMap,n);i.clear(),o.clear();let s=dt.join(t.sdkPath,"default","sdk-pkg.json"),a=Ru(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=dt.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Qo.existsSync(e))return Qo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=XB(e);if(t.includes("dist")){let s=dt.dirname(t),a=dt.dirname(s);return dt.join(a,"src","resources")}let n=dt.dirname(t),i=dt.dirname(n),o=dt.dirname(i);return dt.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let n;try{n=this.readBuiltInConfigText()}catch{Zo("read builtin acl permission failed.");return}if(n!==void 0)try{let i=JSON.parse(n),s=(Array.isArray(i)?i:xu(i)?Object.values(i):[]).filter(xu).map(a=>new Iu(a));s.forEach(a=>{let c=a.permissionInsteadName;ZB(c)&&(a.permissionInsteadName=Du(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Zo(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,n){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!xu(o))return;let s=o,a=lg(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Pk(a)||(this.generateAclInfos(n,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||lg(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||lg(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:QB(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,n){let i=new Iu;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=eW(n,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=dt.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Qo.existsSync(t))return;let n;try{n=Qo.readFileSync(t,"utf-8")}catch(s){Zo(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(n);if(!xu(s)){Zo("json object is null");return}i=s}catch(s){Zo(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Zo("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Du(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Du(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Tu(r,e){let t=new Set,n=new Set;$n.handleSpecificAclPermissions(),$n.initAclPermission(r,e);for(let i of r.profile.modules){let o=kk(i,r,e,n,Au.join("src","main"));for(let a of o)t.add(a);let s=kk(i,r,e,n,Au.join("src","ohosTest"));for(let a of s)t.add(a)}return rW(n),t}function rW(r){if(r.size>0)throw new Error(Ek.DUPLICATE_PERMISSION)}function kk(r,e,t,n,i){let o=iW(e.rootDir,r,i);if(o==null)return new Set;let s=[];for(let y of o){if(typeof y!="object"||y===null)continue;let D=nW(y,"name");D&&s.push(D)}let a=new Set(s);a.size!==s.length&&n.add(r.name);let c=Au.join(t.sdkPath,"default","sdk-pkg.json"),l=Ru(c),d=$n.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(y=>{let D=Number(y.minSupportApiLevel);return Number.isFinite(D)&&D<=l}).map(y=>y.permissionName));for(let y of Array.from(a))h.has(y)||a.delete(y);return a}function nW(r,e){let t=r[e];return typeof t=="string"?t:""}function iW(r,e,t){let n=Au.join(r,e.srcPath,t,"module.json5"),i=oW(n);if(i==null)return null;let o=sW(i,"module");return o==null?null:aW(o,"requestPermissions")}function oW(r){try{if(!Ck.existsSync(r))return null;let e=Ck.readFileSync(r,"utf-8");return tW.parse(e)}catch{return null}}function sW(r,e){if(r==null||typeof r!="object")return null;let t=r[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function aW(r,e){if(r==null||typeof r!="object")return null;let t=r[e];return Array.isArray(t)?t:null}var ug=class{verifyStorePassword(e,t){try{let n=jn.readFileSync(e),i=Dk.asn1.fromDer(n.toString("binary"));return Dk.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let n=jn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(n&&n.length>0)return n.map(i=>this.formatFp(new Nu.X509Certificate(i).fingerprint256));try{return[this.formatFp(new Nu.X509Certificate(jn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=jn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new Nu.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function lW(r,e){let t=jn.readFileSync(r,"utf-8"),n=dW(t),i=null;if(n)try{i=JSON.parse(n)}catch{i=null}let o=i?.["bundle-info"]??{},s=e==="release"?"distribution-certificate":"development-certificate";return{rawContent:t,bundleNameInProfile:dg(o["bundle-name"]),expiryDate:uW(i?.validity?.["not-after"]),cerFingerprintInProfile:pW(dg(o[s])),deviceUdidsInProfile:fW(i?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:mW(i?.acls?.["allowed-acls"]),teamIdInProfile:dg(o["developer-id"])}}function dW(r){let e=r.indexOf("{");if(e<0)return null;let t=0,n=-1,i=!1,o=!1;for(let s=e;s<r.length;s++){let a=r[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){n=s;break}}return n<0?null:r.slice(e,n+1)}function uW(r){if(typeof r!="number"||!Number.isFinite(r))return null;let e=new Date(r*1e3);return isNaN(e.getTime())?null:e}function pW(r){if(!r)return null;try{let t=new Nu.X509Certificate(r).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function fW(r){if(!Array.isArray(r))return[];let e=[];for(let t of r)if(typeof t=="string"){let n=t.toUpperCase();e.includes(n)||e.push(n)}return e}function mW(r){if(!Array.isArray(r))return[];let e=[];for(let t of r)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function dg(r){return typeof r=="string"?r:null}var Ga=class r{static async shouldRegenerate(e,t){let n=await r.#e(e,t);return r.#t(n)??r.#r(n)??r.#n(n)??r.#i(n)??r.#o(n)??r.#s(n)??(n.type==="release"?null:r.#a(n))??r.#c(n)??r.#l(n)??r.#d(n)??await r.#u(n)??r.#p()}static async#e(e,t){let n=e.force,i=e.teamId,o=e.productName??"default",s=e.type,a=W.discover(process.cwd()),c=a.rootDir,[l,d]=await Promise.all([hW(o,c,s),s==="release"?Promise.resolve([]):yW(t.hdcPath)]),h=null;if(xk(l).allExist)try{h=lW(l.profileFile,s)}catch{}return{force:n,teamId:i,productName:o,projectPath:c,type:s,materialPaths:l,bundleName:a.getBundleName(o),deviceUdids:d,storePassword:await gW(c,o,l.storeFile,s),localAclPermissions:[...Tu(a,t)].sort(),hapSignTool:new ug,profileInfo:h}}static#t(e){return e.force?(f("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:bt({force:!0})}):null}static#r(e){let t=xk(e.materialPaths);return t.allExist?null:(f(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:bt({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(f("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(f(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(f(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(f(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=vW(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(f(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return bW(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(f("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),n=e.profileInfo?.cerFingerprintInProfile;return n&&t.includes(n)?null:(f("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,n=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!n||n>=new Date?null:(f(`[reGenerateSign] local certificate expired at ${n.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${n.toISOString()}`,checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(f("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(f("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return f("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:bt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function hW(r,e,t){let[n,i,o,s]=await Promise.all([He(r,e,"p12",t),He(r,e,"csr",t),He(r,e,"cer",t),He(r,e,"p7b",t)]);return{storeFile:n,csrFile:i,cerFile:o,profileFile:s}}async function gW(r,e,t,n){let i=Ik.join(r,"build-profile.json5");if(!jn.existsSync(i))return;let o;try{o=cW.parse(jn.readFileSync(i,"utf-8"))}catch{return}let s=n==="release"?`${e}_release`:e,l=(o?.app?.signingConfigs??[]).find(d=>d.name===s)?.material?.storePassword;if(l)try{return await Fn.decryptPassword(l,t)}catch{return}}async function yW(r){f(`Executing: ${r} list targets`);let{stdout:e}=await Rk(r,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1394
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let n=[];for(let i of t)try{f(`Executing: ${r} -t ${i} shell bm get -u`);let{stdout:o}=await Rk(r,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=wW(o);s&&n.push(s)}catch{f(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return n}function wW(r){let e=r.trim();if(!e)return null;let t=e.split(`
|
|
1395
|
+
`);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let n=e.match(/[A-Fa-f0-9]{64}/);return n?n[0].toUpperCase():null}function xk(r){let e=[r.storeFile,r.csrFile,r.cerFile,r.profileFile],t=[];for(let n of e)jn.existsSync(n)||t.push(n);return{allExist:t.length===0,missing:t}}function vW(r,e){let t=[];for(let n of e)r.includes(n)||t.push(n);return{allPresent:t.length===0,missing:t}}function bW(r,e){let t=[...r].sort(),n=[...e].sort();return t.length!==n.length?!1:t.every((i,o)=>i===n[o])}function bt(r){let e={force:!1,allFilesExist:!1,missingFiles:[],profileContentNotEmpty:!1,profileNotExpired:!1,bundleNameMatched:!1,teamIdMatched:!1,allDevicesInProfile:!1,missingDeviceUdids:[],aclMatched:!1,cerMatched:!1,cerNotExpired:!1,storePasswordValid:!1};return r.force?{...e,force:!0}:{...e,...r,force:!1}}import{debuglog as pg}from"util";import{execa as fg}from"execa";async function Tk(r,e){let t=await _u(r);if(!t)throw new Error(k.DEVICE_LIST_EMPTY);let n=await PW(e);if(t.length===0)for(let s of n)await SW(r,s.udid,s.deviceName);else for(let s of n)await EW(r,t,s.udid,s.deviceName);let o=(await _u(r)).map(s=>s.id);if(o.length===0)throw new Error(k.DEVICE_LIST_EMPTY);return o}async function SW(r,e,t){await Mk(r,e,Nk(t))}async function EW(r,e,t,n){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await Mk(r,t,Nk(n));return}}}function Nk(r){switch(r){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Ak(r,e=1,t=100){let n=`${fe.BASE_URL}${fe.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=Ok(r),o=await $.get(n,{headers:i});if(!o)throw pg("query devices failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw _k(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw pg("query devices failed: response list is null"),new Error(s.ret?.msg||k.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function _k(r,e,t){return r===Qt.FORBIDDEN?e===Ne.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):r===Qt.UNAUTHORIZED?new Error(k.ERR_UNAUTHORIZED):t.includes(Ne.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(k.DEVICE_LIMIT_REACHED):new Error(k.ERROR_WHILE_ADD_DEVICE)}async function _u(r){let t=await Ak(r,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let n=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await Ak(r,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;n.push(...a.deviceList)}return n}async function Mk(r,e,t){let n=`${fe.BASE_URL}${fe.DEVICE_ADD_PATH}`,i=Ok(r),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await $.postAllowFailure(n,{headers:i,params:s});if(!a)throw pg("add device failed: response is null"),new Error(k.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw _k(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(Ne.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(k.DEVICE_LIMIT_REACHED):c.includes(Ne.DEVICE_NAME_REPEAT_CODE)?new Error(k.DEVICE_NAME_REPEAT):new Error(k.ERROR_WHILE_ADD_DEVICE)}function Ok(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}async function PW(r){let{stdout:e}=await fg(r,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1396
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let n=[];for(let i of t)try{let o=await CW(i,r),s=await kW(i,r);o.length>0&&n.push({id:"",udid:o,deviceName:s})}catch{f(`Failed to get device info for ${i}, skipping`)}return n}async function CW(r,e){let{stdout:t}=await fg(e,["-t",r,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),n=t.trim();if(!n)return"";let i=n.split(`
|
|
1397
|
+
`);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=n.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function kW(r,e){let{stdout:t}=await fg(e,["-c","-t",r,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return RW(t)}function RW(r){let e=r.trim();return!e||e.includes("inaccessible")?"phone":r.includes("liteWearable")?"liteWearable":r.includes("wearable")?"wearable":r.includes("tv")?"tv":"phone"}import Ii from"fs";import{createHash as DW}from"crypto";import{debuglog as Ti}from"util";import{Buffer as Fk}from"buffer";import{createPublicKey as xW,X509Certificate as mg}from"crypto";import{readFileSync as IW}from"fs";import Ai from"node-forge";async function $k(r,e){console.log("Start generating profile");let{productName:t,bundleName:n,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e,d=e.type==="release";if(!d&&(s==null||s.length===0))throw new Error(k.DEVICE_LIST_EMPTY);let h=d?fe.PROVISION_ADD_REAL_PATH:fe.PROVISION_ADD_TEST_PATH,y=`${fe.BASE_URL}${h}`,D=AW(t,n),K=await NW(r,y,a||[],n,s??[],D,o||[]);if(!K||!K.profileInfo||!K.profileInfo.provisionFileUrl)throw Ti("add provision failed, the provision file url is null"),new Error(k.ADD_PROFILE_FAIL);let we=K.profileInfo,tr=(await LW(r,we.provisionFileUrl)).urlList,Un=K.profileInfo.id;if(tr&&tr.length>0){let Bn=await Eu(t,i,e.type),Wn=Bn.profilePath;if(!await FW(tr,Wn))throw await Lk(r,Un),new Error(k.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Lk(r,Un),Ii.existsSync(Bn.certPath)&&Ii.existsSync(Wn)&&Ii.existsSync(Bn.p12Path)){let iR=Ii.readFileSync(Bn.certPath,"utf8"),oR=Ii.readFileSync(Wn,"utf8");return $W(oR,iR,Bn.p12Path,c,l)||OW(Wn),Wn}}throw new Error(k.ADD_PROFILE_FAIL)}function AW(r,e){let t=r?`${r}_`:"";return`${TW(`${t}${e}_${e}`)}`}function TW(r){return DW("sha256").update(r).digest("hex").substring(0,16)}async function NW(r,e,t,n,i,o,s){_W(n);let a=gg(r),c={certList:t,packageName:n,provisionName:o};i.length>0&&(c.deviceList=i),s.length&&(c.aclPermissionList=s);let l=await $.postAllowFailure(e,{headers:a,params:c});if(!l)throw f("[generateProfile] add provision failed: response is null"),new Error(k.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw f(`[generateProfile] add provision HTTP ${l.statusCode}: ${l.data}`),hg(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw f(`[generateProfile] add provision fail: ${l.data}`),MW(l.data,o),new Error(d.ret?.msg||k.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:h}}}function hg(r,e,t){return r===Qt.FORBIDDEN?e===Ne.OPENPROXY_BLOCKED_URL?new Error(k.ERR_CERT_NETWORK_ERROR):new Error(k.ERR_FORBIDDEN):r===Qt.UNAUTHORIZED?new Error(k.ERR_UNAUTHORIZED):t.includes(Ne.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(k.TEST_PROVISION_EXCEEDS_LIMIT):new Error(k.ADD_PROFILE_FAIL)}function _W(r){if(!r||r.trim().length===0)throw new Error(k.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!xe.BUNDLE_NAME_REGEX.test(r))throw new Error(k.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function MW(r,e){if(r.includes(Ne.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(k.TEST_PROVISION_EXCEEDS_LIMIT);if(r.includes(Ne.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(k.PROFILE_NAME_REPEAT)}async function Lk(r,e){if(!e||e.trim().length===0)return;let t=`${fe.BASE_URL}${fe.PROVISION_DELETE_PATH}?id=${e}`,n=await $.deleteAllowFailure(t,{headers:gg(r)});if(n.statusCode!==200)throw hg(n.statusCode,n.statusText,n.data);let i=JSON.parse(n.data);(!i||!i.ret||i.ret.code!==0)&&Ti(`delete provision failed: ${n.data}`)}function OW(...r){for(let e of r)try{Ii.existsSync(e)&&Ii.unlinkSync(e)}catch(t){Ti(`delete local sign file error: ${t.message}`)}}async function LW(r,e){let t=`${fe.BASE_URL}${fe.CERT_DOWNLOAD_URL_PATH}`,n=gg(r),i={sourceUrls:e},o=await $.postAllowFailure(t,{headers:n,params:i});if(!o)throw Ti("get download list failed: response is null"),new Error(k.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw hg(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Ti("download: The application does not exist"),new Error(s.ret?.msg||k.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function FW(r,e){if(!r||r.length===0)return!1;let t=r[0];return await Ba(t.newUrl,e,t.sha256),!0}function $W(r,e,t,n,i){return jW(r,e),n=n||xe.TARGET_FRIENDLY_NAME,i=i||"",HW(e,t,n,i),!0}function jW(r,e){if(e.lastIndexOf(xe.CERT_BEGIN_HEADER)<0)throw new Error(k.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(xe.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!r.includes(t))throw new Error(k.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function HW(r,e,t,n){let i=r.matchAll(xe.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=UW(l),h=new Date(d.validFrom),y=new Date(d.validTo);if(s<h||s>y){let D=`Certificate is not valid, Valid from ${h} to ${y}`;throw console.warn(`checkCertificateInValidityPeriod: ${D}`),new Error(k.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(k.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(k.CERTIFICATE_HAS_EXPIRED);if(!WW(e,t,n,o))throw new Error(k.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function UW(r){let e="-----BEGIN CERTIFICATE-----",t=r.trim();try{if(t.startsWith(e))return new mg(t);let n=Fk.from(t,"base64");return new mg(n)}catch(n){throw new Error("decodeBase64ToX509Certificate",{cause:n})}}function BW(r){if(r.cert){let e=Ai.pki.publicKeyToPem(r.cert.publicKey);return xW(e).export({type:"spki",format:"der"})}if(r.asn1)try{let e=Ai.asn1.toDer(r.asn1).getBytes(),t=Fk.from(e,"binary");return new mg(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Ti(`Failed to parse cert from asn1: ${e}`),null}return null}function WW(r,e,t,n){try{let i=IW(r),o=Ai.asn1.fromDer(Ai.util.createBuffer(i)),c=Ai.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Ai.pki.oids.certBag})[Ai.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=BW(l);if(!h)continue;if(n.some(D=>{let K=D.publicKey.export({type:"spki",format:"der"});return h.equals(K)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Ti(`Failed to process P12 file: ${r}, error: ${o}`),!1}}function gg(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}var Hk="https://developer.huawei.com",VW={"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"},GW="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function qW(r){let e=VW[r];return e?`${Hk}${e}`:void 0}function zW(){return`${Hk}${GW}`}var JW={"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 jk(r,e){return(JW[r]??r).replace(/\{(\d+)\}/g,(n,i)=>String(e[Number(i)]??""))}function KW(r){return Array.from(r).join(", ")}function Uk(r,e){if(r.size===0)return;let t=$n.getAclPermissionInfos(e),n=new Set;for(let h of t)r.has(h.permissionName)&&n.add(h);for(let h of n){let y=qW(h.permissionName);y!=null&&(h.permissionHelpUrlKey=y)}let i=new Set;for(let h of n)i.add(h.permissionDisplayName);let o=new Set;for(let h of n)if(h.permissionHelpUrlKey!=null){let y=h.permissionInsteadName??h.permissionDisplayName;o.add(`${y} (${h.permissionHelpUrlKey})`)}let s=zW(),a=jk("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=jk("acl.permissions.warn",[KW(i),l,c]);console.log(d)}var Mu=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=W.discover(process.cwd()),{passed:!0,message:""}}catch(t){return f(`[EnvCheck] Project.discover() failed: ${t.message}`),e(be.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(n){return f(`[EnvCheck] Product validation failed: ${n.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(n){return f(`[EnvCheck] BundleName check failed: ${n.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:be.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import YW from"fs";import Bk from"path";var Ou=class{constructor(e){this.toolProvider=e}checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return f(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,n=Bk.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!YW.existsSync(n)){let i=Bk.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Lu=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Ke.getUserInfo()}catch(e){return f(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Ke.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(be.LOGIN_REQUIRED)}catch(t){return f(`[EnvCheck] Login check failed: ${t.message}`),e(be.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(be.TEAM_INFO_FAILED);try{if((await Pn()).teamList.length>0)return{passed:!0,message:""}}catch(n){return f(`[EnvCheck] Team API error: ${n.message}`),e(be.TEAM_INFO_FAILED)}return f("[EnvCheck] No teams found for current user"),e(be.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(be.REALNAME_REQUIRED):t.isRealName!==!0?(f("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(be.REALNAME_REQUIRED)):{passed:!0,message:""}:e(be.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let n=e??"";try{let i=await Pn();if(n=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===n)){let s=`team-id for ${n} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return f(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return f(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${n} 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(be.REGION_CHINA_ONLY):{passed:!0,message:""}:(f("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(be.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function XW(r){try{let{teamList:e}=await Pn();if(e.length>0)return e[0].id}catch(e){f(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return r??""}async function ZW(r){let e=await Ke.getUserInfo(),t=await Ke.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let n=r||await XW(e.userId);if(!n)throw new Error("No team found");let i={uid:e.userId??"",teamId:n,accessToken:t.accessToken};return(await _u(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Fu=class{constructor(e){this.toolProvider=e}async checkDevice(e,t){try{let n=await ZW(t);if(n.length>0)return f(`[EnvCheck] Scenario 4 Device check: ${n.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};f("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await ce.from(this.toolProvider).listDevices();return o.length===0?(f("[EnvCheck] Scenario 4 Device check: no local devices found"),e(be.DEVICE_MISSING)):o.some(a=>ur(a.serial))?{passed:!0,message:""}:(f("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(be.DEVICE_MISSING))}catch(n){return f(`[EnvCheck] Scenario 4 Device check failed: ${n.message}`),e(be.DEVICE_DETECT_FAILED)}}};var $u=class{projectChecker=new Mu;toolchainChecker=null;authChecker=new Lu;deviceChecker=null;constructor(){}async preflight(e){let t=n=>this.blockingFail(n);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||e.type!=="release"&&!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let n=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let o of i)if(!n(await o()))return!1;return!(e.teamId&&!n(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await P.new();return this.toolchainChecker=new Ou(e),this.deviceChecker=new Fu(e),!0}catch(e){throw f(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(be.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let n=o=>o.passed?!0:(this.fail(o),!1);if(!n(this.projectChecker.checkProjectDir(t))||!n(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!n(o()))return!1;return!0}async runAuxChecks(e){let t=n=>n.passed?!0:(this.fail(n),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(n=>this.blockingFail(n)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw f(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var Wk=5*1024*1024;function tV(r){try{let e=Ni.statSync(r);if(e.size>Wk)throw new Error(`Profile file too large: ${e.size} bytes (max ${Wk} bytes): ${r}`);let t=Ni.readFileSync(r,"utf-8");return qk.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${r}`,{cause:e})}}function rV(r){r.app||(r.app={signingConfigs:[],products:[]}),r.app.signingConfigs||(r.app.signingConfigs=[]),r.app.products||(r.app.products=[])}async function nV(r){if(r.keyPwd===r.storePassword){let n=await Fn.encryptedPassword(r.keyPwd,r.p12FilePath);return{keyPassword:n,storePassword:n}}let e=await Fn.encryptedPassword(r.keyPwd,r.p12FilePath),t=await Fn.encryptedPassword(r.storePassword,r.p12FilePath);return{keyPassword:e,storePassword:t}}async function zk(r,e,t,n){let i=wg.join(r,"build-profile.json5"),o=tV(i);rV(o);let s=n==="release"?`${t??"default"}_release`:t??"default",{keyPassword:a,storePassword:c}=await nV(e),l={name:s,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:a,profile:e.profileFilePath,signAlg:Zr.signAlg,storeFile:e.p12FilePath,storePassword:c}},d=o.app?.signingConfigs?.findIndex(y=>y.name===s);d!==void 0&&d>=0?o.app.signingConfigs[d]=l:o.app.signingConfigs.push(l);let h=o.app?.products?.findIndex(y=>y.name===t);h!==void 0&&h>=0?o.app.products[h].signingConfig=s:o.app.products.push({name:t,signingConfig:s}),Ni.writeFileSync(i,qk.stringify(o,null,2),"utf-8")}async function iV(r){let e=await Ke.getUserInfo(),t=await Ke.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:r.teamId??e.userId??"",accessToken:t.accessToken??""}}var Vk=["debug","release"];async function oV(r){let e=r.product||"default";if(r.type&&!Vk.includes(r.type))throw new Error(`Invalid signing type '${r.type}'. Valid types: ${Vk.join(", ")}`);await new $u().preflight({productName:e,teamId:r.teamId,type:r.type}),await rt.warnInvalidBundledLinks(W.discover(process.cwd()).rootDir),console.log("Executing signature generate command");let n=await iV(r),i=await P.new(),{shouldRegenerate:o}=await Ga.shouldRegenerate({force:r.force??!1,teamId:n.teamId,productName:r.product,type:r.type},i);if(!o){console.log(yg("Signature generation completed successfully."));return}await sV(r,n,i)||(process.exitCode=1)}async function sV(r,e,t){if(r.type==="release"&&await cV(r))return!1;let n=await ig(e,r.product,r.type),i=lV(r,e,n,t);r.type!=="release"&&(i.allDeviceIds=await Tk(e,t.hdcPath));try{await $k(e,i)}catch(s){if(r.type==="release")return aV(r,n);throw s}let o=W.discover(process.cwd()).rootDir;return await zk(o,n,r.product??"default",r.type),console.log(yg(`Signing config written to ${wg.join(o,"build-profile.json5")}`)),console.log(yg("Signature generation completed successfully.")),!0}async function aV(r,e){let t=r.product||"default",n=W.discover(process.cwd()).rootDir;return await zk(n,e,t,r.type),console.warn(Gk(`
|
|
1398
|
+
Release certificate materials generated successfully, but the release Profile (.p7b) cannot be auto-generated.
|
|
1399
|
+
Signing config (with encrypted p12 password) has been written to build-profile.json5.
|
|
1400
|
+
Please go to AGC (https://developer.huawei.com/consumer/cn/doc/doccenter-deveco-studio/ide-publish-app#section1079214271414) to manually apply for a release Profile:
|
|
1401
|
+
1. Use the generated .csr file to apply for a release certificate
|
|
1402
|
+
2. Apply for and download the release Profile (.p7b)
|
|
1403
|
+
3. Set the profile path in the '${t}_release' signing config in build-profile.json5
|
|
1404
|
+
4. Build with: devecocli build --assemble-type assembleHap --build-mode release --signing-config ${t}_release
|
|
1405
|
+
|
|
1406
|
+
Generated files:
|
|
1407
|
+
p12: ${e.p12FilePath}
|
|
1408
|
+
csr: ${e.csrFilePath}
|
|
1409
|
+
cer: ${e.cerFilePath}
|
|
1410
|
+
|
|
1411
|
+
Signing config '${t}_release' written to ${wg.join(n,"build-profile.json5")}
|
|
1412
|
+
`)),!1}async function cV(r){let e=W.discover(process.cwd()).rootDir,t=r.product||"default",n=await Eu(t,e,r.type),i=Ni.existsSync(n.p12Path)&&Ni.existsSync(n.csrPath)&&Ni.existsSync(n.certPath),o=Ni.existsSync(n.profilePath);return!i||o?!1:(console.warn(Gk(`
|
|
1413
|
+
Release certificate materials already exist. Profile (.p7b) is still missing.
|
|
1414
|
+
Please go to AGC (https://developer.huawei.com/consumer/cn/doc/doccenter-deveco-studio/ide-publish-app#section1079214271414) to manually apply for a release Profile:
|
|
1415
|
+
1. Use the generated .csr file to apply for a release certificate
|
|
1416
|
+
2. Apply for and download the release Profile (.p7b)
|
|
1417
|
+
3. Set the profile path in the '${t}_release' signing config in build-profile.json5
|
|
1418
|
+
4. Build with: devecocli build --assemble-type assembleHap --build-mode release --signing-config ${t}_release
|
|
1419
|
+
|
|
1420
|
+
Existing files:
|
|
1421
|
+
p12: ${n.p12Path}
|
|
1422
|
+
csr: ${n.csrPath}
|
|
1423
|
+
cer: ${n.certPath}
|
|
1424
|
+
`)),!0)}function lV(r,e,t,n){let i=process.cwd(),o=W.discover(i),s=Tu(o,n);return Uk(s,o),{productName:r.product||"default",bundleName:o.getBundleName(r.product||"default"),projectPath:o.rootDir,teamId:e.teamId,force:r.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd,type:r.type||"debug"}}var Jk=new QW("signature").description("Generate application signature.");Jk.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("--type <type>","Signing type: debug or release (default: debug)").action(async r=>{let e={event:v.CommandExecuted,args:["signature","generate",...r.force?["--force"]:[],...r.teamId?["--team-id"]:[],...r.product?["--product"]:[],...r.type?["--type"]:[]]},t=Date.now(),n=!0,i=null;try{await oV(r)}catch(o){n=!1,i=Z(o),console.error(eV(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:n,error_code:i};await R.track(e,o)}});var Kk=Jk;import{Command as vV}from"commander";import{green as bV,red as Dg}from"colorette";import es from"fs";import Uu from"path";import SV from"ora";import ju from"fs";import vg from"path";import{homedir as dV}from"os";function Yk(){let r=process.env.DEVECO_CLI_DATA_DIR?j():vg.join(dV(),Se.CONFIG_DIR_NAME,Se.APP_NAME);return vg.join(r,"ui_verification_config.json")}function Xk(){let r=Yk();if(!ju.existsSync(r))return{};try{let e=JSON.parse(ju.readFileSync(r,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function bg(){let r=Xk();if(Object.keys(r).length===0)return null;let e;if($m(r.encryptedApiKey))try{e=Fm(r.encryptedApiKey)}catch{}return{baseUrl:typeof r.baseUrl=="string"?r.baseUrl:void 0,modelName:typeof r.modelName=="string"?r.modelName:void 0,apiKey:e}}function Sg(r){let e=Yk();ju.mkdirSync(vg.dirname(e),{recursive:!0,mode:448});let t=Xk();return r.baseUrl!==void 0&&(t.baseUrl=r.baseUrl),r.modelName!==void 0&&(t.modelName=r.modelName),r.apiKey!==void 0&&(t.encryptedApiKey=Lm(r.apiKey),delete t.apiKey),ju.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384}),e}import Hu from"fs";import uV from"os";import Zk from"path";var _i=Zk.join(uV.tmpdir(),"ui-verification","cache"),pV=15;function Eg(r=_i,e=pV){if(!Hu.existsSync(r))return;let t=Hu.readdirSync(r,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>{let i=Zk.join(r,n.name);return{entryPath:i,mtime:Hu.statSync(i).mtimeMs}}).sort((n,i)=>n.mtime-i.mtime);for(let n of t.slice(0,Math.max(0,t.length-e)))Hu.rmSync(n.entryPath,{recursive:!0,force:!0})}import{execFile as fV,spawn as mV}from"child_process";import hV from"fs";import Pg from"path";import{fileURLToPath as gV}from"url";function yV(){let r=Pg.dirname(gV(import.meta.url));for(;;){let e=Pg.join(r,"node_modules","ui-verification-mcp","bin","ui-verification-mcp.cjs");if(hV.existsSync(e))return e;let t=Pg.dirname(r);if(t===r)break;r=t}throw new Error("ui-verification-mcp is not installed. Run `npm install` and try again.")}var qa=class r{constructor(e){this.child=e;this.stopped=new Promise(n=>e.once("close",()=>n())),e.stdout?.on("data",n=>{this.buffer+=n.toString();let i=this.buffer.split(`
|
|
1425
|
+
`);this.buffer=i.pop()??"";for(let o of i)if(o.trim())try{this.handleMessage(JSON.parse(o))}catch{}});let t=n=>{this.closedError??=n;for(let i of this.pending.values())i.reject(n);this.pending.clear(),this.progressHandlers.clear()};e.on("error",t),e.on("exit",(n,i)=>{let o=n===null?`signal ${i??"unknown"}`:`code ${n}`;t(new Error(`ui-verification-mcp exited with ${o}`))})}buffer="";nextId=1;pending=new Map;progressHandlers=new Map;closedError;closePromise;stopped;abortCleanup;handleMessage(e){if(!("id"in e)){if(e.method!=="notifications/progress")return;let i=e.params;if(i?.progressToken===void 0||i.progress===void 0)return;this.progressHandlers.get(i.progressToken)?.(i.progress,i.total,i.message);return}let t=e.id;if(typeof t!="number")return;let n=this.pending.get(t);n&&(this.pending.delete(t),n.resolve(e))}sendAndWait(e,t,n,i="MCP request timed out"){return new Promise((o,s)=>{if(this.closedError){s(this.closedError);return}this.registerPending(e,o,s,n,i);try{this.child.stdin?.write(`${JSON.stringify(t)}
|
|
1426
|
+
`)}catch(a){let c=this.pending.get(e);this.pending.delete(e),c?.reject(a instanceof Error?a:new Error(String(a)))}})}registerPending(e,t,n,i,o="MCP request timed out"){let s=!1,a=i===void 0?void 0:setTimeout(()=>{s||(s=!0,this.pending.delete(e),n(new Error(o)))},i),c=()=>{a!==void 0&&clearTimeout(a)};this.pending.set(e,{resolve:l=>{s||(s=!0,c(),t(l))},reject:l=>{s||(s=!0,c(),n(l))}})}static async start(e,t){t?.throwIfAborted();let n=yV();f(`Executing: ${process.execPath} ${n}`);let i=mV(process.execPath,[n],{env:e,detached:process.platform!=="win32",stdio:["pipe","pipe","ignore"]}),o=new r(i);o.attachCancellation(t);try{return await o.sendAndWait(0,{jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"devecocli",version:"1.0.0"}}}),o}catch(s){throw await o.close(s instanceof Error?s:new Error(String(s))),s}}async callTool(e,t,n,i){let o=this.nextId++;n&&this.progressHandlers.set(o,n);try{let s=await this.sendAndWait(o,{jsonrpc:"2.0",id:o,method:"tools/call",params:{name:e,arguments:t,...n?{_meta:{progressToken:o}}:{}}},i,`${e} timed out after ${Math.floor((i??0)/6e4)} minutes`);if(s.error){let l=s.error;throw new Error(String(l.message??`${e} failed`))}let a=s.result;if(a?.structuredContent!==void 0)return a.structuredContent;let c=a?.content;return c?.length&&typeof c[0].text=="string"?c[0].text:a}finally{this.progressHandlers.delete(o)}}attachCancellation(e){if(!e)return;let t=()=>{let n=e.reason;this.close(n instanceof Error?n:new Error("Verification cancelled by user"))};e.addEventListener("abort",t,{once:!0}),this.abortCleanup=()=>e.removeEventListener("abort",t),e.aborted&&t()}close(e=new Error("ui-verification-mcp session closed")){if(this.closePromise)return this.closePromise;this.closedError??=e,this.abortCleanup?.(),this.abortCleanup=void 0;for(let t of this.pending.values())t.reject(e);return this.pending.clear(),this.progressHandlers.clear(),this.closePromise=this.terminateProcessTree(),this.closePromise}async terminateProcessTree(){if(!this.child.pid){await this.stopped;return}if(process.platform==="win32"){let t=["/pid",String(this.child.pid),"/t","/f"];f(`Executing: taskkill ${t.join(" ")}`),await new Promise(n=>fV("taskkill",t,()=>n())),await this.stopped;return}this.killProcessGroup("SIGTERM");let e=setTimeout(()=>this.killProcessGroup("SIGKILL"),1e3);try{await this.stopped}finally{clearTimeout(e),this.killProcessGroup("SIGKILL")}}killProcessGroup(e){try{process.kill(-this.child.pid,e)}catch(t){if(t.code!=="ESRCH")throw t}}};import Qk from"fs";import Rg from"path";async function kg(r,e){let t=await new le(r).listTargets();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(e){let n=e.toLowerCase(),i=t.filter(o=>o.id===e||o.name.toLowerCase().includes(n));if(i.length===1)return i[0].id;throw i.length>1?new Error(`Multiple devices match '${e}'. Use a serial instead:
|
|
1427
|
+
${Cg(i)}`):new Error(`Device '${e}' not found.
|
|
1378
1428
|
Available devices:
|
|
1379
|
-
${
|
|
1429
|
+
${Cg(t)}`)}if(t.length===1)return t[0].id;throw new Error(`Multiple devices connected. Use --device <name|serial> to specify one.
|
|
1380
1430
|
Available devices:
|
|
1381
|
-
${
|
|
1382
|
-
`)}var
|
|
1383
|
-
`).filter(i=>i.includes(
|
|
1384
|
-
`).join(""),!t)){console.log(`The log does not contain the keyword '${
|
|
1385
|
-
${t.slice(-
|
|
1431
|
+
${Cg(t)}`)}function Cg(r){return r.map(e=>` - ${e.name} (${e.id})`).join(`
|
|
1432
|
+
`)}var Hn=class extends Error{exitCode;constructor(e){super("Verification cancelled by user"),this.exitCode=e==="SIGINT"?130:143}};var wV=600*1e3,za=class{async verifyUi(e,t,n){let i=this.resolveBundleName(e.bundleName),o=await P.new(),s=await kg(o,e.device),a=new AbortController,c=()=>a.abort(new Hn("SIGINT")),l=()=>a.abort(new Hn("SIGTERM"));process.on("SIGINT",c),process.on("SIGTERM",l);let d;try{d=await this.startSession(t,o.hdcPath,a.signal);let h=await d.callTool("verifyUI",{testPlan:e.testPlan,bundleName:i,freshStart:e.freshStart,device:s},n,wV),y=this.parseVerifyResult(h);return await this.cacheArtifacts(d,y.id,a.signal),a.signal.throwIfAborted(),Eg(),y}finally{try{await d?.close()}finally{process.off("SIGINT",c),process.off("SIGTERM",l)}}}startSession(e,t,n){return qa.start({...process.env,UI_VERIFY_BASE_URL:e.baseUrl,UI_VERIFY_API_KEY:e.apiKey,UI_VERIFY_MODEL_NAME:e.modelName,UI_VERIFY_HDC_PATH:t},n)}parseVerifyResult(e){if(typeof e=="object"&&e!==null)return e;if(typeof e=="string")try{return JSON.parse(e)}catch{throw new Error(e)}throw new Error("Failed to parse verifyUI result.")}resolveBundleName(e){if(e)return e;try{return W.discover(process.cwd()).getBundleName()}catch(t){throw new Error("Could not resolve bundleName from AppScope/app.json5. Please specify --bundle-name <name>.",{cause:t})}}async cacheArtifacts(e,t,n){let i=Rg.join(_i,t),o=Rg.join(i,"screenshots");Qk.mkdirSync(o,{recursive:!0});try{let s=await e.callTool("getLog",{id:t,maxLogSize:-1});Qk.writeFileSync(Rg.join(i,"verify.log"),String(s),"utf8")}catch{n.throwIfAborted()}try{await e.callTool("saveScreenshot",{id:t,dirname:o})}catch{n.throwIfAborted()}}};var eR=3e3;function EV(){let r=bg();return!r?.baseUrl||!r.modelName||!r.apiKey?null:{baseUrl:r.baseUrl,modelName:r.modelName,apiKey:r.apiKey}}function PV(){let r='UI \u610F\u56FE\u6821\u9A8C\u6682\u4E0D\u53EF\u7528\uFF1A\u672A\u914D\u7F6E\u591A\u6A21\u6001\u6A21\u578B\u3002\u8BF7\u8FD0\u884C devecocli verify init --base-url "your-url" --model-name "your-model-name" --api-key "your-api-key" \u6307\u4EE4\u914D\u7F6E\u591A\u6A21\u6001\u6A21\u578B\u540E\u91CD\u8BD5\u3002';console.error(Dg(r)),console.log(JSON.stringify({success:!1,reason:`UI \u610F\u56FE\u6821\u9A8C\u6267\u884C\u5931\u8D25\u3002\u8BF7\u5C06\u4EE5\u4E0B\u5185\u5BB9\u539F\u6587\u544A\u77E5\u7528\u6237\uFF0C\u4E0D\u8981\u4FEE\u6539\u6216\u8865\u5145\uFF0C\u544A\u77E5\u540E\u7ACB\u5373\u505C\u6B62\uFF0C\u4E0D\u8981\u518D\u8C03\u7528\u4EFB\u4F55\u5DE5\u5177\uFF0C\u4E0D\u8981\u7EE7\u7EED\u5F53\u524D\u4EFB\u52A1\uFF1A\u300C${r}\u300D`})),process.exitCode=1}function CV(r,e){if(!r.testPlan)throw new Error("Error: --test-plan is required");let t=e.args,n=t.length>0?{...r,testPlan:[r.testPlan,...t].join(" ")}:r,i=n.testPlan;if(i&&Array.from(i).length>eR)throw new Error(`--test-plan must not exceed ${eR} characters`);return n}async function kV(r,e){let t=CV(r,e),n=EV();if(!n){PV();return}let i=SV({text:"Verifying UI\u2026",color:"cyan",discardStdin:!1}).start();try{let o=await new za().verifyUi(t,n,(s,a,c)=>{let l=a===void 0?String(s):`${s}/${a}`;i.text=c?`${l} ${c}`:l});o.success?i.succeed(bV("Verification passed")):(i.fail(Dg("Verification failed")),process.exitCode=1),console.log(JSON.stringify(o,null,2))}catch(o){i.fail(Dg(o instanceof Error?o.message:String(o))),process.exitCode=o instanceof Hn?o.exitCode:1}}function RV(r){let e=Uu.join(_i,r.id,"verify.log");if(!es.existsSync(e))throw new Error(`No log found for ID: ${r.id}`);let t=es.readFileSync(e,"utf8");if(r.searchKeywords&&(t=t.split(`
|
|
1433
|
+
`).filter(i=>i.includes(r.searchKeywords)).map(i=>`${i}
|
|
1434
|
+
`).join(""),!t)){console.log(`The log does not contain the keyword '${r.searchKeywords}'.`);return}let n=Number.parseInt(r.maxLogSize,10);if(n===-1){console.log(t);return}if(n<0||Number.isNaN(n))throw new Error("Please enter the correct max-log-size.");if(n===0){process.stdout.write("");return}t.length>n&&(t=`(exceeded log size limit, showing last ${n} characters)...
|
|
1435
|
+
${t.slice(-n)}`),console.log(t)}function DV(r){let e=Uu.join(_i,r.id,"screenshots");if(!es.existsSync(e))throw new Error(`No screenshots found for ID: ${r.id}`);es.mkdirSync(r.savePath,{recursive:!0});let t=es.readdirSync(e).map(n=>{let i=Uu.join(r.savePath,n);return es.copyFileSync(Uu.join(e,n),i),i});console.log(JSON.stringify({filenames:t,message:"Screenshots saved successfully"},null,2))}var Bu=new vV("verify").description("Run UI verification on a connected device").option("--test-plan <plan>","Natural-language test plan describing steps and expected results").option("--bundle-name <name>","Bundle name of the app to be tested").option("--no-fresh-start","Skip relaunching the app before verification").option("--device <name|serial>","Target device name or serial").allowExcessArguments(!0).action(kV);Bu.command("init").description("Configure the vision model for UI verification").option("--base-url <url>","Base URL of the vision model").option("--model-name <name>","Vision model name").option("--api-key <key>","API key for the vision model").action(r=>{if(!r.baseUrl&&!r.modelName&&!r.apiKey)throw new Error("Error: at least one of --base-url, --model-name, --api-key is required");let e=Sg(r);console.log(`UI verification config saved to ${e}`)});Bu.command("log").description("Get verification log by ID").requiredOption("--id <id>","Verification task ID").option("--search-keywords <keywords>","Filter log by keywords").option("--max-log-size <n>","Max characters to show (-1 for unlimited)","5000").action(RV);Bu.command("screenshot").description("Save verification screenshots by ID").requiredOption("--id <id>","Verification task ID").requiredOption("--save-path <path>","Absolute path to save screenshots").action(DV);var tR=Bu;function rR(r){let e=r.opts();if(r.name()==="log")return e.format==="json"||e.format==="hilog";if(r.name()!=="status"||e.format!=="json")return!1;let t=r.parent;for(;t!==null;){if(t.name()==="screenrecord")return!0;t=t.parent}return!1}if(!Ze())try{R.init(Wu.join(j(),"TraceLogData")),R.startScheduler()}catch(r){g.error(`[telemetry] init failed: ${r instanceof Error?r.message:String(r)}`)}(async()=>{if(!Ze())try{let r=await P.new();R.setSourceType(r.sourceType);let e=r.readVersion();e&&(r.sourceType==="clt"?R.setCltVersion(e):R.setStudioVersion(e))}catch(r){g.error(`[telemetry] toolchain info failed: ${r instanceof Error?r.message:String(r)}`)}})();me.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1386
1436
|
|
|
1387
|
-
Privacy: ${
|
|
1437
|
+
Privacy: ${rs.PRIVACY_URL}`).version("1.3.10-Test.1");var nR=me.options.find(r=>r.long==="--version");nR&&(nR.flags="-V, -v, --version");me.addCommand(Fw);me.addCommand(bb);me.addCommand(kb);me.addCommand(hS);me.addCommand(US);me.addCommand(dE);me.addCommand(hE);me.addCommand(rP);me.addCommand(mP);me.addCommand(wP);me.addCommand(KP);me.addCommand(tC);me.addCommand(kC);me.addCommand(ak);me.addCommand(Kk);me.addCommand(tR);for(let r=2;r<process.argv.length;r++){let e=process.argv[r];if(e==="-v"){process.argv[r]="-V";break}if(!e.startsWith("-"))break}var xg=process.argv.slice(2);xg.length>=2&&xg[xg.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function IV(r){let e=r;for(;e.parent&&e.parent!==me;)e=e.parent;return e}var AV=new Set(["update","auth","serve"]);me.hook("preAction",async(r,e)=>{await zy().catch(()=>{});let t=IV(e),n=Hi();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new sn(Wu.join(j(),"update")),o=cr();if(n==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||AV.has(t.name())||await P.checkVersion()});me.hook("postAction",async(r,e)=>{if(process.exitCode||Hi()!=="off"||rR(e))return;await new gs(e).checkAndNotify()});me.parseAsync(process.argv).finally(()=>{R.stopScheduler();try{ip(Wu.join(j(),"TraceLogData"))}catch(r){g.error(`[telemetry] background upload spawn check failed: ${r instanceof Error?r.message:String(r)}`)}}).catch(r=>{let e=r instanceof Error?r.message:String(r??"Unknown error");console.error(xV(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});
|