@deveco-test/deveco-cli 1.3.3-Test.1 → 1.3.3-Test.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -2
- package/SKILL.md +10 -2
- package/dist/cli.js +146 -132
- package/dist/internal/telemetry-upload-background.js +1 -1
- package/docs.zip +0 -0
- package/index.zip +0 -0
- package/package.json +1 -1
- package/src/resources/arkts-check.cjs +3642 -0
- package/templates/application/gitignore.txt +2 -1
package/dist/cli.js
CHANGED
|
@@ -1,83 +1,94 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(o-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let o=0;o<t.length;o++){let i=t[o];if(!r.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}static 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 o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return f(`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(Ee.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Ee.resolve(Ee.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Ee.normalize(e),o=Ee.relative(r,t);if(o.split(Ee.sep)[0]===".."||Ee.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Ee.isAbsolute(e)}static isPathContained(e,t){let r=Ee.resolve(t,e),o=Ee.relative(t,r);return n.isPathEscaping(o)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let o;try{o=vc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=Ee.resolve(o,e),s;try{s=vc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};import pp from"crypto";import Xe from"fs";import xc from"os";import Bn from"path";import Ov from"https";var Hu={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var $i=class n{static ENDPOINT=Hu.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:o}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(o)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,o){let i=new URL(e);return new Promise((s,a)=>{let c=Ov.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},l=>{let d=[];l.on("data",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 Uu={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()},Sc=class{constructor(e={}){this.config=e}config;serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??Uu.identity,r=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=r[i]??t(i);o[a]=this.transform(s)}return o}},Bu=new Sc({namingStrategy:Uu.snakeCase,fieldNames:{}});import wo from"crypto";import Hi from"fs";import Mv from"path";var Ui="aes-256-gcm",_v=12,Fv="deveco-cli-trace-file",jv="trace-file-secret",Vu=32;function Wu(n){try{let e=Hi.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Vu?e:null}catch{return null}}function Gu(n){let e=Mv.join(n,jv),t=Wu(e);if(t)return bc(t);let r=wo.randomBytes(Vu).toString("base64");try{Hi.mkdirSync(n,{recursive:!0});try{Hi.writeFileSync(e,r,{flag:"wx"})}catch{let o=Wu(e);if(o)return bc(o);Hi.writeFileSync(e,r)}}catch{}return bc(r)}function bc(n){return wo.createHash("sha256").update(Fv).update(n).digest()}function Ec(n,e){let t=wo.randomBytes(_v),r=wo.createCipheriv(Ui,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i={version:1,algorithm:Ui,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(i)}function qu(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!$v(t))return n;try{let r=wo.createDecipheriv(Ui,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 $v(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Ui&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as j from"fs";import*as Ji from"path";import Y from"fs";import*as Bi from"os";import*as M from"path";import Hv from"json5";var Cc="Huawei";var Yu=3;function Wi(n){if(!Y.existsSync(n)||!Y.statSync(n).isDirectory())return!1;let e=Y.existsSync(M.join(n,"build-profile.json5")),t=Y.existsSync(M.join(n,"hvigorfile.js"))||Y.existsSync(M.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=Y.readFileSync(M.join(n,"build-profile.json5"),"utf-8");return Hv.parse(r).app!==void 0}catch{return!1}}function Pc(n,e,t){if(e>=t)return null;let r=Uv(n),o=Bv(r);if(o)return o;for(let i of r){let s=Pc(i,e+1,t);if(s)return s}return null}function Uv(n){try{let e=Y.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(M.join(n,r.name));return t}catch{return[]}}function Bv(n){for(let e of n)if(Wi(e))return e;return null}function Lt(n){if(!n||n.trim()==="")return null;let e=M.resolve(n),t;try{t=Y.realpathSync(e)}catch{t=e}if(!Y.existsSync(t))return null;if(Wi(t))return t;let r=t;for(let o=1;o<=3;o++){let i=M.dirname(r);if(i===r)break;if(Wi(i))return i;r=i}if(Y.statSync(t).isDirectory()){let o=Pc(t,0,Yu);if(o)return o}return null}function Vi(n){if(!n||n.trim()==="")return null;let e=M.resolve(n),t;try{t=Y.realpathSync(e)}catch{t=e}return!Y.existsSync(t)||!Y.statSync(t).isDirectory()?null:Wi(t)?t:Pc(t,0,Yu)}var zu="DevEco Studio";function Ku(){if(process.platform==="win32"){let n=[M.join("C:\\Program Files",Cc,zu),M.join("C:\\Program Files (x86)",Cc,zu)];return Ju(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",M.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Ju(n)}return null}function Ju(n){for(let e of n)if(Y.existsSync(e))return e;return null}function vo(n,e){let t=e?M.join("standardIndex","index.js"):"index.js";return Y.existsSync(M.join(n,"ace-server"))?M.join(n,"ace-server","out",t):M.join(n,"out",t)}function Gi(n){return Y.existsSync(vo(n,!0))}var Wv=[".idea",".deveco","cxx","compile_commands.json"];function jn(n){return M.join(n,...Wv)}function Xu(n){return new Promise(e=>setTimeout(e,n))}var Vv=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function $n(n){let e=M.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Vv.has(e)}function qi(n){return M.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ge(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Gv(n){return ge(n)}function Hn(n){let e=Gv(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Xt(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??M.join(Bi.homedir(),"AppData","Local");return M.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?M.join(Bi.homedir(),"Library","Logs","devecocli-mcp-server"):M.join(Bi.homedir(),".local","share","devecocli-mcp-server","logs")}function Zu(n,e){let t=qv(e),r=zv(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Jv(t,n,s);return Yv(e,a),o}function qv(n){let e;try{e=Y.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function zv(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function Jv(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function Yv(n,e){try{Y.mkdirSync(M.dirname(n),{recursive:!0})}catch{}try{Y.writeFileSync(n,e.join(`
|
|
2
|
+
var SS=Object.defineProperty;var bS=(r,e)=>{for(var t in e)SS(r,t,{get:e[t],enumerable:!0})};import*as Nc from"path";import{program as le}from"commander";import{red as NM}from"colorette";var So={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},qi={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 Ee={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"},X={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"},Br={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},bo={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"},Eo={baseUrl:X.LOGIN_URL,authUrl:X.AUTH_APPLY_PATH,tempTokenCheckUrl:X.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:X.JWT_TOKEN_CHECK_PATH,successRedirectUrl:X.LOGIN_SUCCESS_PATH,failedRedirectUrl:X.LOGIN_FAILED_PATH,logoutUrl:X.LOGOUT_PATH,agcTeamListUrl:X.AGC_TEAM_LIST_URL,appId:Ee.APP_ID,timeout:So.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as iE}from"commander";import{green as al,red as ym,yellow as cl}from"colorette";import Q from"fs";import*as j from"path";import Pt from"json5";import*as _c from"fs";import*as Ce from"path";function m(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 o=Number.parseInt(n,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
|
+
`)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return r.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);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,o=new Date){if(!t&&!n)return e;let[i,s]=r.resolveTimeBounds(t,n,o),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=r.extractTimestampFromLogLine(d,o);g&&(l=r.isWithinBounds(g,i,s)),l&&c.push(d)}return c.join(`
|
|
4
|
+
`)}static resolveTimeBounds(e,t,n){let o=e?new Date(n.getTime()-e*1e3):null,i=t?new Date(n.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,n]:i?[null,i]:[null,null]}static isWithinBounds(e,t,n){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=n?Math.floor(n.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>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 o=t.getFullYear(),i=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",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),v=new Date(o,i,s,a,c,l,g);return v.getTime()>t.getTime()+1440*60*1e3&&v.setFullYear(o-1),v}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let n=/^[a-zA-Z0-9_]+$/;for(let o=0;o<t.length;o++){let i=t[o];if(!n.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}static 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 o=n.charCodeAt(0);return o<=r.ASCII_CONTROL_MAX||o===r.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let n=`'${e.replace(/'/g,"'\\''")}'`;return m(`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(Ce.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=Ce.resolve(Ce.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=Ce.normalize(e),o=Ce.relative(n,t);if(o.split(Ce.sep)[0]===".."||Ce.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Ce.isAbsolute(e)}static isPathContained(e,t){let n=Ce.resolve(t,e),o=Ce.relative(t,n);return r.isPathEscaping(o)?{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 o;try{o=_c.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=Ce.resolve(o,e),s;try{s=_c.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return r.isPathContained(s,o)}};import jp from"crypto";import nt from"fs";import Jc from"os";import qr from"path";import CS from"https";var pp={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Ji=class r{static ENDPOINT=pp.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:o}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(o)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),n=t?.code??t?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(e,t,n,o){let i=new URL(e);return new Promise((s,a)=>{let c=CS.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},l=>{let d=[];l.on("data",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(n),c.end()})}};var mp={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()},Fc=class{constructor(e={}){this.config=e}config;serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??mp.identity,n=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=n[i]??t(i);o[a]=this.transform(s)}return o}},fp=new Fc({namingStrategy:mp.snakeCase,fieldNames:{}});import Co from"crypto";import Yi from"fs";import PS from"path";var Ki="aes-256-gcm",AS=12,IS="deveco-cli-trace-file",kS="trace-file-secret",gp=32;function hp(r){try{let e=Yi.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===gp?e:null}catch{return null}}function yp(r){let e=PS.join(r,kS),t=hp(e);if(t)return jc(t);let n=Co.randomBytes(gp).toString("base64");try{Yi.mkdirSync(r,{recursive:!0});try{Yi.writeFileSync(e,n,{flag:"wx"})}catch{let o=hp(e);if(o)return jc(o);Yi.writeFileSync(e,n)}}catch{}return jc(n)}function jc(r){return Co.createHash("sha256").update(IS).update(r).digest()}function $c(r,e){let t=Co.randomBytes(AS),n=Co.createCipheriv(Ki,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i={version:1,algorithm:Ki,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(i)}function vp(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!DS(t))return r;try{let n=Co.createDecipheriv(Ki,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 DS(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===Ki&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as H from"fs";import*as ns from"path";import Z from"fs";import*as Xi from"os";import*as _ from"path";import TS from"json5";var Hc="Huawei";var bp=3;function Zi(r){if(!Z.existsSync(r)||!Z.statSync(r).isDirectory())return!1;let e=Z.existsSync(_.join(r,"build-profile.json5")),t=Z.existsSync(_.join(r,"hvigorfile.js"))||Z.existsSync(_.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=Z.readFileSync(_.join(r,"build-profile.json5"),"utf-8");return TS.parse(n).app!==void 0}catch{return!1}}function Uc(r,e,t){if(e>=t)return null;let n=RS(r),o=xS(n);if(o)return o;for(let i of n){let s=Uc(i,e+1,t);if(s)return s}return null}function RS(r){try{let e=Z.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(_.join(r,n.name));return t}catch{return[]}}function xS(r){for(let e of r)if(Zi(e))return e;return null}function Mt(r){if(!r||r.trim()==="")return null;let e=_.resolve(r),t;try{t=Z.realpathSync(e)}catch{t=e}if(!Z.existsSync(t))return null;if(Zi(t))return t;let n=t;for(let o=1;o<=3;o++){let i=_.dirname(n);if(i===n)break;if(Zi(i))return i;n=i}if(Z.statSync(t).isDirectory()){let o=Uc(t,0,bp);if(o)return o}return null}function Qi(r){if(!r||r.trim()==="")return null;let e=_.resolve(r),t;try{t=Z.realpathSync(e)}catch{t=e}return!Z.existsSync(t)||!Z.statSync(t).isDirectory()?null:Zi(t)?t:Uc(t,0,bp)}var wp="DevEco Studio";function Ep(){if(process.platform==="win32"){let r=[_.join("C:\\Program Files",Hc,wp),_.join("C:\\Program Files (x86)",Hc,wp)];return Sp(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",_.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Sp(r)}return null}function Sp(r){for(let e of r)if(Z.existsSync(e))return e;return null}function Po(r,e){let t=e?_.join("standardIndex","index.js"):"index.js";return Z.existsSync(_.join(r,"ace-server"))?_.join(r,"ace-server","out",t):_.join(r,"out",t)}function es(r){return Z.existsSync(Po(r,!0))}var LS=[".idea",".deveco","cxx","compile_commands.json"];function Wr(r){return _.join(r,...LS)}function Cp(r){return new Promise(e=>setTimeout(e,r))}var NS=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Vr(r){let e=_.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&NS.has(e)}function ts(r){return _.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ve(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function OS(r){return ve(r)}function Gr(r){let e=OS(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function tr(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??_.join(Xi.homedir(),"AppData","Local");return _.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?_.join(Xi.homedir(),"Library","Logs","devecocli-mcp-server"):_.join(Xi.homedir(),".local","share","devecocli-mcp-server","logs")}function Pp(r,e){let t=MS(e),n=_S(t,r);if(n!==null)return n;let o=Date.now(),s=`${r.replace(/:/g,"\\:")}=${o}`,a=FS(t,r,s);return jS(e,a),o}function MS(r){let e;try{e=Z.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function _S(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(n+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function FS(r,e,t){let n=!1,o=r.map(i=>{if(n)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):i});return n||o.push(t),o}function jS(r,e){try{Z.mkdirSync(_.dirname(r),{recursive:!0})}catch{}try{Z.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),i=[];for(let s of o){let a=
|
|
6
|
+
`,"utf8")}catch{}}function Bc(r,e,t="[Cleanup]"){try{let n=_.dirname(r);if(!Z.existsSync(n))return;let o=Date.now();for(let i of Z.readdirSync(n,{withFileTypes:!0}))i.isDirectory()&&$S(_.join(n,i.name),o,e,t)}catch{}}function $S(r,e,t,n){try{let{mtimeMs:o}=Z.statSync(r);if(e-o<=t)return;Z.rmSync(r,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${n} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${r}`)}catch(o){console.error(`${n} Failed to remove expired dir ${r}: ${o}`)}}var Ap="mcp-server.log",HS="mcp-server",US={maxSize:10*1024*1024,maxFiles:4},Wc=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={...US,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=tr(),this.currentLogFile=ns.join(this.logDir,Ap),H.existsSync(this.logDir)||H.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${o}`}getRotatedFileName(e,t){return ns.join(this.logDir,`${HS}-${e}.log.${t}`)}fileExists(e){try{return H.accessSync(e,H.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=H.readdirSync(this.logDir),t=[];for(let o of e)if(o===Ap||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=ns.join(this.logDir,o),s=H.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let o=n;o<t.length;o++)try{H.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&H.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&H.renameSync(i,s)}let n=this.getRotatedFileName(e,1);H.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=H.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=H.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{H.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let o=n.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
|
|
7
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);H.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{H.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},rt=null;function zr(r=!1){rt&&rt.dispose(),rt=new Wc(r)}function Ip(){rt&&(rt.dispose(),rt=null)}function kp(){rt&&rt.flush()}function Dp(){return rt?.getLogFilePath()??null}function Tp(){return rt?.getLogDirectory()??null}function rs(){return rt||zr(!1),rt}var h={debug:(r,...e)=>rs().debug(r,...e),info:(r,...e)=>rs().info(r,...e),warn:(r,...e)=>rs().warn(r,...e),error:(r,...e)=>rs().error(r,...e)};import Vc from"fs";import Rp from"path";var Ao=300*1e3,Io=3600*1e3,Gc=10080*60*1e3;function rr(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var BS="upload-state.json";function xp(r){return Rp.join(r,BS)}function WS(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function os(r){try{let e=Vc.readFileSync(xp(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 WS()}}function zc(r,e){try{Vc.writeFileSync(xp(r),JSON.stringify(e),"utf8")}catch{}}function Lp(r){let e=os(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),zc(r,e))}function Np(r){let e=os(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,zc(r,e)}function Op(r){let e=os(r);e.lastRetryAt=Date.now(),zc(r,e)}function qc(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 VS(r,e=Date.now()){let t=Rp.join(r,"failed"),n;try{n=Vc.readdirSync(t)}catch{return!1}for(let o of n){if(!o.startsWith("telemetry-")||!o.endsWith(".txt"))continue;let i=qc(o);if(i!==null&&e-i<=Gc)return!0}return!1}function Mp(r,e=Date.now()){let t=os(r);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Ao||VS(r,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Io))}import GS from"crypto";import is from"fs";import zS from"path";var qS="install-id";function JS(r){return zS.join(r,qS)}function _p(r){try{let e=is.readFileSync(r,"utf8").trim();return YS(e)?e:null}catch{return null}}function YS(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 Fp(r){let e=JS(r),t=_p(e);if(t)return t;let n=GS.randomUUID();try{is.mkdirSync(r,{recursive:!0});try{is.writeFileSync(e,n,{flag:"wx"})}catch{let o=_p(e);if(o)return o;is.writeFileSync(e,n)}}catch{}return n}var ko=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 Ji;storageDir="";failedDir="";installId="";disabled=rr();traceFileKey=Buffer.alloc(0);sessionId=jp.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.info(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=qr.join(e,"failed"),this.cliVersion="1.3.3-Test.2",this.nodeVersion=process.version,this.installId=Fp(e).replace(/-/g,""),this.traceFileKey=yp(e),nt.mkdirSync(e,{recursive:!0}),nt.mkdirSync(this.failedDir,{recursive:!0}),h.info(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,h.info(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.info(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.info(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let n=t,o=Date.now();try{let i=await n(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=this.toErrorCode(i);throw await this.record(e,s,!1,a),i}}async record(e,t,n,o){let i=this.buildTraceEvent(e,t,n,o);try{let s=$c(JSON.stringify(i),this.traceFileKey);await nt.promises.appendFile(this.currentFile(),s+`
|
|
8
|
+
`,"utf8"),Lp(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=fp.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:jp.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,duration_ms:t,success:n,error_code:o,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=Jc.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Jc.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 Jc.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}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 qr.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){h.info("[telemetry] scheduler not started (telemetry disabled)");return}h.info(`[telemetry] scheduler started (flush every ${Ao/1e3}s, retry failed every ${Io/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Ao)},Ao),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Io)},Io)}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),h.info("[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 Np(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.");let e=Date.now(),t;try{t=await nt.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>qr.join(this.failedDir,i)),o=!0;for(let i of n){let s=qr.basename(i),a=qc(s);if(a!==null){if(e-a>Gc){try{await nt.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||h.warn("[telemetry] retry failed"),Op(this.storageDir),o}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await nt.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>qr.join(this.storageDir,t)).sort()}async flushFile(e){let t=e+".pending";try{await nt.promises.rename(e,t)}catch{return!1}let n;try{n=await nt.promises.readFile(t,"utf8")}catch{return!1}let o=n.split(`
|
|
9
|
+
`).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let a=vp(s,this.traceFileKey);a!==null&&i.push(a)}if(i.length===0){try{await nt.promises.unlink(t)}catch{}return!0}return this.uploadInBatches(t,i)}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let o=n,i=[],s=16;for(;n<t.length&&i.length<r.MAX_BATCH;){let d=t[n],g=Buffer.byteLength(d,"utf8")+1;if(i.length>0&&s+g>r.MAX_PAYLOAD_BYTES)break;i.push(d),s+=g,n++}let a=this.buildPayloadItems(i),c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){h.warn("[telemetry] upload failed");let d=t.slice(o).join(`
|
|
10
10
|
`)+`
|
|
11
|
-
`;return await this.moveToFailed(e,d),!1}}try{await
|
|
12
|
-
`).filter(Boolean).map(s
|
|
11
|
+
`;return await this.moveToFailed(e,d),!1}}try{await nt.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let o=JSON.parse(n);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=qr.basename(e,".pending"),o=qr.join(this.failedDir,n);try{let i=t.split(`
|
|
12
|
+
`).filter(Boolean).map(s=>$c(s,this.traceFileKey)).join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`;await Xe.promises.appendFile(o,i,"utf8")}catch{return}try{await Xe.promises.unlink(e)}catch{}}};var D=new Eo;import{spawn as aS}from"child_process";import{existsSync as cS}from"fs";import{dirname as lS,join as dS}from"path";import{fileURLToPath as uS}from"url";function pS(){let n=lS(uS(import.meta.url)),e=dS(n,"internal","telemetry-upload-background.js");return cS(e)?e:null}function Lc(n){if(Zt()||!lp(n))return;let e=pS();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{aS(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 v=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function W(n){if(n instanceof v)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var S={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var De={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 X=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 o=F.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=F.join(e,"build-profile.json5");if(!K.existsSync(t))return null;try{let r=K.readFileSync(t,"utf-8"),o=bt.parse(r);return o.app?o: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(i=>i.name===e);if(!t)throw new v(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),o=F.join(r,"src","main","module.json5");if(!K.existsSync(o))return"entry";try{let i=K.readFileSync(o,"utf-8");return bt.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=F.normalize(e);for(let r of this.profile.modules){let o=F.normalize(F.join(this.rootDir,r.srcPath)),i=o+F.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)throw new v(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=b.resolvePathWithinRoot(this.rootDir,t.srcPath),o=F.join(r,"build-profile.json5");if(!K.existsSync(o))throw new v(`Build profile for module '${e}' not found at ${o}.`,"Build profile for module not found at ${profilePath}.");try{let i=K.readFileSync(o,"utf-8");return bt.parse(i)}catch(i){throw new Error(`Failed to parse module build profile at ${o}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}getBundleName(e){if(e){let r=this.profile.app.products?.find(o=>o.name===e);if(r?.bundleName)return r.bundleName}let t=F.join(this.rootDir,"AppScope","app.json5");if(K.existsSync(t))try{let r=K.readFileSync(t,"utf-8"),o=bt.parse(r);if(o?.app?.bundleName)return o.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=F.join(this.rootDir,"AppScope","app.json5");if(!K.existsSync(e))return!1;try{let t=K.readFileSync(e,"utf-8");return bt.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 o=b.resolvePathWithinRoot(this.rootDir,r.srcPath),i=F.join(o,"src","main","module.json5");if(!K.existsSync(i))return"EntryAbility";try{let s=K.readFileSync(i,"utf-8"),c=bt.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 ${i}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new v(`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(o=>o.name).join(", ")||"none";throw new v(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)return[];let r=this.readLockFinalLocalModuleDeps(e);return r!==null?r:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=F.join(this.rootDir,De.LOCK_JSON5_PATH);if(!K.existsSync(t))return null;let r;try{r=bt.parse(K.readFileSync(t,"utf-8"))}catch(d){return f(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let o=r,i=o?.modules;if(!i||typeof i!="object")return null;let s=Object.values(i).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(o.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,w=>this.resolveLockDepByVersion(w),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 o=t.get(e);if(o){let i=this.resolveLocalDepToModule(o);if(i)return i}}return r()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[r,o]of Object.entries(e))typeof o=="string"&&t.set(r,o);return t.size>0?t:null}resolveLocalDepToModule(e){let t=n.stripLocalDep(e);if(!t)return null;let r=F.resolve(this.rootDir,t),o;try{o=b.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let i=this.profile.modules.find(s=>F.resolve(this.rootDir,s.srcPath)===o);return i?i.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=F.join(b.resolvePathWithinRoot(this.rootDir,e.srcPath),De.OH_PACKAGE_JSON5);if(!K.existsSync(t))return[];let r=this.readRootOverrideMap(),o=[],i=new Set;try{let s=bt.parse(K.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),o,i)}}catch(s){f(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return o}readRootOverrideMap(){let e=F.join(this.rootDir,De.OH_PACKAGE_JSON5);if(!K.existsSync(e))return null;try{let t=bt.parse(K.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,o,i){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>r(a));c&&!i.has(c)&&(i.add(c),o.push(c))}}resolveLocalDepModuleName(e,t){let r=n.stripLocalDep(e);if(!r)return null;let o=F.join(t.srcPath,r),i=b.resolvePathWithinRoot(this.rootDir,o),s=this.profile.modules.find(a=>F.resolve(this.rootDir,a.srcPath)===i);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],r=[],o=new Set;for(r.push(e),o.add(e);r.length>0;){let i=r.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(r.push(c),o.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let o=this.profile.modules.find(l=>l.name===e);if(!o){let l=this.getRunnableModuleNames();throw new v(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let i=this.getModuleType(e)==="shared",s=i?"hspName":"hapName",a=this.buildOutputPath(o.srcPath,r,["intermediates",i?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!K.existsSync(a))throw new v(`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:o,isShared:i,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,o="default"){let{moduleNode:i,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,o),{packageName:c,isSigned:l}=a,d=c;if(!l){let C=this.getSignedHapName(c,i.srcPath,o,t);C&&(d=C)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new v(`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 w=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!K.existsSync(w))throw new v(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:o,metadata:i}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of i.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=F.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!K.existsSync(l))throw new v(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,r,["outputs",o,i]);return K.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=b.resolvePathWithinRoot(this.rootDir,e),i=F.resolve(o,"build",t,...r);return b.ensurePathWithinRoot(this.rootDir,i)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(o=>!!(o.hspName&&o.hspPath)).map(o=>({hspName:o.hspName,hspPath:o.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=K.readFileSync(e,"utf-8");r=bt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let o,i=!1,s=Array.isArray(r)?r:[r];for(let c of s)o||(o=c[t]),i||(i=c.isSigned===!0);if(!o)throw new v(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(o);let a=this.collectRemoteHsps(s);return{packageName:o,isSigned:i,dependRemoteHsps:a}}validatePackageName(e){let t=F.basename(e);if(t!==e)throw new v(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new v(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import ke from"fs";import*as Ge from"os";import*as P from"path";import Zi from"fs";import*as Qi from"os";import*as Co from"path";import gS from"regedit";import{execFileSync as fS}from"child_process";import fp from"fs";import*as hp from"os";import*as Nc from"path";import{compare as mS}from"semver";function mp(n,e){return mS(n,e)}function pr(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let o=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(o)return o}return 0}function Xi(n,e){let t=Nc.join(n,"Contents","Info.plist");if(!fp.existsSync(t)){f(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=fS(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function hS(n){let e=Xi(n,"CFBundleShortVersionString");if(!e)return Xi(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Xi(n,"CFBundleVersion"),Xi(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function Qt(n){if(hp.platform()==="darwin")return hS(n);let e=Nc.join(n,"product-info.json");try{let t=JSON.parse(fp.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var yS="DevEco Studio",wS=["Contents","Resources","product-info.json"],vS="name";function SS(n){return n.filter(e=>{try{return Zi.statSync(e).isDirectory()}catch{return!1}})}function bS(n){let e=Co.join(n,...wS);if(Zi.existsSync(e))try{let r=JSON.parse(Zi.readFileSync(e,"utf8"))[vS];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function ES(n){return bS(n)===yS}function CS(){let n=[];for(let e of[Co.join(Qi.homedir(),"Applications"),"/Applications"])try{n.push(...Zi.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>Co.join(e,t)).filter(ES))}catch{}return n}function gp(n){return new Promise((e,t)=>gS.list(n,(r,o)=>r?t(r):e(o)))}async function yp(n,e,t){let o=((await gp([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await gp(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function PS(){let n=[Co.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 yp(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 yp(e,()=>!0,""))}catch{}return n}async function wp(){let n=Qi.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"?CS():await PS(),t=SS(e).flatMap(r=>{let o=Qt(r);return o?(f(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(f(`[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,o)=>pr(o.version,r.version)>0?o:r)}import*as vp from"fs";import*as Oe from"path";function Po(n,e){let t=Oe.relative(e,n);return t===""||!Oe.isAbsolute(t)&&!t.startsWith(`..${Oe.sep}`)&&t!==".."}function Et(n){let e=Oe.resolve(n),t=[],r=e;for(;;)try{let o=vp.realpathSync(r);return t.length===0?o:Oe.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Oe.dirname(r);if(i===r)return e;t.push(Oe.basename(r)),r=i}}function es(n,e){let t=Et(e),r=Et(n);return Po(r,t)?r:null}function Oc(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function ts(n){let e=Oc(n);if(!e)throw new Error("Path must not be empty.");return Et(e)}var Mc="https://matrix.openharmony.cn",Ze={TAGS_API_URL:`${Mc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Mc}/api/registry/skill/skills`,SKILL_API_BASE:`${Mc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},dt={"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"}};import{homedir as Ct}from"os";import Me from"path";var Pt="deveco-mcp";var en={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Me.join(Ct(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:Me.join(Ct(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Me.join(process.platform==="win32"?Me.join(process.env.APPDATA??Me.join(Ct(),"AppData","Roaming"),"Trae CN","User"):Me.join(Ct(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Me.join(Ct(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Me.join(Ct(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Me.join(process.platform==="win32"?Me.join(process.env.APPDATA??Me.join(Ct(),"AppData","Roaming"),"Qoder","SharedClientCache"):Me.join(Ct(),"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:Me.join(Ct(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Me.join(Ct(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function bp(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Sp(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Ep(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function ns(n,e){return n.format==="opencode"?bp(e):n.format==="claude-code"||n.format==="codex"?Sp(e):Ep(e)}var _c="https://developer.huawei.com/consumer/cn/download/";var IS=/^#\s*Version:\s*(\S+)/,AS="26.0.0.810";function DS(n){try{let e=JSON.parse(ke.readFileSync(n,"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 ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function kS(n){let e=P.join(n,"default","openharmony");return[P.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>P.join(e,t,"oh-uni-package.json"))]}var k=class n{constructor(e,t,r,o,i,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=o;this._ohpmJsPath=i;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;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(ke.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return ke.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&&(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 pr(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 getStudioVersion(){try{let e=await n.resolveInstallSource();return Qt(e.toolchainRoot)}catch{return}}static async getCltVersion(){try{let e=await n.resolveInstallSource();return n.readCltVersion(e.toolchainRoot)}catch{return}}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()}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(Qt(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,o,i){if(!e)throw new v(`Failed to determine ${t} version from ${r} at ${i}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new v(`Invalid ${t} version "${e}" from ${r} at ${i}`,`Invalid ${t} version "${e}" from ${r}`);if(pr(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
|
|
15
|
-
${
|
|
14
|
+
`;await nt.promises.appendFile(o,i,"utf8")}catch{return}try{await nt.promises.unlink(e)}catch{}}};var I=new ko;import{spawn as KS}from"child_process";import{existsSync as XS}from"fs";import{dirname as ZS,join as QS}from"path";import{fileURLToPath as eb}from"url";function tb(){let r=ZS(eb(import.meta.url)),e=QS(r,"internal","telemetry-upload-background.js");return XS(e)?e:null}function Yc(r){if(rr()||!Mp(r))return;let e=tb();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{KS(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 w=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function q(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 S={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Re={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 V=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 o=j.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=j.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let n=Q.readFileSync(t,"utf-8"),o=Pt.parse(n);return o.app?o: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(i=>i.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),o=j.join(n,"src","main","module.json5");if(!Q.existsSync(o))return"entry";try{let i=Q.readFileSync(o,"utf-8");return Pt.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=j.normalize(e);for(let n of this.profile.modules){let o=j.normalize(j.join(this.rootDir,n.srcPath)),i=o+j.sep;if(t.startsWith(i)||t===o)return n.name}return null}getModuleProfile(e){let t=this.profile.modules.find(i=>i.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),o=j.join(n,"build-profile.json5");if(!Q.existsSync(o))throw new w(`Build profile for module '${e}' not found at ${o}.`,"Build profile for module not found at ${profilePath}.");try{let i=Q.readFileSync(o,"utf-8");return Pt.parse(i)}catch(i){throw new Error(`Failed to parse module build profile at ${o}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}getBundleName(e){if(e){let n=this.profile.app.products?.find(o=>o.name===e);if(n?.bundleName)return n.bundleName}let t=j.join(this.rootDir,"AppScope","app.json5");if(Q.existsSync(t))try{let n=Q.readFileSync(t,"utf-8"),o=Pt.parse(n);if(o?.app?.bundleName)return o.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=j.join(this.rootDir,"AppScope","app.json5");if(!Q.existsSync(e))return!1;try{let t=Q.readFileSync(e,"utf-8");return Pt.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 o=E.resolvePathWithinRoot(this.rootDir,n.srcPath),i=j.join(o,"src","main","module.json5");if(!Q.existsSync(i))return"EntryAbility";try{let s=Q.readFileSync(i,"utf-8"),c=Pt.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 ${i}:`,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(o=>o.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(o=>o.name===e);if(!t)return[];let n=this.readLockFinalLocalModuleDeps(e);return n!==null?n:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=j.join(this.rootDir,Re.LOCK_JSON5_PATH);if(!Q.existsSync(t))return null;let n;try{n=Pt.parse(Q.readFileSync(t,"utf-8"))}catch(d){return m(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let o=n,i=o?.modules;if(!i||typeof i!="object")return null;let s=Object.values(i).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(o.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let g=s[d];!g||typeof g!="object"||this.collectLocalDeps(g,a,v=>this.resolveLockDepByVersion(v),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 o=t.get(e);if(o){let i=this.resolveLocalDepToModule(o);if(i)return i}}return n()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[n,o]of Object.entries(e))typeof o=="string"&&t.set(n,o);return t.size>0?t:null}resolveLocalDepToModule(e){let t=r.stripLocalDep(e);if(!t)return null;let n=j.resolve(this.rootDir,t),o;try{o=E.ensurePathWithinRoot(this.rootDir,n)}catch{return null}let i=this.profile.modules.find(s=>j.resolve(this.rootDir,s.srcPath)===o);return i?i.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=j.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Re.OH_PACKAGE_JSON5);if(!Q.existsSync(t))return[];let n=this.readRootOverrideMap(),o=[],i=new Set;try{let s=Pt.parse(Q.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),o,i)}}catch(s){m(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return o}readRootOverrideMap(){let e=j.join(this.rootDir,Re.OH_PACKAGE_JSON5);if(!Q.existsSync(e))return null;try{let t=Pt.parse(Q.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,o,i){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>n(a));c&&!i.has(c)&&(i.add(c),o.push(c))}}resolveLocalDepModuleName(e,t){let n=r.stripLocalDep(e);if(!n)return null;let o=j.join(t.srcPath,n),i=E.resolvePathWithinRoot(this.rootDir,o),s=this.profile.modules.find(a=>j.resolve(this.rootDir,a.srcPath)===i);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],n=[],o=new Set;for(n.push(e),o.add(e);n.length>0;){let i=n.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(n.push(c),o.add(c))}return t}resolveModuleMetadata(e,t,n){this.validateProduct(n);let o=this.profile.modules.find(l=>l.name===e);if(!o){let l=this.getRunnableModuleNames();throw new w(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let i=this.getModuleType(e)==="shared",s=i?"hspName":"hapName",a=this.buildOutputPath(o.srcPath,n,["intermediates",i?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Q.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:o,isShared:i,metadataPath:a,metadata:c}}findArtifactPath(e,t,n,o="default"){let{moduleNode:i,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,o),{packageName:c,isSigned:l}=a,d=c;if(!l){let b=this.getSignedHapName(c,i.srcPath,o,t);b&&(d=b)}let g=s?"-signed.hsp":"-signed.hap";if(!n&&!d.endsWith(g))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 v=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!Q.existsSync(v))throw new w(`Generated package file not found in ${v}.`,"Generated package file not found.");return v}findRemoteHspPaths(e,t,n="default"){let{moduleNode:o,metadata:i}=this.resolveModuleMetadata(e,t,n),s=[],a=new Set;for(let{hspPath:c}of i.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=j.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,n,["outputs",t,c]);if(!Q.existsSync(l))throw new w(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,n,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,n,["outputs",o,i]);return Q.existsSync(s)?i:null}buildOutputPath(e,t,n){let o=E.resolvePathWithinRoot(this.rootDir,e),i=j.resolve(o,"build",t,...n);return E.ensurePathWithinRoot(this.rootDir,i)}collectRemoteHsps(e){return e.flatMap(t=>{let n=t.dependRemoteHsps;return Array.isArray(n)?n.filter(o=>!!(o.hspName&&o.hspPath)).map(o=>({hspName:o.hspName,hspPath:o.hspPath})):[]})}parseOutputMetadata(e,t){let n;try{let c=Q.readFileSync(e,"utf-8");n=Pt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let o,i=!1,s=Array.isArray(n)?n:[n];for(let c of s)o||(o=c[t]),i||(i=c.isSigned===!0);if(!o)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(o);let a=this.collectRemoteHsps(s);return{packageName:o,isSigned:i,dependRemoteHsps:a}}validatePackageName(e){let t=j.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 xe from"fs";import*as Ye from"os";import*as P from"path";import as from"fs";import*as cs from"os";import*as Do from"path";import ib from"regedit";import{execFileSync as nb}from"child_process";import Hp from"fs";import*as Up from"os";import*as Kc from"path";import{compare as rb}from"semver";function $p(r,e){return rb(r,e)}function wn(r,e){let t=Math.max(r.split(".").length,e.split(".").length);for(let n=0;n<t;n++){let o=Number(r.split(".")[n]??0)-Number(e.split(".")[n]??0);if(o)return o}return 0}function ss(r,e){let t=Kc.join(r,"Contents","Info.plist");if(!Hp.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[n,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=nb(n,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function ob(r){let e=ss(r,"CFBundleShortVersionString");if(!e)return ss(r,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),n=[ss(r,"CFBundleVersion"),ss(r,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of n){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function nr(r){if(Up.platform()==="darwin")return ob(r);let e=Kc.join(r,"product-info.json");try{let t=JSON.parse(Hp.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var sb="DevEco Studio",ab=["Contents","Resources","product-info.json"],cb="name";function lb(r){return r.filter(e=>{try{return as.statSync(e).isDirectory()}catch{return!1}})}function db(r){let e=Do.join(r,...ab);if(as.existsSync(e))try{let n=JSON.parse(as.readFileSync(e,"utf8"))[cb];return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function ub(r){return db(r)===sb}function pb(){let r=[];for(let e of[Do.join(cs.homedir(),"Applications"),"/Applications"])try{r.push(...as.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>Do.join(e,t)).filter(ub))}catch{}return r}function Bp(r){return new Promise((e,t)=>ib.list(r,(n,o)=>n?t(n):e(o)))}async function Wp(r,e,t){let o=((await Bp([r]))[r]?.keys??[]).filter(e).map(s=>`${r}\\${s}`);if(o.length===0)return[];let i=await Bp(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function mb(){let r=[Do.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 Wp(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 Wp(e,()=>!0,""))}catch{}return r}async function Vp(){let r=cs.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"?pb():await mb(),t=lb(e).flatMap(n=>{let o=nr(n);return o?(m(`[ToolProvider] ${n} => version ${o}`),[{root:n,version:o}]):(m(`[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,o)=>wn(o.version,n.version)>0?o:n)}import*as Gp from"fs";import*as Fe from"path";function To(r,e){let t=Fe.relative(e,r);return t===""||!Fe.isAbsolute(t)&&!t.startsWith(`..${Fe.sep}`)&&t!==".."}function At(r){let e=Fe.resolve(r),t=[],n=e;for(;;)try{let o=Gp.realpathSync(n);return t.length===0?o:Fe.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=Fe.dirname(n);if(i===n)return e;t.push(Fe.basename(n)),n=i}}function ls(r,e){let t=At(e),n=At(r);return To(n,t)?n:null}function Xc(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function ds(r){let e=Xc(r);if(!e)throw new Error("Path must not be empty.");return At(e)}var Zc="https://matrix.openharmony.cn",ot={TAGS_API_URL:`${Zc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Zc}/api/registry/skill/skills`,SKILL_API_BASE:`${Zc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},ft={"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 It}from"os";import je from"path";var kt="deveco-mcp";var or={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:je.join(It(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:je.join(It(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:je.join(process.platform==="win32"?je.join(process.env.APPDATA??je.join(It(),"AppData","Roaming"),"Trae CN","User"):je.join(It(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:je.join(It(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:je.join(It(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:je.join(process.platform==="win32"?je.join(process.env.APPDATA??je.join(It(),"AppData","Roaming"),"Qoder","SharedClientCache"):je.join(It(),"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:je.join(It(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:je.join(It(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function qp(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function zp(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function Jp(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function us(r,e){return r.format==="opencode"?qp(e):r.format==="claude-code"||r.format==="codex"?zp(e):Jp(e)}var Qc="https://developer.huawei.com/consumer/cn/download/";var fb=/^#\s*Version:\s*(\S+)/,hb="26.0.0.810";function gb(r){try{let e=JSON.parse(xe.readFileSync(r,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${r}: ${e instanceof Error?e.message:String(e)}`);return}}function yb(r){let e=P.join(r,"default","openharmony");return[P.join(r,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>P.join(e,t,"oh-uni-package.json"))]}var k=class r{constructor(e,t,n,o,i,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=n;this._nodePath=o;this._ohpmJsPath=i;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;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(xe.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=r.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return xe.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&&(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 wn(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 getStudioVersion(){try{let e=await r.resolveInstallSource();return nr(e.toolchainRoot)}catch{return}}static async getCltVersion(){try{let e=await r.resolveInstallSource();return r.readCltVersion(e.toolchainRoot)}catch{return}}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()}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(nr(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,o,i){if(!e)throw new w(`Failed to determine ${t} version from ${n} at ${i}`,`Failed to determine ${t} version from ${n}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new w(`Invalid ${t} version "${e}" from ${n} at ${i}`,`Invalid ${t} version "${e}" from ${n}`);if(wn(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
|
|
15
|
+
${Qc}`)}static resolveCodelinterPath(e,t){let n=r.buildToolPaths(e,t).codelinterCandidates,o=n.find(r.isFile);if(!o){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
16
|
Searched paths:
|
|
17
|
-
${
|
|
18
|
-
`)}`,a)}let i=
|
|
19
|
-
`);for(let l of c){let d=l.trim();d&&/^\d+$/.test(d)&&a.push(Number(d))}e(a)})})}async function Ap(n){let e=0,t=await Qe(n);t&&(e+=Number(t)*1024);let r=await xS(n);for(let o of r)e+=await Ap(o);return e}function ue(n){return`${(n/1024/1024).toFixed(2)}MB`}async function Cp(n,e){if(!n)return process.memoryUsage().rss;if(e)return Ap(n);let t=await Qe(n);return t?Number(t)*1024:0}function rs(n,e=500,t=!1){let r=0,o=!1,i=setInterval(async()=>{if(o)return;let s=await Cp(n,t);s>r&&(r=s)},e);return{stop:async()=>{o=!0,clearInterval(i);let s=await Cp(n,t);return Math.max(r,s)}}}function LS(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function NS(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var qe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o=tn.dirname(e.javaPath),i=`${o}${tn.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=tn.dirname(o)),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,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(i)}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()){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 r=new Dp.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(!os.existsSync(t))return null;try{let r=os.readFileSync(t,"utf-8"),o=JSON.parse(r),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(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||tn.join(kp.homedir(),".hvigor");return tn.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];f(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",i=OS(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o}),s=rs(i.pid,500,!0),a="";try{await i}finally{let c=await s.stop();c>0&&(a=ue(c),f(`Hvigor peak memory: ${a}`))}return a}};import{execa as MS}from"execa";var mr=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"];f(`Executing: ${e} ${t.join(" ")}`);let r=MS(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),o=rs(r.pid);try{await r}finally{let i=await o.stop();i>0&&(this.peakMemoryMb=ue(i))}}};import{mkdir as _S}from"fs/promises";import{dirname as FS,resolve as jS}from"path";import{execa as $S}from"execa";import{lock as jc,check as CF}from"proper-lockfile";function $c(n){return jS(n,".hvigor",".build-lock")}function HS(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Tp(n){let e=FS($c(n));if(await _S(e,{recursive:!0}),process.platform==="win32")try{await $S("attrib",["+h",e])}catch{}}async function US(n,e){let t=new AbortController,r=HS(e);await Tp(n);let o={lockfilePath:$c(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await jc(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await jc(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Wn(n,e,t){let{release:r,signal:o}=await US(n,t);try{return await e(o)}finally{await r()}}async function is(n,e){let t=new AbortController;await Tp(n);let r={lockfilePath:$c(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await jc(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as nn from"fs";import*as Vn from"path";import BS from"json5";var WS=1e3;function as(n){f(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Vn.join(n,De.SYNC_OUTPUT_PATH);if(!nn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return f(`[ProjectCheck] ${l.reason}`),l}let t=nn.statSync(e).mtimeMs;f(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=VS(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return f(`[ProjectCheck] ${l.reason}`),l}let o=Vn.join(n,De.OH_PACKAGE_JSON5),i=ss(o,t,"root");if(i.required)return f(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Vn.join(n,De.BUILD_PROFILE_JSON5),a=ss(s,t,"build-profile");if(a.required)return f(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Vn.join(n,l.srcPath,De.OH_PACKAGE_JSON5),g=ss(d,t,l.name);if(g.required)return f(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=Vn.join(n,l.srcPath,De.BUILD_PROFILE_JSON5),C=ss(w,t,l.name);if(C.required)return f(`[ProjectCheck] Module '${l.name}' build-profile check: ${C.reason}`),C}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return f(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function ss(n,e,t){if(!nn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=nn.statSync(n).mtimeMs;return r-e>WS?{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 VS(n){let e=Vn.join(n,De.BUILD_PROFILE_JSON5);try{let t=nn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=BS.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Z from"fs";import*as re from"path";import*as Rp from"util";var Hc="";function ls(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Hc="";return}Hc=n}function xp(){return Hc||(rp()??"")}function cs(n,...e){if(e.length===0)return n;try{return Rp.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var m={info(n,...e){h.info(`[lsp] ${cs(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${cs(n,...e)}`)},error(n,...e){h.error(`[lsp] ${cs(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${cs(n,...e)}`)}};import*as Io from"fs";import*as Ao from"os";import*as fr from"path";import GS from"json5";var y={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"},R="2.0";var Lp=8192,Uc=100,Np=.03,Op=.7,et=900*1e3;function ze(n){if(!Io.existsSync(n))return null;try{let e=Io.readFileSync(n,"utf-8");return e.trim()?GS.parse(e):null}catch{return null}}function ds(n,e){let t=Math.floor(Ao.totalmem()/1048576),r=Math.floor(t*Op),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=Lp,n>Uc&&(o+=(n-Uc)*Np*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return m.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function ut(n){if(n.startsWith("file:"))return n;try{let e=fr.resolve(n),t=new URL(`file://${e}`).toString();if(Ao.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function hr(n){return n&&n.replace(/\\/g,"/")}function V(n){let e=fr.normalize(n).replace(/\\/g,"/");if(Ao.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Mp(n){return fr.join(n,"build-profile.json5")}var Nt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Mp(this.projectRoot);try{let t=ze(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return m.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as qS}from"child_process";import*as ps from"fs";var zS=600*1e3;function JS(n,e,t){let r=t.split(/\s+/).filter(o=>o.length>0);return[n,[e,...r]]}function YS(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{let o=r.toString();t.push(o),o.split(/\r?\n/).filter(Boolean).forEach(i=>m.info("[hvigor:err] %s",i))}),{stdout:e,stderr:t}}function us(n){return n.join("")}function KS(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
17
|
+
${n.join(`
|
|
18
|
+
`)}`,a)}let i=At(e),s=At(o);return r.assertInsideRoot(s,i,"codelinter"),s}static isValidRoot(e,t){if(!r.isDirectory(e))return!1;if(t==="clt")return xe.existsSync(P.join(e,"version.txt"));let n=Ye.platform()==="darwin"?P.join(e,"Contents"):e,o=Ye.platform()==="darwin"?P.join(n,"Info.plist"):P.join(n,"product-info.json");if(!xe.existsSync(o))return!1;let i=r.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(xe.existsSync)}static buildToolPaths(e,t){return t==="clt"?r.buildCltToolPaths(e):r.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=Ye.platform()==="win32",n=t?".exe":"",o=P.join(e,"sdk");return{nodePath:t?P.join(e,"tool","node","node.exe"):P.join(e,"tool","node","bin","node"),ohpmJsPath:P.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:o,hdcPath:P.join(o,"default","openharmony","toolchains",`hdc${n}`),emulatorPath:P.join(e,"emulator",t?"Emulator.exe":"Emulator"),clangdPath:r.clangdPathFor(o),arktsLangServerCandidates:[{root:P.join(e,"arkts-lsp","lib"),marker:P.join(e,"arkts-lsp","lib","out","index.js")}],codelinterCandidates:r.codelinterCandidatesFor(e,"clt")}}static buildStudioToolPaths(e){let t=Ye.platform()==="darwin",n=Ye.platform()==="win32",o=t?P.join(e,"Contents"):e,i=P.join(o,"tools"),s=P.join(o,"sdk"),a=n?".exe":"";return{nodePath:n?P.join(i,"node","node.exe"):P.join(i,"node","bin","node"),ohpmJsPath:P.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(i,"hvigor","bin","hvigorw.js"),javaPath:n?P.join(e,"jbr","bin","java.exe"):t?P.join(o,"jbr","Contents","Home","bin","java"):P.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:P.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:P.join(i,"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[P.join(e,"codelinter","index.js"),P.join(e,"codelinter","run","index.js"),P.join(e,"tool","codelinter","bin","codelinter.js"),P.join(e,"tool","codelinter","codelinter.js")];let n=Ye.platform()==="darwin"?["Contents"]:[];return[P.join(e,...n,"plugins","codelinter","run","index.js"),P.join(e,...n,"plugins","codelinter","index.js"),P.join(e,...n,"tools","codelinter","bin","codelinter.js"),P.join(e,...n,"tools","codelinter","codelinter.js")]}static studioArktsLangServerCandidates(e){if(Ye.platform()==="linux")return[];let t=Ye.platform()==="darwin"?["Contents"]:[],n=P.join(e,...t,"plugins","openharmony");return[{root:n,marker:P.join(n,"ace-server","out","index.js")}]}static clangdPathFor(e){return P.join(e,"default","openharmony","native","llvm","bin",Ye.platform()==="win32"?"clangd.exe":"clangd")}static isFile(e){try{return xe.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return xe.existsSync(e)&&xe.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,o,i]of e){let s=process.env[n]?.trim();if(s){let a=r.resolveExplicitRoot(s,o,n);return m(`[ToolProvider] Using ${n} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Vp();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,n){let o;try{o=ds(e)}catch(i){throw new Error(`Invalid ${n}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&Ye.platform()==="darwin"&&(o=r.normalizeMacStudioRoot(o)),r.isValidRoot(o,t)?o:r.throwInvalidSource(o,t,n,e)}static assertBuiltPathsInsideRoot(e,t,n){let o=At(e),i=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];n&&t.javaPath&&i.push(["java",t.javaPath]);for(let[s,a]of i)r.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,n){if(ls(e,t)===null)throw new Error(`Unsafe toolchain path: ${n} resolves outside the toolchain root`)}static throwInvalidSource(e,t,n,o){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}: ${o}`)}static normalizeMacStudioRoot(e){let t=`${P.sep}Contents`,n=P.normalize(e);return n.endsWith(t)?n.slice(0,-t.length):n}static readCltVersion(e){try{return xe.readFileSync(P.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(fb)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),n=t&&(r.javaIn(P.join(t,"bin"))??r.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(P.delimiter).map(s=>r.javaIn(s.trim())).find(Boolean),i=n??o;if(i)return xe.realpathSync(i);if(e)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.");return""}static javaIn(e){return(Ye.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(n=>P.join(e,n)).find(xe.existsSync)}getMaxApiLevel(){for(let e of yb(this.sdkPath)){let t=gb(e);if(t!==void 0)return t}return 23}getSdkPlatformVersion(){let e=P.join(this.sdkPath,"default","sdk-pkg.json"),t;try{t=JSON.parse(xe.readFileSync(e,"utf8"))}catch(i){throw new Error(`Failed to read SDK metadata: ${e}`,{cause:i})}let n=t.data?.platformVersion,o=typeof n=="string"?n.trim():"";if(!o)throw new Error(`Missing data.platformVersion in SDK metadata: ${e}`);return o}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ye.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=P.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=P.join(n,"resources","apiChange"),i=P.join(n,"api-change-scan.js");if(!xe.existsSync(o)||!xe.existsSync(i)){let s=nr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${hb}. Upgrade before using 'check compat' at ${Qc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}};import{execa as Cb}from"execa";import*as Qp from"net";import*as ir from"path";import*as ms from"fs";import*as em from"os";import{execFile as Kp}from"child_process";import{existsSync as vb}from"fs";var Xp="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",el;function wb(){return el===void 0&&(el=vb(Xp)),el}function $e(r){return new Promise(e=>{let t=process.platform==="win32",n=t?"tasklist":"ps",o=t?["/fi",`PID eq ${r}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(r)];m(`Executing: ${n} ${o.join(" ")}`),Kp(n,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e(null);return}e(t?Eb(s):bb(s))})})}async function Sb(r){return new Promise(e=>{let t=process.platform==="win32",n,o;if(t){if(!wb()){e([]);return}n=Xp,o=["-NoProfile","-Command",`Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${r} } | Select-Object -ExpandProperty ProcessId`]}else n="ps",o=["-o","pid=","--ppid",String(r)];Kp(n,o,{timeout:5e3,windowsHide:!0},(i,s)=>{if(i){e([]);return}let a=[],c=s.trim().split(`
|
|
19
|
+
`);for(let l of c){let d=l.trim();d&&/^\d+$/.test(d)&&a.push(Number(d))}e(a)})})}async function Zp(r){let e=0,t=await $e(r);t&&(e+=Number(t)*1024);let n=await Sb(r);for(let o of n)e+=await Zp(o);return e}function de(r){return`${(r/1024/1024).toFixed(2)}MB`}async function Yp(r,e){if(!r)return process.memoryUsage().rss;if(e)return Zp(r);let t=await $e(r);return t?Number(t)*1024:0}function ps(r,e=500,t=!1){let n=0,o=!1,i=setInterval(async()=>{if(o)return;let s=await Yp(r,t);s>n&&(n=s)},e);return{stop:async()=>{o=!0,clearInterval(i);let s=await Yp(r,t);return Math.max(n,s)}}}function bb(r){let e=r.trim().match(/^(\d+)$/);return e?e[1]:null}function Eb(r){let e=r.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Ke=class{toolProvider;projectRoot;env;silent;constructor(e,t,n=!1){this.toolProvider=e,this.projectRoot=t,this.silent=n;let o=ir.dirname(e.javaPath),i=`${o}${ir.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=ir.dirname(o)),this.env=s}async sync(e,t){let n=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(n)}async buildProduct(e,t){let n=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(n)}async buildModules(e,t,n,o){let i=[...Array.from(o),"--mode","module","-p",`module=${n.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(i)}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()){m("[HvigorAdapter] Daemon already running.");return}m("[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 Qp.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(!ms.existsSync(t))return null;try{let n=ms.readFileSync(t,"utf-8"),o=JSON.parse(n),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(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||ir.join(em.homedir(),".hvigor");return ir.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","--analyze=normal"),this.runHvigor(n)}async runHvigor(e){let t=this.toolProvider.nodePath,n=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${n.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",i=Cb(t,n,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o}),s=ps(i.pid,500,!0),a="";try{await i}finally{let c=await s.stop();c>0&&(a=de(c),m(`Hvigor peak memory: ${a}`))}return a}};import{execa as Pb}from"execa";var Sn=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"];m(`Executing: ${e} ${t.join(" ")}`);let n=Pb(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),o=ps(n.pid);try{await n}finally{let i=await o.stop();i>0&&(this.peakMemoryMb=de(i))}}};import{mkdir as Ab}from"fs/promises";import{dirname as Ib,resolve as kb}from"path";import{execa as Db}from"execa";import{lock as tl,check as kj}from"proper-lockfile";function rl(r){return kb(r,".hvigor",".build-lock")}function Tb(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function tm(r){let e=Ib(rl(r));if(await Ab(e,{recursive:!0}),process.platform==="win32")try{await Db("attrib",["+h",e])}catch{}}async function Rb(r,e){let t=new AbortController,n=Tb(e);await tm(r);let o={lockfilePath:rl(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await tl(r,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return n(),{release:await tl(r,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Jr(r,e,t){let{release:n,signal:o}=await Rb(r,t);try{return await e(o)}finally{await n()}}async function fs(r,e){let t=new AbortController;await tm(r);let n={lockfilePath:rl(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await tl(r,{...n,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as sr from"fs";import*as Yr from"path";import xb from"json5";var Lb=1e3;function gs(r){m(`[ProjectCheck] Checking sync required at project root: ${r}`);let e=Yr.join(r,Re.SYNC_OUTPUT_PATH);if(!sr.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=sr.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let n=Nb(r);if(n===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Yr.join(r,Re.OH_PACKAGE_JSON5),i=hs(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Yr.join(r,Re.BUILD_PROFILE_JSON5),a=hs(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of n){let d=Yr.join(r,l.srcPath,Re.OH_PACKAGE_JSON5),g=hs(d,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let v=Yr.join(r,l.srcPath,Re.BUILD_PROFILE_JSON5),b=hs(v,t,l.name);if(b.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${b.reason}`),b}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function hs(r,e,t){if(!sr.existsSync(r))return{required:!1,reason:`${t}: source not found, skip`};let n=sr.statSync(r).mtimeMs;return n-e>Lb?{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 Nb(r){let e=Yr.join(r,Re.BUILD_PROFILE_JSON5);try{let t=sr.readFileSync(e,"utf-8");if(!t.trim())return null;let n=xb.parse(t);if(typeof n!="object"||n===null)return null;let o=n.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as ee from"fs";import*as se from"path";import*as rm from"util";var nl="";function vs(r){if(!r||r==="auto"||r==="stdout"||r==="none"){nl="";return}nl=r}function nm(){return nl||(Tp()??"")}function ys(r,...e){if(e.length===0)return r;try{return rm.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(r,...e){h.info(`[lsp] ${ys(r,...e)}`)},warn(r,...e){h.warn(`[lsp] ${ys(r,...e)}`)},error(r,...e){h.error(`[lsp] ${ys(r,...e)}`)},debug(r,...e){h.debug(`[lsp] ${ys(r,...e)}`)}};import*as Ro from"fs";import*as xo from"os";import*as bn from"path";import Ob from"json5";var y={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"},R="2.0";var om=8192,ol=100,im=.03,sm=.7,it=900*1e3;function Xe(r){if(!Ro.existsSync(r))return null;try{let e=Ro.readFileSync(r,"utf-8");return e.trim()?Ob.parse(e):null}catch{return null}}function ws(r,e){let t=Math.floor(xo.totalmem()/1048576),n=Math.floor(t*sm),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=om,r>ol&&(o+=(r-ol)*im*1024),i=`formula(moduleCount=${r})`);let s=n>0&&o>n;s&&(o=n);let a=Math.round(o);return f.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${n}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function ht(r){if(r.startsWith("file:"))return r;try{let e=bn.resolve(r),t=new URL(`file://${e}`).toString();if(xo.platform()==="win32"){let n=t.match(/^file:\/\/\/([A-Za-z]):/);if(n){let o=n[1].toUpperCase(),i=t.substring(`file:///${n[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return r}}function En(r){return r&&r.replace(/\\/g,"/")}function J(r){let e=bn.normalize(r).replace(/\\/g,"/");if(xo.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function am(r){return bn.join(r,"build-profile.json5")}var _t=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=am(this.projectRoot);try{let t=Xe(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Mb}from"child_process";import*as bs from"fs";var _b=600*1e3;function Fb(r,e,t){let n=t.split(/\s+/).filter(o=>o.length>0);return[r,[e,...n]]}function jb(r){let e=[],t=[];return r.stdout?.on("data",n=>{e.push(n.toString())}),r.stderr?.on("data",n=>{let o=n.toString();t.push(o),o.split(/\r?\n/).filter(Boolean).forEach(i=>f.info("[hvigor:err] %s",i))}),{stdout:e,stderr:t}}function Ss(r){return r.join("")}function $b(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
20
20
|
Output so far:
|
|
21
|
-
`+t,exitCode:-1};let r
|
|
22
|
-
`).trim();
|
|
21
|
+
`+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function Hb(r,e,t){return new Promise(n=>{let o=Mb(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:i,stderr:s}=jb(o),a=setTimeout(()=>{o.kill();let c=[Ss(i),Ss(s)].filter(Boolean).join(`
|
|
22
|
+
`).trim();n({success:!1,output:`Build process timeout after 10 minutes.
|
|
23
23
|
Output so far:
|
|
24
|
-
`+c,exitCode:-1})},
|
|
25
|
-
`).trim()||"";
|
|
26
|
-
[ohpm install] Running...`);try{await
|
|
27
|
-
[hvigor sync] Running...`);try{a=await e.sync(t,
|
|
24
|
+
`+c,exitCode:-1})},_b);o.on("close",(c,l)=>{clearTimeout(a);let d=[Ss(i),Ss(s)].filter(Boolean).join(`
|
|
25
|
+
`).trim()||"";n($b(c,l,d))}),o.on("error",c=>{clearTimeout(a),n({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function il(r,e,t,n,o){let i={...process.env,DEVECO_SDK_HOME:n},s=Fb(e,t,o);return await Hb(s,r,i)}function Ub(r,e,t){return{node_path:e,hvigor_path:t,sdk_path:r}}function Bb(r){return!r.node_path||!bs.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!bs.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!bs.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var Wb="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function cm(r,e,t,n){try{let o=Ub(e,t,n),i=Bb(o);if(i!=null)return f.info(`Config validation failed: ${i}`),!1;let s=await il(r,o.node_path,o.hvigor_path,e,Wb);return f.info(`[hvigor] sync finished: success=${s.success}, exitCode=${s.exitCode}`),s.success}catch(o){return f.info(`syncProject failed: ${JSON.stringify(o)}`),!1}}function Vb(r){let e=se.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh"].includes(e)}function Gb(r,e){let t=se.join(r,e.name);return e.isDirectory()?e.name===".cxx"||dm(t):Vb(t)}function dm(r){if(!ee.existsSync(r))return!1;try{return ee.readdirSync(r,{withFileTypes:!0}).some(t=>Gb(r,t))}catch{}return!1}function ar(r){try{let t=new _t(r).getAllModuleInfo(),n=[];for(let o of t){let i=se.resolve(r,o.srcPath);dm(i)&&n.push(o)}return n}catch(e){throw h.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function zb(r){let e=[],n=new _t(r).getAllModuleInfo();for(let o of n){let i=se.resolve(r,o.srcPath),s=se.join(i,".cxx");ee.existsSync(s)&&um(s,e)}return e}function um(r,e){try{let t=ee.readdirSync(r,{withFileTypes:!0});for(let n of t){let o=se.join(r,n.name);n.isDirectory()?um(o,e):n.name==="compile_commands.json"&&e.push(o)}}catch{}}function qb(r){let e=[];for(let t of r)try{let n=ee.readFileSync(t,"utf8"),o=JSON.parse(n);e.push(...o)}catch{}return e}function Jb(r,e){let t=se.join(r,...Yb.slice(0,-1));ee.mkdirSync(t,{recursive:!0});let n=se.join(t,"compile_commands.json");ee.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function sl(r){let e=zb(r);if(e.length>0){let t=qb(e);Jb(r,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var Yb=[".idea",".deveco","cxx","compile_commands.json"];async function Kb(r,e,t,n,o){if(!n){h.warn(`[CppCompile] hvigorw.js path not injected (sdk '${e}')`);return}h.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${n}`);for(let i of o){let s=i.name;try{E.assertModuleName(s)}catch{h.warn(`[CppCompile] Skipping module with invalid name: ${s}`);continue}let a=["--mode","module","-p",`module=${i.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${i.name}`);let c=await il(r,t,n,e,a);c.success?h.info(`[CppCompile] compileNative ${i.name} succeeded`):h.warn(`[CppCompile] compileNative ${i.name} failed: ${c.output}`)}}async function pm(r,e,t,n){let o=ar(r);if(o.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${o.length} C++ module(s): ${o.map(i=>i.name).join(", ")}`),await Kb(r,e,t,n,o),sl(r),nE(r,o)}var Xb=1e3,Zb=["src","main","cpp","CMakeLists.txt"],Qb=new Set([".cxx","build","node_modules",".preview",".hvigor",".idea"]),eE=new Set(["c","cpp","cxx","cc"]),tE="cpp-source-manifest.json";function rE(r){let e=se.extname(r).replace(/^\./,"").toLowerCase();return eE.has(e)}function lm(r,e){return ee.existsSync(r)?ee.statSync(r).mtimeMs-e>Xb:!1}function mm(r){return se.join(se.dirname(Wr(r)),tE)}function fm(r,e,t){let n;try{n=ee.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of n){let i=se.join(r,o.name);if(o.isDirectory()){if(Qb.has(o.name))continue;fm(i,e,t)}else rE(o.name)&&t.push(se.relative(e,i).replace(/\\/g,"/"))}}function hm(r,e){let t=[];for(let n of e){let o=E.resolvePathWithinRoot(r,n.srcPath);fm(o,r,t)}return t.sort()}function nE(r,e){let t=hm(r,e),n={files:t,updatedAt:Date.now()},o=mm(r);try{ee.mkdirSync(se.dirname(o),{recursive:!0}),ee.writeFileSync(o,JSON.stringify(n,null,2),"utf8"),h.info(`[CppCompile] C++ source manifest written, ${t.length} files`)}catch(i){h.warn(`[CppCompile] Failed to write C++ source manifest: ${i}`)}}function oE(r,e){let t=mm(r);if(!ee.existsSync(t))return{required:!0,reason:"C++ source manifest not found, needs initialization"};let n;try{let i=JSON.parse(ee.readFileSync(t,"utf8"));n=Array.isArray(i.files)?i.files:[]}catch{return{required:!0,reason:"C++ source manifest corrupted, needs initialization"}}let o=hm(r,e);return o.length!==n.length||o.some((i,s)=>i!==n[s])?{required:!0,reason:`C++ source file set changed (recorded=${n.length}, actual=${o.length})`}:null}function gm(r){let e=Wr(r);if(!ee.existsSync(e))return{required:!0,reason:"C++ baseline (compile_commands.json) not found, needs initialization"};let t=ee.statSync(e).mtimeMs,n=ar(r);if(n.length===0)return{required:!1,reason:"no C++ modules, skip compileNative"};for(let i of n){let s=E.resolvePathWithinRoot(r,i.srcPath);if(lm(se.join(s,"build-profile.json5"),t))return{required:!0,reason:`module '${i.name}': build-profile.json5 newer than baseline`};let a=se.join(s,...Zb);if(lm(a,t))return{required:!0,reason:`module '${i.name}': CMakeLists.txt newer than baseline`}}let o=oE(r,n);return o||{required:!1,reason:`C++ project up-to-date (baseline: ${new Date(t).toISOString()})`}}function sE(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode){let t=["debug","release"],n=(r.profile.app.buildModeSet?.map(i=>i.name)??[]).filter(i=>!t.includes(i)),o=[...t,...n];if(!o.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${o.join(", ")}`)}}function aE(r,e){let t=r.profile.modules.map(o=>o.name),n=new Set(t);for(let o of e){let i=o.split("@",1)[0];if(!n.has(i))throw new Error(`Module '${i}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function cE(r,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,aE(r,t);else{let o=r.profile.modules,i=o.filter(s=>r.getModuleType(s.name)==="entry");if(o.length===1)t=[o[0].name];else if(i.length===1)t=[i[0].name];else throw i.length>1?new w(`Multiple entry modules found (${i.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 (${o.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 o of t){let i=o.indexOf("@"),s=i!==-1?o.substring(0,i):o,a=i!==-1?o.substring(i+1):"default";n.add(`${s}@${a}`)}return Array.from(n)}function ll(r,e){let t=new Set;for(let n of e){let o=n.indexOf("@"),i=o!==-1?n.substring(0,o):n,s=r.getModuleType(i);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Lo(r,e){let t=e,n=`${r} failed`;console.error(ym(n));let o=t.stdout||t.message;throw o&&console.error(o),t.stderr&&console.error(t.stderr),new Error(n,{cause:e})}async function dl(r,e,t,n,o,i){let s=gs(i);console.log(`
|
|
26
|
+
[ohpm install] Running...`);try{await r.installAll()}catch(l){Lo("ohpm install",l)}let a="";if(s.required){console.log(`
|
|
27
|
+
[hvigor sync] Running...`);try{a=await e.sync(t,n)}catch(l){Lo("hvigor sync",l)}}else console.log(`
|
|
28
28
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
29
|
-
[hvigor build] Running...`);let c="";try{o.type==="product"?c=await e.buildProduct(t,
|
|
30
|
-
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(
|
|
31
|
-
Failed to merge compile_commands.json: ${e.message}`))}}async function
|
|
32
|
-
`+
|
|
33
|
-
[1/2] Running hvigor clean...`);try{await
|
|
34
|
-
[2/2] Running hvigor --stop-daemon...`);try{await
|
|
35
|
-
`+
|
|
29
|
+
[hvigor build] Running...`);let c="";try{o.type==="product"?c=await e.buildProduct(t,n):c=await e.buildModules(t,n,o.modulesToBuild,o.moduleTasks)}catch(l){Lo("hvigor build",l)}return lE(i),{ohpmMemoryMb:r.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function lE(r){try{if(ar(r).length===0)return;sl(r),console.log(al(`
|
|
30
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(cl(`
|
|
31
|
+
Failed to merge compile_commands.json: ${e.message}`))}}async function vm(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=q(i),console.error(ym(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i)}}function dE(r){let e={event:S.CommandExecuted,args:["build",...r.product?["--product"]:[],...r.modules?["--modules"]:[],...r.buildMode?["--build-mode"]:[]]};return r.buildMode&&(e.build_mode=r.buildMode),r.modules&&(e.module_count=r.modules.length),e}function uE(){return{event:S.CommandExecuted,args:["build","clean"]}}async function pE(r){let e=process.cwd(),t=V.discover(e);console.warn(cl("Ensure the project source is trustworthy before proceeding."));let n=await k.new();n.assertJava(),sE(t,r);let o=r.product||"default",i=r.buildMode||"debug",s;if(r.product&&!r.modules)s={type:"product"};else{let d=cE(t,r),g=ll(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:g}}let a=new Sn(n,t.rootDir),c=new Ke(n,t.rootDir),l=await Jr(t.rootDir,async()=>dl(a,c,o,i,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
|
|
32
|
+
`+al("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function mE(){let r=process.cwd(),e=V.discover(r);console.warn(cl("Ensure the project source is trusted before proceeding."));let t=await k.new();t.assertJava();let n=new Ke(t,e.rootDir);return await Jr(e.rootDir,async()=>{console.log(`
|
|
33
|
+
[1/2] Running hvigor clean...`);try{await n.clean()}catch(o){Lo("hvigor clean",o)}console.log(`
|
|
34
|
+
[2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(o){Lo("hvigor --stop-daemon",o)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
35
|
+
`+al("Clean completed successfully.")),e.getBundleName()}var wm=new iE("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)").action(async r=>{let e=dE(r);await vm(e,async()=>{let t=await pE(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)})});wm.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let r=uE();await vm(r,async()=>{r.bundle_name=await mE()})});var Sm=wm;import{Command as RC}from"commander";import{green as Uo,red as xC,yellow as Hs}from"colorette";import*as Bo from"path";import{randomUUID as kE}from"crypto";import{execa as Dm}from"execa";import{execa as IE}from"execa";import{execFile as fE,spawn as hE}from"child_process";import{promisify as gE}from"util";var yE=gE(fE);function bm(r,e,t){let o=r.replace(/\r\n/g,`
|
|
36
36
|
`).split(`
|
|
37
|
-
`),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function
|
|
38
|
-
`)){let o=
|
|
37
|
+
`),i=o.pop()??"",s=o.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),i}function Em(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function vE(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??-1}}function wE(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function SE(r,e,t,n,o){r.stdout?.on("data",i=>{let s=i.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=bm(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",i=>{let s=i.toString();e.stderrChunks.push(s),e.stderrLineBuffer=bm(e.stderrLineBuffer+s,"stderr",t)}),r.on("error",i=>{e.settled||(e.settled=!0,t.onError(i),o(i))}),r.on("close",i=>{if(e.settled)return;e.settled=!0,Em(e.stdoutLineBuffer,"stdout",t),Em(e.stderrLineBuffer,"stderr",t),t.onClose(i);let s=vE(e,i);n(s)})}async function No(r,e=[],t={}){try{let{stdout:n,stderr:o}=await yE(r,e,t);return{stdout:typeof n=="string"?n.trim():"",stderr:typeof o=="string"?o.trim():"",exitCode:0}}catch(n){let o=n;return{stdout:o.stdout?.trim()||"",stderr:o.stderr?.trim()??o.message,exitCode:typeof o.code=="number"?o.code:1}}}async function Cm(r,e,t){return await new Promise((n,o)=>{let i=hE(r,e,{stdio:["inherit","pipe","pipe"]}),s=wE();SE(i,s,t,n,o)})}function Pm(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var bE=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],EE=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function cr(r){return r?bE.some(e=>e.test(r))?"transient":EE.some(e=>e.test(r))?"fatal":"ok":"ok"}var CE=/(?:^|\s)(\d{2,})(?:\s|$)/;function Am(r){let e=r.stdout.trim(),t=r.stderr.trim();return cr(e)!=="ok"||cr(t)!=="ok"?"query-failed":r.exitCode===0?e&&CE.test(e)?"alive":"dead":r.exitCode===1&&!e&&!t?"dead":"query-failed"}var ul=[800,1500,2500];function PE(r){return new Promise(e=>setTimeout(e,r))}async function te(r,e){let t=1+ul.length,n={stdout:"",stderr:"",exitCode:-1};for(let o=0;o<t;o++){if(n=await No(r,e),n.exitCode===0||cr(n.stderr)!=="transient"||o>=t-1)return n;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${ul[o]}ms`),await PE(ul[o])}return n}var Im=/^[\w.-]+$/;async function Es(r,e,t){if(!Im.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let n=["-t",e,"shell","param","get",t];m(`Executing: ${r} ${n.join(" ")}`);let o=await te(r,n);if(o.exitCode!==0)return;let i=o.stdout.trim();if(!(!i||cr(i)!=="ok"))return Pm(i)}var pl="__DEVECO_PARAM_DELIM__";function AE(r,e){let t=new Map,n=r.split(pl);for(let o=0;o<e.length;o++){let i=(n[o]??"").trim();if(!i||cr(i)!=="ok")continue;let s=Pm(i);s&&t.set(e[o],s)}return t}async function Cn(r,e,t){let n=t.filter(a=>Im.test(a)?!0:(m(`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 Es(r,e,n[0]);return c&&a.set(n[0],c),a}let o=n.map(a=>`param get ${a}`).join(`; echo ${pl}; `)+`; echo ${pl}`,i=await te(r,["-t",e,"shell",o]);if(i.exitCode===0){let a=AE(i.stdout,n);if(a.size>0)return a}m(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of n){let c=await Es(r,e,a);c&&s.set(a,c)}return s}function Dt(r){return r.startsWith("127.0.0.1:")}var km=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ue=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(),o=t?.trim();if(!n||!o)return n;let i=new RegExp(`^${this.escapeRegExp(o)}(\\s+|[-_]+)?`,"i");return n.replace(i,"").trim()||n}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),IE(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
|
|
38
|
+
`)){let o=n.trim();if(!o||o.startsWith("[Empty]"))continue;let i=o.split(/\s+/),s=i[0];if(!s||s.startsWith("[Empty]"))continue;let a=i.length>=2?i[1]:"device";if(a.toLowerCase()==="unauthorized"){m(`[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 o=e.get("const.product.model");if(o&&o!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(o,s)}let i=e.get("const.build.product");if(i&&i!=="emulator")return i}async getDeviceName(e){let t=await Cn(this.hdcPath,e,[...km]);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 o=t.toLowerCase(),i=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===o&&i.push({device:s,name:a})}if(i.length===1)return i[0].device;throw i.length>1?new w(`Multiple devices match "${t}". Use a serial instead:
|
|
39
39
|
`+i.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
40
|
-
`),"Multiple devices match."):new v(`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 yr(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let o=r.get("const.ohos.apiversion"),i=r.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}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=It(e),r,o;try{let i=await yr(this.hdcPath,e,[...em]);r=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:o}}};var pt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;f(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await tm(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){b.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 o=`/data/local/tmp/${Fb()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,r){b.assertBundleNameStrict(t),b.assertAbilityName(r);let o=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(o)}async forceStopApp(e,t){b.assertBundleNameStrict(t);let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}async transferFile(e,t,r,o){let i=["-t",e,"file",t,r,o],s=await this.runHdc(i,!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 o=["-t",e,"shell","sqlite3",t,...r];await tm(this.toolProvider.hdcPath,o,{stdio:"inherit",env:{...process.env}})}};import Kc from"fs";import*as Gn from"path";function To(n,e){if(!Kc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Kc.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 o=Gn.resolve(e),i=new Set,s=[];for(let a of r){let c=Gn.resolve(o,a),l=Gn.isAbsolute(a)?Gn.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=b.isPathContainedWithSymlink(l,o);if(!d.contained){if(!Kc.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}`)}i.has(c)||(i.add(c),s.push(c))}return s}import Xc from"fs";import Ro from"path";import{execa as Hb}from"execa";import nm from"fs";import*as rm from"path";import jb from"json5";function $b(n,e){try{let r=jb.parse(nm.readFileSync(n,"utf-8")).modules?.find(o=>o.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return f(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function At(n,e){let t=rm.join(n,"build-profile.json5");return nm.existsSync(t)?$b(t,e)??e:e}async function om(n,e,t,r){let o=Ro.dirname(n.javaPath),i={...process.env,PATH:`${o}${Ro.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"];f(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await Hb(n.nodePath,s,{cwd:e,env:i,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=>Bb(e,l,r))}function im(n,e,t){let r=At(n,e);return Ro.join(n,r,"build",t,"outputs")}function Ub(n,e,t){return Ro.join(im(n,e,t),`${e}-${t}-signed.hqf`)}function Bb(n,e,t){let r=im(n,e,t),o=Ub(n,e,t);if(Xc.existsSync(o))return o;let i=Zc(r,"-signed.hqf")??Zc(r,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${r})`);return f(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function Zc(n,e){if(!Xc.existsSync(n))return null;for(let t of Xc.readdirSync(n,{withFileTypes:!0})){let r=Ro.join(n,t.name);if(t.isDirectory()){let o=Zc(r,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import Q from"fs";import*as N from"path";import Qc from"json5";var sm="default",wr=class n{static writeChangedFileLists(e,t,r,o){let i=t||sm,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,i,c,d,o),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let o=t||sm,i=n.loadBuildProfile(e);if(!i)return[];let s=i.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,o,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let o=n.getModuleType(e,r.srcPath);return o==="entry"||o==="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,o,i){let s=[];for(let a of e){let c=N.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,o);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,i,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,o){let i=n.getModuleType(t,e.srcPath);return i==="entry"||i==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,o,t,r))}static dispatchToCollectors(e,t,r,o,i,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,o.fileClass,i,s)}}static flushCollectors(e,t,r,o,i){let s=[];for(let a of r){let c=o.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!i||a.name===i)&&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,o){let i=N.join(e,r,"build",t,"intermediates","patch","default"),s=N.join(i,"changedFileList.json");if(Q.existsSync(s)||(Q.mkdirSync(i,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=N.join(e,r,"build",t,"intermediates","hotReload"),c=N.join(a,"changedFileList.json");Q.existsSync(c)||(Q.mkdirSync(a,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=N.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8");return Qc.parse(r)}catch{return null}}static classifyFile(e,t,r){let o=N.extname(e).toLowerCase();if(o===".ets"||o===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(o===".cpp"||o===".cc"||o===".c"||o===".h"||o===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let i=e.replace(/\\/g,"/");return i.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:i.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let o=N.normalize(e);for(let i of r){let s=N.normalize(N.join(t,i.srcPath)),a=s+N.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let r=N.join(e,t,"src","main","module.json5");if(!Q.existsSync(r))return"entry";try{let o=Q.readFileSync(r,"utf-8");return Qc.parse(o)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let o of t){let i=n.readLocalDependencies(e,o.srcPath);for(let s of i){let a=r.get(s)||[];a.includes(o.name)||a.push(o.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=N.join(e,t,"oh-package.json5");if(!Q.existsSync(r))return[];try{let o=Q.readFileSync(r,"utf-8"),i=Qc.parse(o);return n.resolveDepModuleNames(e,t,i.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let o=n.loadBuildProfile(e);if(!o)return[];let i=o.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,i);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,o){let i=r;if(!(i.startsWith("file:")||i.startsWith(".")||i.startsWith("..")))return null;i.startsWith("file:")&&(i=i.substring(5));let a=N.resolve(e,t,i);return o.find(l=>N.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,o){let i=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,o,i,a))}return i}static processDependents(e,t,r,o,i,s){let a=t.get(e)||[];for(let c of a){let l=o.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&i.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,o,i){let s=N.join(i,o,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:i}),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,o){let i=t.replace(/^\.\//,""),s=N.join(e,i,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,o),l=N.dirname(s);Q.existsSync(l)||Q.mkdirSync(l,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),f(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!Q.existsSync(e))return[];try{let t=Q.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,o,i,s){let a=t.replace(/^\.\//,""),c=N.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=N.join(e,a,"src","main","ets"),g=o.map(Se=>n.resolveRelativePathForPatch(Se,d)),w=n.mergeStrings(l.modifiedFiles,g),C=n.mergePatchResources(l.rawFile,i),z=n.mergePatchResources(l.resFile,s),de=N.dirname(c);Q.existsSync(de)||Q.mkdirSync(de,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({resources:{resFile:z,rawFile:C},modifiedFiles:w}),"utf-8"),f(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!Q.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=Q.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 N.relative(N.normalize(t),N.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}static mergeStrings(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i)||(r.add(i),o.push(i));return o}static mergePatchResources(e,t){let r=new Set,o=[];for(let i of[...e,...t])r.has(i.filePath)||(r.add(i.filePath),o.push(i));return o}};import Wb from"fs";import{randomUUID as Vb}from"crypto";import{execa as Gb}from"execa";var vr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!Wb.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}b.assertBundleName(r);let i=`/data/local/tmp/${Vb()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,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",i],!1)}}async pushHqf(e,t,r,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}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 i=await this.runHdc(r,!1);if(f(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(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;f(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:o}=await Gb(r,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var qb="6.1.1",fs=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Wn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(qb);let t=To(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t);await this.stopApp(e);let o=await this.buildHqf(e,r);await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=wr.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 f(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await om(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let o=await new vr(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!o.success)throw new Error(`hqf install failed: ${o.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new pt(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 pt(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){console.warn(`[Apply] launch app failed: ${r.message}`)}}};import el from"fs";import*as $ from"path";var hs=class n{static generate(e,t,r,o){let i=At(e,t),s=$.join(e,i),a=$.join(s,"build","config"),c=n.buildConfig(e,s,r,o);el.mkdirSync(a,{recursive:!0}),el.writeFileSync($.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=$.join(s,"build",r,"intermediates","loader_out",r,"ets");el.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,r,o){let i=$.dirname(o.nodePath)+$.sep,s=$.join(t,"build",r),a=$.join(s,"intermediates"),c=$.join(a,"loader_out",r),l=$.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:$.join(e,"build-profile.json5"),localPropertiesPath:$.join(e,"local.properties"),appResource:$.join(l,"ResourceTable.txt"),cachePath:$.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:$.join(a,"loader",r,"loader.json"),aceModuleJsonPath:$.join(l,"module.json"),aceSoPath:$.join(c,"nativeDependencies.txt"),aceModuleRoot:$.join(t,"src","main","ets"),aceModuleBuild:$.join(c,"ets"),aceProfilePath:$.join(l,"resources","base","profile"),aceSuperVisualPath:$.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:$.join(c,"ets"),changedFileList:$.join(a,"patch",r,"changedFileList.json"),patchAbcPath:$.join(a,"patch",r,"ets"),removeChangedFileListInSdk:"true"}}}};import am from"fs";import*as U from"path";var gs=class n{static generate(e,t,r,o){let i=At(e,t),s=U.join(e,i),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,o);am.mkdirSync(a,{recursive:!0}),am.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),f(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,o){let i=U.dirname(o.nodePath)+U.sep,s=U.join(t,"build",r),a=U.join(s,"intermediates"),c=U.join(a,"loader_out",r),l=U.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:U.join(e,"build-profile.json5"),localPropertiesPath:U.join(e,"local.properties"),appResource:U.join(l,"ResourceTable.txt"),cachePath:U.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:U.join(a,"loader",r,"loader.json"),aceModuleJsonPath:U.join(l,"module.json"),aceSoPath:U.join(c,"nativeDependencies.txt"),aceModuleRoot:U.join(t,"src","main","ets"),aceModuleBuild:U.join(c,"ets"),aceProfilePath:U.join(l,"resources","base","profile"),aceSuperVisualPath:U.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:U.join(c,"ets"),changedFileList:U.join(a,"hotReload","changedFileList.json"),patchAbcPath:U.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import cm from"crypto";import tt from"fs";import nt from"path";import lm from"os";import{io as zb}from"socket.io-client";var Jb=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Sr=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),o=this.watchLogPath;tt.mkdirSync(nt.dirname(o),{recursive:!0}),tt.writeFileSync(o,"");let i=this.createWatchLogBuffer(o);r.on("WatchLog",i.onWatchLog),r.on("WatchResult",i.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
40
|
+
`),"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 Cn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=n.get("const.product.devicetype");let o=n.get("const.ohos.apiversion"),i=n.get("const.ohos.releasetype");o&&(t.osVersion=i?`API ${o} (${i})`:`API ${o}`)}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=Dt(e),n,o;try{let i=await Cn(this.hdcPath,e,[...km]);n=this.extractDisplayName(i),o=i.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:o}}};var Ze=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ue.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;m(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:o}=await Dm(n,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.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){if(t.length===0)return;let o=`/data/local/tmp/${kE()}`;try{await this.runHdc(["-t",e,"shell","mkdir",o]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,o+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let i=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!i.includes("install bundle successfully."))throw new Error(i);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async launchApp(e,t,n){E.assertBundleNameStrict(t),E.assertAbilityName(n);let o=["-t",e,"shell","aa","start","-a",n,"-b",t];return await this.runHdc(o)}async pidofBundle(e,t){E.assertBundleNameStrict(t);let n=["-t",e,"shell","pidof",t],o=this.toolProvider.hdcPath;m(`Executing: ${o} ${n.join(" ")}`);let i=await te(o,n),s=Am(i);if(s==="query-failed"){let a=[i.stdout,i.stderr].map(c=>c.trim()).filter(Boolean).join(" ");throw new Error(`pidof query failed for '${t}': ${a||`exit ${i.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,o){let i=["-t",e,"file",t,n,o],s=await this.runHdc(i,!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 o=["-t",e,"shell","sqlite3",t,...n];await Dm(this.toolProvider.hdcPath,o,{stdio:"inherit",env:{...process.env}})}};import ml from"fs";import*as Kr from"path";function Oo(r,e){if(!ml.existsSync(r))throw new Error(`Apply file list not found: ${r}`);let n=ml.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 o=Kr.resolve(e),i=new Set,s=[];for(let a of n){let c=Kr.resolve(o,a),l=Kr.isAbsolute(a)?Kr.relative(o,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,o);if(!d.contained){if(!ml.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}`)}i.has(c)||(i.add(c),s.push(c))}return s}import fl from"fs";import Mo from"path";import{execa as RE}from"execa";import Tm from"fs";import*as Rm from"path";import DE from"json5";function TE(r,e){try{let n=DE.parse(Tm.readFileSync(r,"utf-8")).modules?.find(o=>o.name===e);return n?.srcPath?n.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function Tt(r,e){let t=Rm.join(r,"build-profile.json5");return Tm.existsSync(t)?TE(t,e)??e:e}async function xm(r,e,t,n){let o=Mo.dirname(r.javaPath),i={...process.env,PATH:`${o}${Mo.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","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${r.nodePath} ${s.join(" ")}`);let a=await RE(r.nodePath,s,{cwd:e,env:i,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=>LE(e,l,n))}function Lm(r,e,t){let n=Tt(r,e);return Mo.join(r,n,"build",t,"outputs")}function xE(r,e,t){return Mo.join(Lm(r,e,t),`${e}-${t}-signed.hqf`)}function LE(r,e,t){let n=Lm(r,e,t),o=xE(r,e,t);if(fl.existsSync(o))return o;let i=hl(n,"-signed.hqf")??hl(n,".hqf");if(!i)throw new Error(`Signed hqf not found at ${o} (and no *.hqf under ${n})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${i}`),i}function hl(r,e){if(!fl.existsSync(r))return null;for(let t of fl.readdirSync(r,{withFileTypes:!0})){let n=Mo.join(r,t.name);if(t.isDirectory()){let o=hl(n,e);if(o)return o}else if(t.isFile()&&t.name.endsWith(e))return n}return null}import re from"fs";import*as O from"path";import gl from"json5";var Nm="default",Pn=class r{static writeChangedFileLists(e,t,n,o){let i=t||Nm,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),g=r.collectChanges(n,e,a,l,d);return{writtenModules:r.flushCollectors(e,i,c,d,o),skippedFiles:g}}static initEmptyChangedFileLists(e,t,n){let o=t||Nm,i=r.loadBuildProfile(e);if(!i)return[];let s=i.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,o,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(n=>{let o=r.getModuleType(e,n.srcPath);return o==="entry"||o==="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,o,i){let s=[];for(let a of e){let c=O.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 g=r.resolveTargetModules(d,t,n,o);if(g.length===0){s.push(c);continue}r.dispatchToCollectors(g,i,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,n,o){let i=r.getModuleType(t,e.srcPath);return i==="entry"||i==="shared"?[e.name]:Array.from(r.findTopLevelConsumers(e.name,o,t,n))}static dispatchToCollectors(e,t,n,o,i,s){for(let a of e){let c=t.get(a);c&&r.addFileToCollector(c,n,o.fileClass,i,s)}}static flushCollectors(e,t,n,o,i){let s=[];for(let a of n){let c=o.get(a.name);if(!c||!r.hasAnyChange(c))continue;(!i||a.name===i)&&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,o){let i=O.join(e,n,"build",t,"intermediates","patch","default"),s=O.join(i,"changedFileList.json");if(re.existsSync(s)||(re.mkdirSync(i,{recursive:!0}),re.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!o)return;let a=O.join(e,n,"build",t,"intermediates","hotReload"),c=O.join(a,"changedFileList.json");re.existsSync(c)||(re.mkdirSync(a,{recursive:!0}),re.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=O.join(e,"build-profile.json5");if(!re.existsSync(t))return null;try{let n=re.readFileSync(t,"utf-8");return gl.parse(n)}catch{return null}}static classifyFile(e,t,n){let o=O.extname(e).toLowerCase();if(o===".ets"||o===".ts")return{fileClass:"ets_ts",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""};if(o===".cpp"||o===".cc"||o===".c"||o===".h"||o===".hpp")return{fileClass:"native",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""};let i=e.replace(/\\/g,"/");return i.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""}:i.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:r.findModuleByFilePath(e,t,n)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,n){let o=O.normalize(e);for(let i of n){let s=O.normalize(O.join(t,i.srcPath)),a=s+O.sep;if(o.startsWith(a)||o===s)return i}return null}static getModuleType(e,t){let n=O.join(e,t,"src","main","module.json5");if(!re.existsSync(n))return"entry";try{let o=re.readFileSync(n,"utf-8");return gl.parse(o)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let n=new Map;for(let o of t){let i=r.readLocalDependencies(e,o.srcPath);for(let s of i){let a=n.get(s)||[];a.includes(o.name)||a.push(o.name),n.set(s,a)}}return n}static readLocalDependencies(e,t){let n=O.join(e,t,"oh-package.json5");if(!re.existsSync(n))return[];try{let o=re.readFileSync(n,"utf-8"),i=gl.parse(o);return r.resolveDepModuleNames(e,t,i.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,n){let o=r.loadBuildProfile(e);if(!o)return[];let i=o.modules,s=[];for(let a of Object.values(n)){if(typeof a!="string")continue;let c=r.tryResolveDepModule(e,t,a,i);c&&s.push(c)}return s}static tryResolveDepModule(e,t,n,o){let i=n;if(!(i.startsWith("file:")||i.startsWith(".")||i.startsWith("..")))return null;i.startsWith("file:")&&(i=i.substring(5));let a=O.resolve(e,t,i);return o.find(l=>O.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,n,o){let i=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,o,i,a))}return i}static processDependents(e,t,n,o,i,s){let a=t.get(e)||[];for(let c of a){let l=o.find(g=>g.name===c);if(!l)continue;let d=r.getModuleType(n,l.srcPath);(d==="entry"||d==="shared")&&i.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,n,o,i){let s=O.join(i,o,"src","main","resources");n==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:i}),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,o){let i=t.replace(/^\.\//,""),s=O.join(e,i,"build",n,"intermediates","hotReload","changedFileList.json"),a=r.readExistingApply(s),c=r.mergeApplyEntries(a,o),l=O.dirname(s);re.existsSync(l)||re.mkdirSync(l,{recursive:!0}),re.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!re.existsSync(e))return[];try{let t=re.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,n,o,i,s){let a=t.replace(/^\.\//,""),c=O.join(e,a,"build",n,"intermediates","patch","default","changedFileList.json"),l=r.readExistingPatch(c),d=O.join(e,a,"src","main","ets"),g=o.map(me=>r.resolveRelativePathForPatch(me,d)),v=r.mergeStrings(l.modifiedFiles,g),b=r.mergePatchResources(l.rawFile,i),N=r.mergePatchResources(l.resFile,s),$=O.dirname(c);re.existsSync($)||re.mkdirSync($,{recursive:!0}),re.writeFileSync(c,JSON.stringify({resources:{resFile:N,rawFile:b},modifiedFiles:v}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!re.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=re.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 O.relative(O.normalize(t),O.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let n=new Set,o=[];for(let i of[...e,...t])n.has(i.filePath)||(n.add(i.filePath),o.push(i));return o}static mergeStrings(e,t){let n=new Set,o=[];for(let i of[...e,...t])n.has(i)||(n.add(i),o.push(i));return o}static mergePatchResources(e,t){let n=new Set,o=[];for(let i of[...e,...t])n.has(i.filePath)||(n.add(i.filePath),o.push(i));return o}};import NE from"fs";import{randomUUID as OE}from"crypto";import{execa as ME}from"execa";var An=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,n){for(let a of t)if(!NE.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}E.assertBundleName(n);let i=`/data/local/tmp/${OE()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${i}/${n}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],i,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",i],!1)}}async pushHqf(e,t,n,o){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",n]);let i=await this.runHdc(["-t",e,"file","send",t,o]);if(!i.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${i}`)}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 i=await this.runHdc(n,!1);if(m(`[InstallHqf] quickfix output: ${i}`),/succe(?:ed|ss)/i.test(i))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${i||"(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;m(`[InstallHqf] Executing: ${n} ${e.join(" ")}`);try{let{stdout:o}=await ME(n,e,{env:{...process.env}});return o}catch(o){if(t)throw o;return o.stdout||""}}};var _E="6.1.1",Cs=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;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(_E);let t=Oo(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let n=this.writeChangeFileList(e,t);await this.stopApp(e);let o=await this.buildHqf(e,n);await this.installHqf(e,o),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let n=Pn.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 m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await xm(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let o=await new An(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!o.success)throw new Error(`hqf install failed: ${o.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Ze(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 Ze(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 yl from"fs";import*as U from"path";var Ps=class r{static generate(e,t,n,o){let i=Tt(e,t),s=U.join(e,i),a=U.join(s,"build","config"),c=r.buildConfig(e,s,n,o);yl.mkdirSync(a,{recursive:!0}),yl.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`);let l=U.join(s,"build",n,"intermediates","loader_out",n,"ets");yl.mkdirSync(l,{recursive:!0})}static buildConfig(e,t,n,o){let i=U.dirname(o.nodePath)+U.sep,s=U.join(t,"build",n),a=U.join(s,"intermediates"),c=U.join(a,"loader_out",n),l=U.join(a,"res",n);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:U.join(e,"build-profile.json5"),localPropertiesPath:U.join(e,"local.properties"),appResource:U.join(l,"ResourceTable.txt"),cachePath:U.join(s,"cache",n,`${n}@CompileArkTS`,"esmodule","debug"),aceBuildJson:U.join(a,"loader",n,"loader.json"),aceModuleJsonPath:U.join(l,"module.json"),aceSoPath:U.join(c,"nativeDependencies.txt"),aceModuleRoot:U.join(t,"src","main","ets"),aceModuleBuild:U.join(c,"ets"),aceProfilePath:U.join(l,"resources","base","profile"),aceSuperVisualPath:U.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"false",mode:"hotReload",oldMapFilePath:U.join(c,"ets"),changedFileList:U.join(a,"patch",n,"changedFileList.json"),patchAbcPath:U.join(a,"patch",n,"ets"),removeChangedFileListInSdk:"true"}}}};import Om from"fs";import*as W from"path";var As=class r{static generate(e,t,n,o){let i=Tt(e,t),s=W.join(e,i),a=W.join(s,"build","config"),c=r.buildConfig(e,s,n,o);Om.mkdirSync(a,{recursive:!0}),Om.writeFileSync(W.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,n,o){let i=W.dirname(o.nodePath)+W.sep,s=W.join(t,"build",n),a=W.join(s,"intermediates"),c=W.join(a,"loader_out",n),l=W.join(a,"res",n);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:i,projectProfilePath:W.join(e,"build-profile.json5"),localPropertiesPath:W.join(e,"local.properties"),appResource:W.join(l,"ResourceTable.txt"),cachePath:W.join(s,"cache",n,`${n}@CompileArkTS`,"esmodule","debug"),aceBuildJson:W.join(a,"loader",n,"loader.json"),aceModuleJsonPath:W.join(l,"module.json"),aceSoPath:W.join(c,"nativeDependencies.txt"),aceModuleRoot:W.join(t,"src","main","ets"),aceModuleBuild:W.join(c,"ets"),aceProfilePath:W.join(l,"resources","base","profile"),aceSuperVisualPath:W.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:W.join(c,"ets"),changedFileList:W.join(a,"hotReload","changedFileList.json"),patchAbcPath:W.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Mm from"crypto";import st from"fs";import at from"path";import _m from"os";import{io as FE}from"socket.io-client";var jE=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),In=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),o=this.watchLogPath;st.mkdirSync(at.dirname(o),{recursive:!0}),st.writeFileSync(o,"");let i=this.createWatchLogBuffer(o);n.on("WatchLog",i.onWatchLog),n.on("WatchResult",i.onWatchResult),await this.awaitInitialBuild(n,e)}createWatchLogBuffer(e){let n=[];return{onWatchLog:s=>{let a=r.extractText(s);a.trim()&&(n.push(a.endsWith(`
|
|
41
41
|
`)?a:a+`
|
|
42
|
-
`),
|
|
43
|
-
`].join("")),
|
|
42
|
+
`),n.length>100&&n.shift())},onWatchResult:s=>{let a=r.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),st.writeFileSync(e,[...n,c+`
|
|
43
|
+
`].join("")),n.length=0}}}awaitInitialBuild(e,t){return new Promise((n,o)=>{let i=!1,s=this.createOutputHandler(),a=l=>{!l?.status||i||(l.status==="finish"?(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),n()):(l.status==="reject"||l.status==="close")&&(i=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),o(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{i||(i=!0,o(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 at.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=FE(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((o,i)=>{let s=setTimeout(()=>{i(new Error("Socket connect timeout (10s)"))},1e4);n.once("connect",()=>{clearTimeout(s),o()}),n.once("connect_error",a=>{clearTimeout(s),i(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((o,i)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(n,()=>s,d=>s=d,i),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`),o(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),n.off("BuildStatus",l),this.invalidateSocket(),i(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,o){let i=v=>{t()||(n(!0),g(),this.invalidateSocket(),o(new Error(`Socket disconnected: ${v}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",i),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:i,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=r.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
|
|
44
44
|
`)?"":`
|
|
45
|
-
`))},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 o=this.findProjectDaemon();if(o&&(o.state==="half_busy"||o.state==="idle"))return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!tt.existsSync(e))return null;try{let t=tt.readFileSync(e,"utf-8"),r=JSON.parse(t),o=Object.values(r).filter(i=>i.cwdPath===this.projectRoot&&(i.state==="idle"||i.state==="half_busy"||i.state==="busy")&&this.isProcessAlive(i.pid));return o.length>0?o[o.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=nt.join(t,"fd"),o=nt.join(t,"ac"),i=nt.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(Jb)]),c=this.readSingleFile(o),l=cm.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),g=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,o=t.readUInt32BE(r);r+=4;let i=t.subarray(r,r+12);r+=12;let s=o-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=cm.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=tt.readdirSync(e).map(r=>nt.join(e,r)).filter(r=>tt.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 o=tt.readdirSync(r);if(o.length===0)throw new Error(`No file in ${r}`);return tt.readFileSync(nt.join(r,o[0]))})}readSingleFile(e){let t=tt.readdirSync(e).map(r=>nt.join(e,r)).filter(r=>tt.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return tt.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 o=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let i=0;i<t.length;i++)t[i]^=o[i]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||nt.join(lm.homedir(),".hvigor");return nt.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||nt.join(lm.homedir(),".hvigor");return nt.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import pm from"fs";import*as Ot from"path";import{green as Ss,yellow as tl}from"colorette";import qn from"fs";import*as zn from"path";import Yb from"json5";var Kb=2e6,Xb=1e6,Zb="hotreload",ys=class n{static generateOrUpdate(e,t,r){let o=n.readAppConfig(e),i=zn.resolve(e,t),s=zn.join(i,"patch.json"),a;return qn.existsSync(s)?(f(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(f(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:Kb,versionCode:o.versionCode},module:{name:r,type:Zb}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=zn.join(e,"AppScope","app.json5");if(!qn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=qn.readFileSync(t,"utf-8"),o=Yb.parse(r),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??Xb;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=qn.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=zn.dirname(e);qn.existsSync(r)||qn.mkdirSync(r,{recursive:!0});let o=JSON.stringify(t,null,2);qn.writeFileSync(e,o,"utf-8"),f(`[PatchManager] patch.json written to ${e}`),f(`[PatchManager] Content: ${o}`)}};import ye from"fs";import*as B from"path";import dm from"crypto";import Qb from"json5";import{execa as um}from"execa";var ws=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}`);f(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let o=B.resolve(e,"material"),i=n.getKey(o,r),s=new Int8Array(Buffer.from(t,"hex"));return f(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),n.decrypt(i,s).toString("utf-8")}static getKey(e,t){let r=B.resolve(e,n.DIRS[0]),o=n.readFd(r,t),i=n.readDirBytes(B.resolve(e,n.DIRS[1]),t),s=n.getRootKey(o,i,t),a=n.readDirBytes(B.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 o=[...e,n.COMPONENT],i=n.xor(o[0],o[1],r);for(let a=2;a<o.length;a++)i=n.xor(i,o[a],r);let s=dm.pbkdf2Sync(Buffer.from(i).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 o=new Int8Array(e.byteLength);for(let i=0;i<e.byteLength;i++)o[i]=e[i]^t[i];return o}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],o=t.length-4-r,i=t.slice(4,4+o),s=t.slice(t.length-16),a=dm.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(i));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+o,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=ye.readdirSync(e).filter(i=>i!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let o=[];for(let i of r){let s=B.join(e,i);o.push(n.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(ye.statSync(e).isDirectory()){let o=ye.readdirSync(e).filter(i=>i!==".DS_Store");if(o.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(ye.readFileSync(B.join(e,o[0])))}return new Int8Array(ye.readFileSync(e))}},vs=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${B.dirname(e.javaPath)}${B.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,o,i=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,o);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?i?{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=B.join(e,"ets","modules.abc");if(ye.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(!ye.existsSync(e))return null;let t=ye.readdirSync(e,{withFileTypes:!0});for(let r of t){let o=B.join(e,r.name);if(r.isDirectory()){let i=this.findFirstAbc(o);if(i)return i}else if(r.isFile()&&r.name.endsWith(".abc"))return o}return null}resolveHqfPaths(e,t){let r=At(this.projectRoot,e),o=B.join(this.projectRoot,r,"build",t,"outputs","default");return ye.existsSync(o)||ye.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:B.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:B.join(o,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let o=this.resolvePackingTool();if(!o)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let i=B.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",r,"--force","true"];f(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await um(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):ye.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 o=this.buildSignArgs(r,e,t),i=this.toolProvider.javaPath,s=o.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(o[c-1])?"******":a);f(`[GenSignHqf] Signing: ${i} ${s.join(" ")}`);try{let a=Date.now(),c=await um(i,o,{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}`):ye.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 o=ws.decryptPwd(r,t.storePassword,"storePassword"),i=ws.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:o,keyPwd:i,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=B.resolve(e.storeFile,".."),r=B.join(t,"material");return ye.existsSync(r)?t:null}readSigningConfig(e){let t=B.join(this.projectRoot,"build-profile.json5");if(!ye.existsSync(t))return null;try{let r=ye.readFileSync(t,"utf-8"),o=Qb.parse(r),s=o.app?.products?.find(a=>a.name===e)?.signingConfig;return s?o.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[B.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),B.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(ye.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=[B.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),B.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(ye.existsSync(r))return r;return null}};async function mm(n){let e=Date.now(),t=At(n.projectPath,n.moduleName),r=eE(n);console.log(tl("[HotReload] Ensure the project source is trusted before proceeding."));let o=tE(n),i=To(r,n.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${n.applyFileName}`),nE(n,i),rE(n,t),await oE(n,o);let s=Ot.join(n.projectPath,t,"patch.json"),a=await sE(n,t,s);return await aE(n,a),console.log(Ss("[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 eE(n){if(Ot.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Ot.join(n.projectPath,".hvigor",n.applyFileName)}function tE(n){let{projectPath:e,toolProvider:t}=n,r=new Sr(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 nE(n,e){let t=wr.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(Ss(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(tl(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function rE(n,e){let t=ys.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Ss(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function oE(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let o=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(o!==0){let i=iE(r);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
45
|
+
`))},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 o=this.findProjectDaemon();if(o&&(o.state==="half_busy"||o.state==="idle"))return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!st.existsSync(e))return null;try{let t=st.readFileSync(e,"utf-8"),n=JSON.parse(t),o=Object.values(n).filter(i=>i.cwdPath===this.projectRoot&&(i.state==="idle"||i.state==="half_busy"||i.state==="busy")&&this.isProcessAlive(i.pid));return o.length>0?o[o.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),n=at.join(t,"fd"),o=at.join(t,"ac"),i=at.join(t,"ce"),s=this.readComponents(n),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(jE)]),c=this.readSingleFile(o),l=Mm.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(i),g=this.aesGcmDecrypt(l,d),v=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,v).toString("utf-8")}aesGcmDecrypt(e,t){let n=0,o=t.readUInt32BE(n);n+=4;let i=t.subarray(n,n+12);n+=12;let s=o-16,a=t.subarray(n,n+s);n+=s;let c=t.subarray(n,n+16),l=Mm.createDecipheriv("aes-128-gcm",e,i);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=st.readdirSync(e).map(n=>at.join(e,n)).filter(n=>st.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 o=st.readdirSync(n);if(o.length===0)throw new Error(`No file in ${n}`);return st.readFileSync(at.join(n,o[0]))})}readSingleFile(e){let t=st.readdirSync(e).map(n=>at.join(e,n)).filter(n=>st.statSync(n).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return st.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 o=Buffer.isBuffer(e[n])?e[n]:Buffer.from(e[n]);for(let i=0;i<t.length;i++)t[i]^=o[i]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||at.join(_m.homedir(),".hvigor");return at.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||at.join(_m.homedir(),".hvigor");return at.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import $m from"fs";import*as Ft from"path";import{green as Ts,yellow as vl}from"colorette";import Xr from"fs";import*as Zr from"path";import $E from"json5";var HE=2e6,UE=1e6,BE="hotreload",Is=class r{static generateOrUpdate(e,t,n){let o=r.readAppConfig(e),i=Zr.resolve(e,t),s=Zr.join(i,"patch.json"),a;return Xr.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=r.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:o.bundleName,patchVersionCode:HE,versionCode:o.versionCode},module:{name:n,type:BE}}),r.writePatchJson(s,a),a}static readAppConfig(e){let t=Zr.join(e,"AppScope","app.json5");if(!Xr.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let n=Xr.readFileSync(t,"utf-8"),o=$E.parse(n),i=o?.app?.bundleName;if(!i)throw new Error("bundleName is missing in AppScope/app.json5");let s=o?.app?.versionCode??UE;return{bundleName:i,versionCode:s}}static readExistingPatch(e){let t=Xr.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=Zr.dirname(e);Xr.existsSync(n)||Xr.mkdirSync(n,{recursive:!0});let o=JSON.stringify(t,null,2);Xr.writeFileSync(e,o,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${o}`)}};import we from"fs";import*as G from"path";import Fm from"crypto";import WE from"json5";import{execa as jm}from"execa";var ks=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}`);m(`[DecipherUtil] Decrypting ${n}, encrypted length: ${t.length}`);let o=G.resolve(e,"material"),i=r.getKey(o,n),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${i.length}`),r.decrypt(i,s).toString("utf-8")}static getKey(e,t){let n=G.resolve(e,r.DIRS[0]),o=r.readFd(n,t),i=r.readDirBytes(G.resolve(e,r.DIRS[1]),t),s=r.getRootKey(o,i,t),a=r.readDirBytes(G.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 o=[...e,r.COMPONENT],i=r.xor(o[0],o[1],n);for(let a=2;a<o.length;a++)i=r.xor(i,o[a],n);let s=Fm.pbkdf2Sync(Buffer.from(i).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 o=new Int8Array(e.byteLength);for(let i=0;i<e.byteLength;i++)o[i]=e[i]^t[i];return o}static decrypt(e,t){let n=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],o=t.length-4-n,i=t.slice(4,4+o),s=t.slice(t.length-16),a=Fm.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(i));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+o,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let n=we.readdirSync(e).filter(i=>i!==".DS_Store");if(n.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let o=[];for(let i of n){let s=G.join(e,i);o.push(r.readDirBytes(s,t))}return o}static readDirBytes(e,t){if(we.statSync(e).isDirectory()){let o=we.readdirSync(e).filter(i=>i!==".DS_Store");if(o.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(we.readFileSync(G.join(e,o[0])))}return new Int8Array(we.readFileSync(e))}},Ds=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let o=`${G.dirname(e.javaPath)}${G.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,n,o,i=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,o);return await this.generateHqf(n,s.abcPath,a.unsignedHqfPath)?i?{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=G.join(e,"ets","modules.abc");if(we.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(!we.existsSync(e))return null;let t=we.readdirSync(e,{withFileTypes:!0});for(let n of t){let o=G.join(e,n.name);if(n.isDirectory()){let i=this.findFirstAbc(o);if(i)return i}else if(n.isFile()&&n.name.endsWith(".abc"))return o}return null}resolveHqfPaths(e,t){let n=Tt(this.projectRoot,e),o=G.join(this.projectRoot,n,"build",t,"outputs","default");return we.existsSync(o)||we.mkdirSync(o,{recursive:!0}),{unsignedHqfPath:G.join(o,`${e}-default-unsigned.hqf`),signedHqfPath:G.join(o,`${e}-default-signed.hqf`)}}async generateHqf(e,t,n){let o=this.resolvePackingTool();if(!o)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let i=G.dirname(t),s=this.toolProvider.javaPath,a=["-jar",o,"--mode","hqf","--json-path",e,"--ets-path",i,"--out-path",n,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await jm(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):we.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 o=this.buildSignArgs(n,e,t),i=this.toolProvider.javaPath,s=o.map((a,c)=>c>0&&["-keyPwd","-keystorePwd"].includes(o[c-1])?"******":a);m(`[GenSignHqf] Signing: ${i} ${s.join(" ")}`);try{let a=Date.now(),c=await jm(i,o,{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}`):we.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 o=ks.decryptPwd(n,t.storePassword,"storePassword"),i=ks.decryptPwd(n,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:o,keyPwd:i,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=G.resolve(e.storeFile,".."),n=G.join(t,"material");return we.existsSync(n)?t:null}readSigningConfig(e){let t=G.join(this.projectRoot,"build-profile.json5");if(!we.existsSync(t))return null;try{let n=we.readFileSync(t,"utf-8"),o=WE.parse(n),s=o.app?.products?.find(a=>a.name===e)?.signingConfig;return s?o.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[G.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),G.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let n of t)if(we.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=[G.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),G.join(e,"toolchains","lib","app_packing_tool.jar")];for(let n of t)if(we.existsSync(n))return n;return null}};async function Hm(r){let e=Date.now(),t=Tt(r.projectPath,r.moduleName),n=VE(r);console.log(vl("[HotReload] Ensure the project source is trusted before proceeding."));let o=GE(r),i=Oo(n,r.projectPath);console.log(`[HotReload] Parsed ${i.length} changed file(s) from ${r.applyFileName}`),zE(r,i),qE(r,t),await JE(r,o);let s=Ft.join(r.projectPath,t,"patch.json"),a=await KE(r,t,s);return await XE(r,a),console.log(Ts("[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 VE(r){if(Ft.basename(r.applyFileName)!==r.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r.applyFileName}`);return Ft.join(r.projectPath,".hvigor",r.applyFileName)}function GE(r){let{projectPath:e,toolProvider:t}=r,n=new In(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 zE(r,e){let t=Pn.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(Ts(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(vl(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function qE(r,e){let t=Is.generateOrUpdate(r.projectPath,e,r.moduleName);console.log(Ts(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function JE(r,e){let t=Date.now(),n=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let o=await e.sendHotCompile({moduleSpecs:r.moduleSpecs,productName:r.productName});if(o!==0){let i=YE(n);throw new Error(`Daemon hot compile exited with code ${o}`+(i?`
|
|
46
46
|
--- compile output (from watch session) ---
|
|
47
|
-
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function
|
|
48
|
-
`):""}catch{return""}}async function
|
|
49
|
-
`),
|
|
47
|
+
${i}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function YE(r){try{return $m.existsSync(r)?$m.readFileSync(r,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
|
|
48
|
+
`):""}catch{return""}}async function KE(r,e,t){let n=Ft.join(r.projectPath,e,"build",r.productName,"intermediates"),o=[Ft.join(n,"hotReload","patchAbcPath"),Ft.join(n,"patch","default")],i=Date.now(),s=new Ds(r.toolProvider,r.projectPath),a=r.targetDeviceId.includes("127.0.0.1")||r.targetDeviceId.includes("localhost"),c=null;for(let l of o){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()-i}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 XE(r,e){let t=Date.now(),o=await new An(r.toolProvider).install(r.targetDeviceId,e,r.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!o.success)throw new Error(`hqf install failed: ${o.message}`)}function wl(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 Um(r,e,t){let n=Ft.join(r.rootDir,".hvigor",t),o;try{o=Oo(n,r.rootDir)}catch{return}let i=new Set;for(let s of o){let a=r.findOwningModule(s);if(!a||a===e)continue;let c=r.getModuleType(a);(c==="feature"||c==="shared")&&i.add(`${a} (${c})`)}i.size>0&&console.warn(vl(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...i].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 Bm(r,e,t,n,o){let i=new Set,s=r.collectNonHarDependentModuleList(e);for(let a of s)i.add(r.findArtifactPath(a,t,n,o));return i.add(r.findArtifactPath(e,t,n,o)),[...i]}async function Wm(r,e){await new Ke(r,e.rootDir).stopDaemon(),console.log(Ts("Hvigor daemon stopped."))}var Rs=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:o,evidence:i}=e,s=[`Smoke: ${n}`,`${o} (bundle=${t.bundleName}, device=${t.targetDeviceId}).`];return n==="FAIL_CRASH"&&i.crashLogPath&&s.push(`crash_log: ${i.crashLogPath}`),n==="FAIL_BLANK"&&i.screenshotPath&&s.push(`screenshot: ${i.screenshotPath}`),s.join(`
|
|
49
|
+
`)}toTraceError(e,t){return new w(this.formatFailure(e,t),e.status)}};import _s from"fs";import DC from"path";import{yellow as Ho}from"colorette";import{cyan as xs}from"colorette";function Qr(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=cr(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 Sl=[800,1500,2500];function QE(r){return new Promise(e=>setTimeout(e,r))}var lr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ue.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(`
|
|
50
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return m(xs(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return m(xs(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(n,e);if(o)return m(xs(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(n);throw new w(`Device '${e}' not found.
|
|
51
|
+
Available devices:
|
|
52
|
+
${i}`,"Device not found.")}if(n.length===1){let o=n[0];return m(xs(`Using device: ${o.name} (${o.serial})`)),o.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){m(`Retrieving PID for bundle ${n}`),E.assertBundleNameStrict(n);let o=await te(e,["-t",t,"shell","pidof",n]),i=Qr(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${n}: ${a}`),a}return m(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){if(m(`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 o=await te(e,["-t",t,"shell","hilog","-G",n]),i=Qr(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,n,o){let i=this.buildHilogShellCommand(n,o);return[e,["-t",t,"shell",i]]}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,o,i){let a=await Cm(e,t,{onData:n,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,n,o,i){let s=1+Sl.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,n,o,i),a.exitCode===0||cr(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Sl[c]}ms`),await QE(Sl[c])}return a}async runHilogStreamingCollect(e,t,n){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{m(`Callback triggered when an error occurs during ${n}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,n,o){if(!n.tail&&!n.fromSeconds&&!n.toSeconds)return;let i={...n,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Qr(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,o){let[i,s]=this.buildHilogCommand(e,t,n,o);m(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=Qr(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,o){try{await this.printTailSnapshotIfNeeded(e,t,n,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,n,o);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Qr(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,o=t.bundleName?await this.getPidForBundle(n,e,t.bundleName):void 0;if(t.bundleName&&!o)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,o||""):await this.getHilogOnce(n,e,t,o||"")}async getLatestCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let n=this.toolProvider.hdcPath,o=await this.listCrashLogs(n,e,t);if(o.length===0)return;let s=[...o].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 o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=Qr(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return m(`Crash logs list output:
|
|
53
|
+
${i.stdout}`),this.parseCrashLogFilenames(i.stdout,n)}parseCrashLogFilenames(e,t){return e.split(`
|
|
54
|
+
`).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){m(`Fetching latest crash log file: ${n}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];m(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=Qr(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};import{readFileSync as tC,unlinkSync as rC}from"fs";import{tmpdir as nC}from"os";import{join as oC}from"path";var jt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),n=eC(t);return e?.all||(n=n.filter(o=>o.type===1)),n}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await te(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function eC(r){let e=r.split(`
|
|
55
|
+
`),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]),g=Number(c[2]),v=Number(c[3]),b=Number(c[4]);Number.isFinite(v)&&Number.isFinite(d)&&Number.isFinite(g)&&n.push({id:v,name:l,pid:g,displayId:d,type:b})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return n.map(s=>({...s,focused:s.id===i}))}function Vm(r){if(!(!r||r==="HitTestMode.Default"))return r.startsWith("HitTestMode.")?r.slice(12):r}function _o(r){if(!(r==null||r==="")){if(typeof r=="boolean")return r;if(r==="true")return!0;if(r==="false")return!1}}function Gm(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 zm(r){return r.originalText||void 0}function kn(r,e){let t=[],n=[...r].reverse();for(;n.length>0;){let o=n.pop();o.id===e&&t.push(o);for(let i=o.children.length-1;i>=0;i--)n.push(o.children[i])}return t}function qm(r,e){let t=[],n=[{current:r,parent:null,depth:0}];for(;n.length>0;){let{current:o,parent:i,depth:s}=n.pop(),a=i===null,c=!o.id&&!o.text&&!o.clickable&&!o.longClickable&&!o.scrollable&&!o.checkable,l=a||!c,d=i;if(l){let v={...o,children:[]};if(a?t.push(v):i.children.push(v),d=v,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let v=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";m(`collapse ${v} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let v=o.children.length-1;v>=0;v--)n.push({current:o.children[v],parent:d,depth:g})}return t}function iC(r){let e=tC(r,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function sC(r){return r.attributes??{}}function Ls(r,e,t){let n=sC(r),o={id:n.id||void 0,type:n.type||void 0,text:zm(n),bounds:Gm(n.bounds),clickable:_o(n.clickable)||void 0,longClickable:_o(n.longClickable)||void 0,scrollable:_o(n.scrollable)||void 0,checkable:_o(n.checkable)||void 0,hitTestBehavior:Vm(n.hitTestBehavior),children:[]};return e>0&&t+1>=e||r.children&&(o.children=r.children.map(i=>Ls(i,e,t+1))),o}function aC(r,e){if(e){let n=r.find(o=>String(o.id)===e);if(!n){let o=r.map(i=>`${i.id} (${i.name})`).join(", ");throw new w(`Window '${e}' not found. Available windows: ${o||"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 en=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 o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];n!==void 0&&i.push("-d",String(n)),t&&i.push("-w",t),m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await te(this.hdcPath,i);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,o)}async recvAndParseDump(e,t){let n=oC(nC(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,n),iC(n)}finally{await this.cleanupDumpArtifacts(e,n,t)}}async recvDumpFile(e,t,n){let o=["-t",e,"file","recv",t,n];m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await te(this.hdcPath,o);if(i.exitCode!==0)throw new Error(`Failed to recv dump file: ${(i.stderr||i.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,n){try{m(`Removing local dump file: ${t}`),rC(t)}catch(i){m(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",n];m(`Executing: ${this.hdcPath} ${o.join(" ")}`),await te(this.hdcPath,o).catch(i=>{m(`Failed to clean remote dump file ${n}: ${i.message}`)})}async dumpRawNodes(e,t,n){let i=await new jt(this.hdcPath,e).listWindows({all:!0});if(n){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=aC(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,n,o){return(await this.dumpRawNodes(e,n,o)).map(s=>Ls(s,t,0))}async dumpFullTreeByDisplays(e,t,n){let o=[];for(let i of n){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:Ls(s,t,0)})}return o}async dumpCollapsedTree(e,t,n,o){return(await this.dumpRawNodes(e,n,o)).flatMap(s=>qm(Ls(s,0,0),t))}};import He from"fs";import Pe from"path";import{randomUUID as cC}from"crypto";function Jm(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 Ym(r,e){return[r,e].filter(Boolean).join(`
|
|
56
|
+
`).trim()}function Km(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 Xm(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 Zm(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 lC(){return String(Date.now())}function bl(r){let e;try{e=He.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{He.accessSync(r,He.constants.W_OK|He.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${r}`,{cause:t})}}function El(r,e){try{throw He.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 Qm(r){if(!He.existsSync(r))throw new Error(`Screenshot file was not created: ${r}`);let e=He.statSync(r);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${r}`);let t=He.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 ef(r){try{return Qm(r),!0}catch{return!1}}function tf(r){let e=[];for(let t of He.readdirSync(r,{withFileTypes:!0})){let n=Pe.join(r,t.name);if(t.isDirectory()){e.push(...tf(n));continue}t.isFile()&&ef(n)&&e.push(n)}return e}function dC(r,e){let t=Pe.join(r,Pe.basename(e));if(ef(t))return t;let n=tf(r);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple screenshot files were received in ${r}.`)}function uC(r,e){try{He.copyFileSync(r,e,He.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Qm(e)}var tn=class{constructor(e){this.toolProvider=e}toolProvider;resolveDestinationPath(e){if(!e?.trim())throw new Error("--path is required.");let t=e.trim(),n=Pe.resolve(t);try{if(He.statSync(n).isDirectory()){bl(n);let i=Pe.join(n,`screenshot-${lC()}.png`);return El(i,n),i}}catch(i){if(i.code!=="ENOENT")throw i}if(Pe.extname(n).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${n}`);let o=Pe.dirname(n);return bl(o),El(n,o),n}async captureToPath(e,t,n){let o=Pe.dirname(Pe.resolve(t));bl(o),El(Pe.resolve(t),o);let i=`/data/local/tmp/devecocli-${cC()}.png`;await this.capture({hdcPath:this.toolProvider.hdcPath,serial:e,localPath:Pe.resolve(t),remotePath:i,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];m(`Executing: ${e.hdcPath} ${t.join(" ")}`);let n=await te(e.hdcPath,t);return n.exitCode===0?Zm(n.stdout):void 0}async tryCreateRemoteScreenshot(e,t){let n=Jm(e,t);m(`Executing: ${e.hdcPath} ${n.join(" ")}`);let o=await te(e.hdcPath,n),i=await this.getRemoteScreenshotSize(e);return{created:i!==void 0&&i>0,output:Km(Ym(o.stdout,o.stderr))}}async createRemoteScreenshot(e){let t="";for(let n of[void 0,"png"]){let o=await this.tryCreateRemoteScreenshot(e,n);if(o.created)return;if(e.display!==void 0&&Xm(o.output))throw new Error(`Screenshot was not created on device: ${e.remotePath}.
|
|
57
|
+
snapshot_display output:
|
|
58
|
+
${o.output}`);o.output&&(t=o.output)}throw new Error(t?`Screenshot was not created on device: ${e.remotePath}.
|
|
59
|
+
snapshot_display output:
|
|
60
|
+
${t}`:`Screenshot was not created on device: ${e.remotePath}.`)}async tryReceiveScreenshot(e,t,n){let o=["-t",e.serial,"file","recv",e.remotePath,n];m(`Executing: ${e.hdcPath} ${o.join(" ")}`);let i=await te(e.hdcPath,o);return i.exitCode!==0&&m(`hdc file recv failed: ${i.stderr||i.stdout||`exit code ${i.exitCode}`}`),dC(t,e.remotePath)}async receiveScreenshotFile(e){let t=He.mkdtempSync(Pe.join(Pe.dirname(e.localPath),".devecocli-screenshot-"));try{let n=await this.tryReceiveScreenshot(e,t,Pe.join(t,Pe.basename(e.remotePath)))??await this.tryReceiveScreenshot(e,t,t)??await this.tryReceiveScreenshot(e,t,Pe.join(t,"screenshot.png"));if(!n)throw new Error(`Screenshot file was not created in ${t}.`);uC(n,e.localPath)}finally{He.rmSync(t,{recursive:!0,force:!0})}}async removeRemoteScreenshot(e){let t=["-t",e.serial,"shell","rm","-f",e.remotePath];m(`Executing: ${e.hdcPath} ${t.join(" ")}`),await te(e.hdcPath,t)}};var Ns={left:"0",right:"1",up:"2",down:"3"};function Le(r,e){let t=Number(r);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Cl(r,e){r!==void 0&&Le(r,e)}function rf(r,e){if(r===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Os(r,e){if(r!==void 0&&r.length===0)throw new Error(`${e} must not be empty`)}function Fo(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 nf(r){if(r!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(r))throw new Error("--window must consist of letters, digits, - or _")}function of(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 Dn(r,e,t,n,o=!0){rf(r,e),Os(t,"--id"),Cl(r,"x"),Cl(e,"y"),nf(n),of(r!==void 0,!!t,!!n,o)}async function gt(r,e){let n=await new lr(r).selectDevice(e);if(!n)throw new Error("No device selected. Use `devecocli device list` to see targets.");return n}async function Rt(r){let e=await k.new(),t=await gt(e,r);return{hdcPath:e.hdcPath,deviceId:t}}async function Tn(r,e,t,n,o,i){if(t!==void 0&&n!==void 0)return{x:t,y:n};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new jt(r,e).listWindows({all:!0}),c=new en(r);return pC(c,e,a,o,i)}async function pC(r,e,t,n,o){if(o!==void 0){let i=t.find(a=>String(a.id)===o);if(i&&i.displayId!==0)throw new w(`Window "${o}" is on display ${i.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,o,!1);return fC(s,n)}return mC(r,e,t,n)}async function mC(r,e,t,n){let o=[...new Set(t.map(a=>a.displayId))],i=await r.dumpFullTreeByDisplays(e,0,o),s=[];for(let{displayId:a,tree:c}of i)for(let l of kn([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 sf(s[0].node,n)}function fC(r,e){let t=kn(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 sf(t[0],e)}function sf(r,e){let t=r.bounds;if(!t)throw new w(`Node "${e}" has no bounds.`,"Node has no bounds.");let[n,o,i,s]=t;return{x:Math.ceil((n+i)/2),y:Math.ceil((o+s)/2)}}async function ct(r,e,t){let n=["-t",e,"shell",...t];m(`Executing: ${r} ${n.join(" ")}`);let o=await te(r,n);if(o.exitCode!==0)throw new Error(o.stderr||o.stdout||`uitest exited with code ${o.exitCode}`);let i=o.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>i.includes(a))&&!i.includes("no error"))throw new Error(o.stdout.trim()||"uitest command failed")}import{deflateSync as hC,inflateSync as gC}from"zlib";import yC from"fs";var af=8,cf=32,vC=.06,wC=.04,Pl=10,Ms=class r{whiteBits=null;blackBits=null;analyzeRgb(e,t,n){if(e<8||t<8||n.length<e*t*3)return null;let o=this.cropChrome(e,t,n),i=this.hashBits(o.width,o.height,o.rgb),s=Math.min(this.hammingDistance(i,this.solidRefBits(255)),this.hammingDistance(i,this.solidRefBits(0)));return{phash:this.bitsToHex(i),hamming:s,isBlank:s<=Pl}}analyzeFile(e){let t;try{t=yC.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 o=r.pngCrcTable(),i=[Buffer.from(`\x89PNG\r
|
|
61
|
+
|
|
62
|
+
`,"binary")],s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=2,i.push(r.pngChunk("IHDR",s,o));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 i.push(r.pngChunk("IDAT",hC(a),o)),i.push(r.pngChunk("IEND",Buffer.alloc(0),o)),Buffer.concat(i)}cropChrome(e,t,n){let o=Math.floor(t*vC),i=Math.floor(t*(1-wC));if(i<=o+8)return{width:e,height:t,rgb:n};let s=i-o,a=new Uint8Array(e*s*3);for(let c=0;c<s;c++){let l=(o+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 o=this.toGray(e,t,n),i=this.resizeGray(o,cf,cf),s=this.dct2(i),a=[];for(let d=0;d<af;d++)a.push(s[d].slice(0,af));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 i=new Uint8Array(12288);for(let s=0;s<4096;s++)i[s*3]=e,i[s*3+1]=t,i[s*3+2]=n;return this.hashBits(64,64,i)}hammingDistance(e,t){let n=Math.min(e.length,t.length),o=Math.abs(e.length-t.length);for(let i=0;i<n;i++)e[i]!==t[i]&&o++;return o}bitsToHex(e){let t=0n;for(let o of e)t=t<<1n|(o?1n:0n);let n=Math.max(1,Math.ceil(e.length/4));return t.toString(16).padStart(n,"0")}toGray(e,t,n){let o=[];for(let i=0;i<t;i++){let s=[];for(let a=0;a<e;a++){let c=(i*e+a)*3;s.push(.299*n[c]+.587*n[c+1]+.114*n[c+2])}o.push(s)}return o}resizeGray(e,t,n){let o=e.length,i=e[0]?.length??0;if(i===t&&o===n)return e;let s=[];for(let a=0;a<n;a++){let c=(a+.5)*o/n-.5,l=Math.max(0,Math.min(o-1,Math.floor(c))),d=Math.max(0,Math.min(o-1,l+1)),g=c-l,v=[];for(let b=0;b<t;b++){let N=(b+.5)*i/t-.5,$=Math.max(0,Math.min(i-1,Math.floor(N))),me=Math.max(0,Math.min(i-1,$+1)),Te=N-$,Ct=e[l][$],up=e[l][me],Oc=e[d][$],Mc=e[d][me];v.push(Ct*(1-Te)*(1-g)+up*Te*(1-g)+Oc*(1-Te)*g+Mc*Te*g)}s.push(v)}return s}stabilizeDct(e){let t=e.flat(),n=Math.abs(t[0]??0),o=Math.max(.001,n*1e-8);return t.map(i=>Math.abs(i)<o?0:i)}median(e){if(e.length===0)return 0;let t=[...e].sort((o,i)=>o-i),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 g=0;g<t;g++)d+=a[g]*Math.cos(Math.PI*(g+.5)*l/t);c[l]=d}return c},o=e.map(n),i=[];for(let a=0;a<t;a++)i.push(n(o.map(c=>c[a])));let s=[];for(let a=0;a<t;a++){let c=[];for(let l=0;l<t;l++)c.push(i[l][a]);s.push(c)}return s}decodePngRgb(e){let t=this.parsePngChunks(e);if(!t)return null;let n;try{n=gC(Buffer.concat(t.idat))}catch{return null}let o=this.pngScanlinesToRgb(n,t.width,t.height,t.colorType);return{width:t.width,height:t.height,rgb:o}}parsePngChunks(e){if(e.length<8||e.subarray(0,8).toString("binary")!==`\x89PNG\r
|
|
63
|
+
|
|
64
|
+
`)return null;let t=8,n=0,o=0,i=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),o=d.readUInt32BE(4),i=d[8],s=d[9];else if(l==="IDAT")a.push(d);else if(l==="IEND")break}return!n||!o||i!==8||s!==2&&s!==6?null:{width:n,height:o,colorType:s,idat:a}}pngScanlinesToRgb(e,t,n,o){let i=o===6?4:3,s=t*i,a=new Uint8Array(t*n*3),c=0,l=new Uint8Array(s),d=new Uint8Array(s);for(let g=0;g<n;g++){let v=e[c++];d.set(e.subarray(c,c+s)),c+=s,this.applyPngFilter(v,d,l,i);for(let b=0;b<t;b++){let N=(g*t+b)*3,$=b*i;a[N]=d[$],a[N+1]=d[$+1],a[N+2]=d[$+2]}l.set(d)}return a}applyPngFilter(e,t,n,o){for(let i=0;i<t.length;i++){let s=i>=o?t[i-o]:0,a=n[i],c=i>=o?n[i-o]:0;e===1?t[i]=t[i]+s&255:e===2?t[i]=t[i]+a&255:e===3?t[i]=t[i]+Math.floor((s+a)/2)&255:e===4&&(t[i]=t[i]+this.paeth(s,a,c)&255)}}paeth(e,t,n){let o=e+t-n,i=Math.abs(o-e),s=Math.abs(o-t),a=Math.abs(o-n);return i<=s&&i<=a?e:s<=a?t:n}static pngChunk(e,t,n){let o=Buffer.concat([Buffer.from(e,"ascii"),t]),i=Buffer.alloc(12+t.length);return i.writeUInt32BE(t.length,0),o.copy(i,4),i.writeUInt32BE(r.pngCrc(o,n),8+t.length),i}static pngCrcTable(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let o=0;o<8;o++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e}static pngCrc(e,t){let n=4294967295;for(let o=0;o<e.length;o++)n=t[(n^e[o])&255]^n>>>8;return(n^4294967295)>>>0}};import $t from"fs";import yt from"path";import{randomUUID as AC}from"crypto";var SC=/^smoke-screenshot-\d+\.png$/,bC=/^smoke-crash-\d+\.log$/,EC=/^run-\d+-\d+-[0-9a-f]{4}$/;function lf(r){return`smoke-screenshot-${r}.png`}function df(r){return`smoke-crash-${r}.log`}function uf(r){return SC.test(r)||bC.test(r)}var jo="RUNNING",Al="ENDED",CC=1440*60*1e3,PC=1440*60*1e3;function pf(r,e,t){return`run-${r}-${e}-${t}`}function mf(r){return EC.test(r)}function ff(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 hf(r,e,t){return r===null?!0:r==="ended"?e?.endedAt===void 0?!0:t.now-e.endedAt>=CC:!e||!Number.isInteger(e.pid)||e.pid<=0||t.now-e.startedAt>=PC?!0:!t.isPidAlive(e.pid)}var IC="smoke";function kC(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}var $o=class{constructor(e,t=kC){this.baseDir=e;this.isPidAlive=t;this.runsRoot=yt.join(e,IC)}baseDir;isPidAlive;runsRoot;static resolveBaseDir(e,t){return t??yt.join(e,".hvigor")}createRun(){let e=yt.join(this.runsRoot,pf(Date.now(),process.pid,AC().slice(0,4)));$t.mkdirSync(e,{recursive:!0});let t={pid:process.pid,startedAt:Date.now()};return $t.writeFileSync(yt.join(e,jo),JSON.stringify(t),"utf8"),e}prune(e,t=Date.now()){this.pruneLegacyFlatArtifacts(),this.pruneEndedRuns(e,t)}finalize(e){try{let t=this.readMarker(e,jo),n={pid:t?.pid??process.pid,startedAt:t?.startedAt??Date.now(),endedAt:Date.now()};$t.writeFileSync(yt.join(e,Al),JSON.stringify(n),"utf8"),$t.rmSync(yt.join(e,jo),{force:!0})}catch(t){m(`Smoke: finalize run failed (${e}): ${t.message}`)}}discard(e){try{$t.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: discard run failed (${e}): ${t.message}`)}}pruneLegacyFlatArtifacts(){let e;try{e=$t.readdirSync(this.baseDir,{withFileTypes:!0})}catch{return}for(let t of e)!t.isFile()||!uf(t.name)||this.removeQuietly(yt.join(this.baseDir,t.name))}pruneEndedRuns(e,t){let n;try{n=$t.readdirSync(this.runsRoot,{withFileTypes:!0})}catch{return}for(let o of n){if(!o.isDirectory()||!mf(o.name))continue;let i=yt.join(this.runsRoot,o.name);if(yt.resolve(i)===yt.resolve(e))continue;let s=this.readMarkerState(i);hf(s.kind,s.marker,{now:t,isPidAlive:this.isPidAlive})&&this.removeQuietly(i)}}readMarkerState(e){let t=this.readMarker(e,Al);if(t!==void 0)return{kind:"ended",marker:t};let n=this.readMarker(e,jo);return n!==void 0?{kind:"running",marker:n}:{kind:null,marker:null}}readMarker(e,t){try{return ff($t.readFileSync(yt.join(e,t),"utf8"))}catch(n){return n.code==="ENOENT"?void 0:null}}removeQuietly(e){try{$t.rmSync(e,{recursive:!0,force:!0})}catch(t){m(`Smoke: prune artifact failed (${e}): ${t.message}`)}}};var gf=1e3;function TC(){let r=process.env.DEVECO_CLI_SMOKE_WAIT_MS;if(r===void 0||r==="")return gf;let e=Number(r);return Number.isFinite(e)&&e>=0?Math.floor(e):gf}var Fs=class{constructor(e,t,n){this.hdc=t;this.projectRoot=n;this.hilog=new lr(e),this.screenshots=new tn(e)}hdc;projectRoot;phash=new Ms;hilog;screenshots;runDir;runStore;async collect(e){this.openRun(e);let t=TC();t>0&&await new Promise(o=>setTimeout(o,t));let n;try{n=await this.hdc.pidofBundle(e.targetDeviceId,e.bundleName)}catch(o){return console.warn(Ho(`Smoke: process check failed (${o.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 $o($o.resolveBaseDir(this.projectRoot,e.screenshotDir)),n=t.createRun();t.prune(n),this.runStore=t,this.runDir=n}artifactPath(e){return DC.join(this.runDir??"",e)}discardEvidence(e){for(let t of[e.screenshotPath,e.crashLogPath])if(t)try{_s.rmSync(t,{force:!0})}catch(n){m(`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(lf(Date.now()));try{await this.screenshots.captureToPath(e.targetDeviceId,t)}catch(o){return this.skipBlank(`screenshot failed (${o.message})`)}if(!_s.existsSync(t)||_s.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(Ho(`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(Ho(`Smoke: crash log query failed (${n.message}).`));return}if(!t?.trim()){console.warn(Ho("Smoke: no crash log found on device."));return}try{let n=this.artifactPath(df(Date.now()));return _s.writeFileSync(n,t,"utf8"),n}catch(n){console.warn(Ho(`Smoke: failed to save crash log (${n.message}).`));return}}};var js=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 ${Pl}, 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 $s=class{inspector;judge=new js;formatter=new Rs;constructor(e,t,n){let o=n??new Ze(e);this.inspector=new Fs(e,o,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 Il(r){await new $s(r.toolProvider,r.projectRoot,r.hdcAdapter).execute(r)}function kl(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 Us(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 o=await r.listDevicesWithName();throw new w("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+o.map(i=>` - ${i.name} (${i.serial})`).join(`
|
|
65
|
+
`),"Multiple devices found.")}let n=await r.getDeviceInfo(t,e);if(!n)throw new Error("No active devices found.");if(!e){let o=await r.getDeviceName(n.serial);console.log(`Auto-selected device: ${o} (${n.serial})`)}return n.serial}function Dl(r,e){if(e&&e.length>0)return e;let t=r.profile.modules.filter(n=>{let o=r.getModuleType(n.name);return o==="entry"||o==="feature"||o==="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>...].
|
|
50
66
|
Available runnable modules:
|
|
51
|
-
`+t.map(
|
|
52
|
-
`),"Specify module error.")}function
|
|
53
|
-
Installing artifacts to device ${e}...`),await
|
|
67
|
+
`+t.map(n=>` - ${n.name}`).join(`
|
|
68
|
+
`),"Specify module error.")}function yf(r,e,t){if(t)return t;let n=e.find(({moduleName:i})=>r.getModuleType(i)==="entry");if(n)return r.getMainAbility(n.moduleName);let o=e.find(({moduleName:i})=>r.getModuleType(i)==="feature");if(o)return r.getMainAbility(o.moduleName)}async function vf(r,e,t,n,o,i){if(i&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
69
|
+
Installing artifacts to device ${e}...`),await r.installApp(e,n),o){console.log(`Launching ${t}/${o}...`);let s=await r.launchApp(e,t,o);console.log(Uo(`
|
|
54
70
|
Application '${t}': ${s}`))}else console.log(`
|
|
55
|
-
Application '${t}' installed successfully (no ability to launch).`)}function
|
|
56
|
-
`+
|
|
57
|
-
${
|
|
71
|
+
Application '${t}' installed successfully (no ability to launch).`)}function LC(r){let e={event:S.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 NC=new RC("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=LC(r),t=Date.now(),n=!0,o=null;try{let i=await MC(r,e);i&&(i.ohpmMemoryMb&&(e.ohpm_install_memory=i.ohpmMemoryMb),i.syncMemoryMb&&(e.hvigor_sync_memory=i.syncMemoryMb),i.buildMemoryMb&&(e.hvigor_build_memory=i.buildMemoryMb))}catch(i){n=!1,o=q(i),console.error(xC(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}});async function OC(r,e,t,n,o){let i=new Sn(e,r.rootDir),s=new Ke(e,r.rootDir),a=new Set,c=new Set;for(let{moduleName:b,targetName:N}of t)for(let $ of r.collectNonHarDependentModuleList(b))a.add(`${$}@${N}`),c.add($);let l=[...a],d=ll(r,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let b of c)Ps.generate(r.rootDir,b,n,e);let v=await Jr(r.rootDir,()=>dl(i,s,n,o,g,r.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
|
|
72
|
+
`+Uo("Build completed successfully.")),v}async function MC(r,e){let t=V.discover(process.cwd());console.warn(Hs("Ensure the project source is trusted before proceeding."));let n=await k.new();if(r.skipBuild||n.assertJava(),e.bundle_name=t.getBundleName(),r.hotreloadApply){await jC(r,t,n);return}if(r.hotreload){await FC(r,t,n);return}if(r.apply){await HC(r,t,n);return}return wf(r,t,n)}async function _C(r,e,t){r.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)});let n=new Ke(e,t.rootDir),o=setInterval(async()=>{await n.isDaemonAlive()||(clearInterval(o),console.log("Daemon stopped (via --hotreload stop). Exiting watch session."),process.exit(0))},3e3);await new Promise(()=>{})}async function FC(r,e,t){if(r.hotreload==="stop"){await Wm(t,e);return}let o=Dl(e,r.module).map(kl),{moduleName:i,targetName:s}=o[0];wl(r.module,i);let a=new Ze(t),c=ue.from(t),l=await Us(c,r.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=r.product||"default";e.validateProduct(g);let v=e.getBundleName(g),b=yf(e,o,r.ability);As.generate(e.rootDir,i,g,t);let N=new Ke(t,e.rootDir);console.log(Uo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await N.ensureDaemonRunning();let $=[`${i}@${g}`];for(let Ct of e.collectNonHarDependentModuleList(i))$.includes(`${Ct}@${g}`)||$.push(`${Ct}@${g}`);console.log(Uo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let me=new In(e.rootDir,t);await me.startWatchSession({moduleSpecs:$,productName:g});let Te=Bm(e,i,s,d,g);await vf(a,l,v,Te,b,!!r.uninstall),console.log(Uo("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(me,t,e)}async function jC(r,e,t){let n=r.hotreloadApply;if(!n)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");if(Bo.basename(n)!==n)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n}`);let o=Dl(e,r.module),{moduleName:i}=kl(o[0]);wl(r.module,i);let s=ue.from(t),a=await Us(s,r.device),c=r.product||"default";e.validateProduct(c);let l=e.getBundleName(c);Um(e,i,n);let d=[`${i}@${c}`],g=await Hm({applyFileName:n,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function $C(r,e,t,n){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of r.collectNonHarDependentModuleList(i)){o.add(r.findArtifactPath(a,s,t,n));for(let c of r.findRemoteHspPaths(a,s,n))o.add(c)}return[...o]}async function wf(r,e,t){let o=Dl(e,r.module).map(kl);for(let{moduleName:$}of o){let me=e.getModuleType($);if(me!=="entry"&&me!=="feature"&&me!=="shared")throw new w(`Module '${$}' '${me}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}let i=new Ze(t),s=ue.from(t),a=await Us(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",g;r.skipBuild||(g=await OC(e,t,o,l,d));let v=$C(e,o,c,l),b=e.getBundleName(l),N=yf(e,o,r.ability);return await vf(i,a,b,v,N,!!r.uninstall),N&&await Il({toolProvider:t,projectRoot:e.rootDir,hdcAdapter:i,targetDeviceId:a,bundleName:b}),g}async function HC(r,e,t){let n=r.apply;if(!n)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Bo.basename(n)!==n)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n}`);let o=Bo.join(e.rootDir,".hvigor",n),i=ue.from(t),s=await Us(i,r.device),a=r.product||"default";e.validateProduct(a);let c=e.getBundleName(a),l=e.profile.modules.find(v=>e.getModuleType(v.name)==="entry")?.name,d=l?e.getMainAbility(l,r.ability):r.ability||"EntryAbility",g=new Cs(t,e.rootDir);try{await g.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d})}catch(v){console.warn(Hs(`[Apply] \u5931\u8D25\uFF1A${v.message}`)),console.warn(Hs("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run...")),await wf(r,e,t);return}console.log(Hs("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002")),await Il({toolProvider:t,projectRoot:e.rootDir,targetDeviceId:s,bundleName:c})}var Sf=NC;import{Command as tP}from"commander";import*as Df from"path";import{green as Af,red as If,cyan as Ll}from"colorette";import{execa as Ol}from"execa";import{spawn as VC}from"child_process";import*as Pf from"fs";import*as Bs from"path";import{yellow as GC}from"colorette";import zC from"proper-lockfile";import*as dr from"fs";import*as bf from"path";import{homedir as UC}from"os";var BC="deveco-cli",Tl,rn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Ef(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":Xc(r))||bf.join(UC(),".local","share",BC);try{return ds(t)}catch(n){throw new rn(n instanceof Error?n.message:String(n))}}async function Cf(){let r=Ef();await dr.promises.mkdir(r,{recursive:!0});let e;try{e=await dr.promises.realpath(r)}catch(n){throw new rn(`DEVECO_CLI_DATA_DIR is not usable: ${n instanceof Error?n.message:String(n)}`)}if(!(await dr.promises.stat(e)).isDirectory())throw new rn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Tl=e,e}function lt(){if(Tl!==void 0)return Tl;let r=Ef();try{if(dr.existsSync(r))return dr.realpathSync(r)}catch{}return r}function Wo(){return"@deveco-test/deveco-cli"}function ur(){return"1.3.3-Test.2"}function Rn(){return"daily"}function xn(){let r=process.env.DEVECO_CLI_DISABLE_UPDATE;return r==="check"||r==="all"?r:"off"}import*as Vo from"fs";import*as Go from"path";var WC={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},Rl=new Map,pr=class r{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=Go.join(e,"cache.json"),this.lockFilePath=Go.join(e,"check.lock")}async writeSuccess(e,t=[],n,o){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:n,checkedAgainstTag:o})}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}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=Rl.get(this.cacheFilePath);if(e)return e;try{let t=Vo.readFileSync(this.cacheFilePath,"utf-8"),n=JSON.parse(t);return Rl.set(this.cacheFilePath,n),n}catch{return{...WC}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await Vo.promises.mkdir(Go.dirname(this.cacheFilePath),{recursive:!0}),await Vo.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Rl.set(this.cacheFilePath,e)}};var zo=class{constructor(e){this.actionCommand=e}actionCommand;cache=new pr(Bs.join(lt(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=ur(),t=Rn(),n=this.cache.getCheckedAgainstVersion(),o=this.cache.getCheckedAgainstTag(),i=o!=null&&o!==t,s=n!=null&&n!==e,a=i?null:this.cache.getLatestVersion();a&&$p(a,e)>0&&(console.log(),console.log(GC(`New version ${a} available, run \`devecocli update\` to upgrade`))),(i||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){m(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}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 qC(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),VC(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{m("Update check lock held by another process, skipping")}}};async function qC(r,e){await Pf.promises.mkdir(Bs.dirname(r),{recursive:!0});let t=await zC.lock(r,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}import*as Ws from"fs";import*as Ln from"path";import{execa as JC}from"execa";import{yellow as YC}from"colorette";function KC(r){return r?r.endsWith(".ts"):!0}function XC(r,e){let t=Ln.join(r,"package.json");try{return JSON.parse(Ws.readFileSync(t,"utf8")).name===e}catch{return!1}}function ZC(r,e){let t;try{t=Ln.dirname(Ws.realpathSync(r))}catch{return null}for(let n=0;n<20&&t&&t!==Ln.dirname(t);n++){if(XC(t,e))return t;t=Ln.dirname(t)}return null}async function QC(){try{m("Executing: npm root -g");let{stdout:r}=await JC("npm",["root","-g"]);return r.trim()||null}catch(r){return m(`[install-check] npm root -g failed: ${r instanceof Error?r.message:String(r)}`),null}}function eP(r,e){return To(r,e)}async function xl(r){if(process.env.DEVECO_CLI_SKIP_INSTALL_CHECK)return;let e=process.argv[1];if(KC(e))return;let t=await QC();if(!t)return;let n=ZC(e,r);if(!n){m("[install-check] running package root not found, skipping");return}eP(n,t)||(console.log(),console.log(YC(`Warning: devecocli is running from
|
|
73
|
+
${n}
|
|
58
74
|
but \`npm\` in PATH installs global packages to
|
|
59
75
|
${t}
|
|
60
76
|
The devecocli binary in PATH does not match the npm that \`devecocli update\` uses.
|
|
61
77
|
The update would land in the wrong place and would not reach the binary you are running.
|
|
62
78
|
Continuing with update \u2014 abort if this is unexpected.
|
|
63
|
-
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 ${
|
|
64
|
-
${
|
|
65
|
-
New version found: ${i} (current: ${e})`)),console.log(
|
|
66
|
-
`+
|
|
67
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let o=t[0];return f(Is(`Using device serial: ${o}`)),o}if(e&&t.includes(e))return f(Is(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let o=this.findDeviceByArg(r,e);if(o)return f(Is(`Using device: ${o.name} (${o.serial})`)),o.serial;let i=this.formatConnectedDeviceList(r);throw new v(`Device '${e}' not found.
|
|
68
|
-
Available devices:
|
|
69
|
-
${i}`,"Device not found.")}if(r.length===1){let o=r[0];return f(Is(`Using device: ${o.name} (${o.serial})`)),o.serial}throw new v("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r),"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,r){f(`Retrieving PID for bundle ${r}`),b.assertBundleNameStrict(r);let o=await se(e,["-t",t,"shell","pidof",r]),i=Yn(o,"Failed to look up PID");if(i)throw i;if(o.exitCode===0&&o.stdout.trim()){let s=o.stdout.trim(),a=s.split(/\s+/)[0]||s;return f(`Found PID for ${r}: ${a}`),a}return f(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){if(f(`Setting hilog buffer size to: ${r}`),!/^\d+[KMG]?$/.test(r))throw new Error(`Invalid hilog buffer size: ${JSON.stringify(r)}. Expected format: <number>[K|M|G], e.g. "4M", "16M"`);let o=await se(e,["-t",t,"shell","hilog","-G",r]),i=Yn(o,"Failed to resize hilog buffer");if(i)throw i;o.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${o.stderr||o.stdout}`)}buildHilogCommand(e,t,r,o){let i=this.buildHilogShellCommand(r,o);return[e,["-t",t,"shell",i]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(b.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(b.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(b.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(b.assertHilogKeyword(e.keyword),r.push("-e",b.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,o,i){let a=await Xp(e,t,{onData:r,onError:o,onClose:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,o,i){let s=1+pl.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,o,i),a.exitCode===0||gr(a.stderr)!=="transient"||c>=s-1)return a;f(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${pl[c]}ms`),await _E(pl[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},o=>{f(`Callback triggered when an error occurs during ${r}: ${o.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,o){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let i={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,i,o);f(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=Yn(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=b.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=b.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,o){let[i,s]=this.buildHilogCommand(e,t,r,o);f(`Ready to run hilog command: ${i} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(i,s,"a single hilog streaming read"),c=Yn(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=b.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=b.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,o){try{await this.printTailSnapshotIfNeeded(e,t,r,o)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[i,s]=this.buildHilogCommand(e,t,r,o);f(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${i} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(i,s,this.createFollowLineHandler(),l=>{f(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=Yn(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 r=this.toolProvider.hdcPath,o=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!o)throw new v(`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(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,o||""):await this.getHilogOnce(r,e,t,o||"")}async getCrashLog(e,t){f(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,o=await this.listCrashLogs(r,e,t);if(o.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...o].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let o=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];f(`Running command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log list streaming read"),s=Yn(i,"Failed to list crash logs");if(s)throw s;if(i.exitCode!==0)throw new Error(`Failed to list crash logs: ${i.stderr||i.stdout}`);return f(`Crash logs list output:
|
|
70
|
-
${i.stdout}`),this.parseCrashLogFilenames(i.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
71
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return b.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){f(`Fetching latest crash log file: ${r}`);let o=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];f(`Executing command: ${e} ${o.join(" ")}`);let i=await this.runHilogStreamingCollect(e,o,"a crash log streaming read"),s=Yn(i,"Failed to fetch crash log content");if(s)throw s;return i.exitCode!==0&&i.stderr&&console.error(`Warning: Failed to fetch crash logs: ${i.stderr}`),i.stdout+i.stderr}};async function mt(n,e){let r=await new Pr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}import{execa as As}from"execa";function Ce(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}function Rm(n){let e=n.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as FE}from"child_process";var jE=2500;function $E(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function HE(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,jE);n.once("error",d=>c(d.message)),$E(n,l,s,a,c,i)}function xm(n,e,t){return f(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=FE(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),HE(s,i,r,o)})}import*as Ir from"path";function UE(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function BE(n){let e=n.instancePath?.trim();if(e)return Ir.dirname(Ir.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Ir.dirname(Ir.normalize(t)).replace(/\\/g,"/"):""}function WE(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Lm(n,e){return e?[...n,"-bootmode",e]:n}function VE(n,e,t){let r=[Lm(["-start",n],t)],o=BE(e);if(o)for(let i of WE(e.imageRoot))r.push(Lm(["-hvd",n,"-path",o,...i],t));return UE(r)}async function Nm(n,e,t,r){let o=new Error("No start strategy ran"),i=VE(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}function GE(n){let e=n.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 ml(n){return(await ae.withHdcPath(n).listDevices()).map(t=>t.serial).filter(It)}async function fl(n){let e=await ml(n);return e.length===0?[]:(await Promise.all(e.map(r=>ms(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Om(n,e){return(await fl(n)).includes(e)}async function Mm(n,e){let t=await ae.withHdcPath(n).listDevicesWithName(),r=e.normalize("NFKC").replace(/\s+/g," ").trim(),o=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===r);if(!o||!It(o.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let i=["-t",o.serial,"shell","hidumper","-s","3302","-a","-i"];f(`Executing: ${n} ${i.join(" ")}`);let s=await se(n,i);if(s.exitCode===0){let a=GE(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as Dr from"path";import{existsSync as qE,statSync as zE}from"fs";function Ar(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function JE(n){let e=Ar(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function YE(n){return Ar(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function KE(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Dr.dirname(Dr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=b.ensurePathWithinRoot(t,Dr.join(t,r.name));qE(o)&&zE(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function XE(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=YE(t),o=Ar(t,["deviceType","DeviceType","devicetype"]),i=Ar(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:JE(t),path:Ar(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Ar(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function ZE(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function _m(n){let t=XE(n)??ZE(n);return KE(t),t}function hl(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function QE(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function eC(n){let e=hl(n,["osVersion","OsVersion","OSVersion"]),t=hl(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=hl(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Fm(n,e=()=>!0){let t=n.trim();if(!t)return[];try{let r=JSON.parse(t);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(!i||typeof i!="object")continue;let s=i;if(!e(s))continue;let a=eC(s);a&&o.push(a)}return o}catch{return[]}}function jm(n){return Fm(n)}function gl(n){return Fm(n,QE)}function $m(n){let t=gl(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Hm=/no images are available/i,tC=/Scenario simulation failed\s*[::]/i,nC="7.0.0";function Mt(n){return n.normalize("NFKC").trim().toLowerCase()}function rC(n){let e=n.message||"";return Hm.test(e)}function oC(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Fo(n,e){return`${n} ${e.join(" ")}`.trim()}function iC(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var kr=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return f(`Executing: ${Fo(this.emulatorPath,e)}`),As(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return xm(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return _m(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(Ce(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=Ce(e),o=t.find(a=>Ce(a.name)===r);if(!o)throw new v(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";let s=await Nm(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new v(`Unable to start emulator "${e}". All methods failed.
|
|
79
|
+
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 Ml=new tP("update").description("Update deveco-cli to latest");Ml.command("_check",{hidden:!0}).action(async()=>{let r=Date.now(),e=new pr(Df.join(lt(),"update"));try{let t=Rn(),n=Wo();m(`Executing: npm view ${n}@${t} --json`);let{stdout:o}=await Ol("npm",["view",`${n}@${t}`,"--json"]),i=JSON.parse(o),s=typeof i.version=="string"?i.version.trim():null,a=Array.isArray(i.blockedVersions)?i.blockedVersions:[];await e.writeSuccess(s,a,ur(),t),await kf(r,!0,null)}catch(t){await e.writeError(t instanceof Error?t.message:String(t));let n=t,o=n.code??n.name??"UnknownError";await kf(r,!1,o)}});var rP={event:S.CommandExecuted,args:["update"]},nP={event:S.CommandExecuted,args:["update","_check"]};async function Nl(r,e,t){let n={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(rP,n).catch(()=>{})}async function kf(r,e,t){let n={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(nP,n).catch(()=>{})}Ml.action(async()=>{if(xn()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");await xl(Wo());let r=Date.now(),e=ur(),t=Rn();console.log(Ll("Checking for updates..."));let n=Wo();try{let{stdout:o}=await Ol("npm",["view",n,`dist-tags.${t}`]),i=o.trim();if(!i||i===e){console.log(Af(`
|
|
80
|
+
${n} is already up to date (v${e}, tag: ${t})`)),await Nl(r,!0,null);return}console.log(Ll(`
|
|
81
|
+
New version found: ${i} (current: ${e})`)),console.log(Ll(`Updating ${n}...`)),await Ol("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
|
|
82
|
+
`+Af(`${n} updated successfully to version ${i}.`)),await Nl(r,!0,null)}catch(o){let i=o,s=i.code??i.name??"UnknownError";console.error(If(`Failed to update ${n}`)),i.message&&console.error(If(i.message)),await Nl(r,!1,s),process.exit(1)}});var Tf=Ml;import{Command as LP,Option as Vf}from"commander";import{execa as Vs}from"execa";function Ae(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}function Rf(r){let e=r.normalize("NFKC").match(/\((\d+)(?:\.\d+)*\)/)?.[1];return e!==void 0&&Number(e)>=26}import{spawn as oP}from"child_process";var iP=2500;function sP(r,e,t,n,o,i){r.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?n():o(a||`Emulator process exited with code ${s}`)})}function aP(r,e,t,n){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),r.removeAllListeners(),r.stderr?.removeAllListeners(),r.stderr?.destroy(),r.unref(),t())},c=d=>{if(!o){o=!0,clearTimeout(l),r.removeAllListeners(),r.stderr?.removeAllListeners();try{r.kill()}catch{}n(new Error(d))}},l=setTimeout(a,iP);r.once("error",d=>c(d.message)),sP(r,l,s,a,c,i)}function xf(r,e,t){return m(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,o)=>{let i=[],s=oP(r,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),aP(s,i,n,o)})}import*as Nn from"path";function cP(r){let e=new Set,t=[];for(let n of r){let o=JSON.stringify(n);e.has(o)||(e.add(o),t.push(n))}return t}function lP(r){let e=r.instancePath?.trim();if(e)return Nn.dirname(Nn.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?Nn.dirname(Nn.normalize(t)).replace(/\\/g,"/"):""}function dP(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function Lf(r,e){return e?[...r,"-bootmode",e]:r}function uP(r,e,t){let n=[Lf(["-start",r],t)],o=lP(e);if(o)for(let i of dP(e.imageRoot))n.push(Lf(["-hvd",r,"-path",o,...i],t));return cP(n)}async function Nf(r,e,t,n){let o=new Error("No start strategy ran"),i=uP(r,e,n);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}function pP(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 _l(r){return(await ue.withHdcPath(r).listDevices()).map(t=>t.serial).filter(Dt)}async function Fl(r){let e=await _l(r);return e.length===0?[]:(await Promise.all(e.map(n=>Es(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Of(r,e){return(await Fl(r)).includes(e)}async function Mf(r,e){let t=await ue.withHdcPath(r).listDevicesWithName(),n=e.normalize("NFKC").replace(/\s+/g," ").trim(),o=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===n);if(!o||!Dt(o.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let i=["-t",o.serial,"shell","hidumper","-s","3302","-a","-i"];m(`Executing: ${r} ${i.join(" ")}`);let s=await te(r,i);if(s.exitCode===0){let a=pP(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as Mn from"path";import{existsSync as mP,statSync as fP}from"fs";function On(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function hP(r){let e=On(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 o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return n.trim()}return""}function gP(r){return On(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function yP(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Mn.dirname(Mn.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let o=E.ensurePathWithinRoot(t,Mn.join(t,n.name));mP(o)&&fP(o).isDirectory()&&(n.instancePath=o.replace(/\\/g,"/"))}}function vP(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=gP(t),o=On(t,["deviceType","DeviceType","devicetype"]),i=On(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:hP(t),path:On(t,["path","Path","hvdPath","hvd_path"]),imageRoot:On(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function wP(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,o;for(;(o=t.exec(r))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=i.toLowerCase();a==="isrunning"?n.isRunning=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 _f(r){let t=vP(r)??wP(r);return yP(t),t}function jl(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function SP(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function bP(r){let e=jl(r,["osVersion","OsVersion","OSVersion"]),t=jl(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=jl(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Ff(r,e=()=>!0){let t=r.trim();if(!t)return[];try{let n=JSON.parse(t);if(!Array.isArray(n))return[];let o=[];for(let i of n){if(!i||typeof i!="object")continue;let s=i;if(!e(s))continue;let a=bP(s);a&&o.push(a)}return o}catch{return[]}}function jf(r){return Ff(r)}function $l(r){return Ff(r,SP)}function $f(r){let t=$l(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var Hf=/no images are available/i,EP=/Scenario simulation failed\s*[::]/i,CP="7.0.0";function Ht(r){return r.normalize("NFKC").trim().toLowerCase()}function PP(r){let e=r.message||"";return Hf.test(e)}function AP(r){return r.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function qo(r,e){return`${r} ${e.join(" ")}`.trim()}function IP(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 _n=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 m(`Executing: ${qo(this.emulatorPath,e)}`),Vs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return xf(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return _f(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set(Ae(n.name),n.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),n=Ae(e),o=t.find(a=>Ae(a.name)===n);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";let s=await Nf(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new w(`Unable to start emulator "${e}". All methods failed.
|
|
72
83
|
Last error: ${s.lastError.message||"unknown"}`,`Unable to start emulator. All methods failed.
|
|
73
|
-
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:
|
|
74
|
-
`).trim(),a=
|
|
75
|
-
`:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}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(
|
|
76
|
-
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(i!==0||a||c)throw new Error(s||`emulator exited with code ${i===null?"null":i}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e,t){let
|
|
77
|
-
`)}),!await this.waitForEmulatorPresenceByList(t))throw new
|
|
78
|
-
The device may be running.`,"Failed to delete device, The device may be running.");return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as
|
|
79
|
-
`)}async function
|
|
80
|
-
`),"Multiple devices connected.")}async function
|
|
84
|
+
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(o=>o.name===e)?.isRunning===!0?!0:Of(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),n=Ae(e),o=t.find(a=>Ae(a.name)===n);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;return await this.isAlreadyRunning(i,o)?(await this.executeEmulator(["-stop",i]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let o=(await this.listEmulators()).find(s=>s.name===e);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(o.name,o))throw new w(`Emulator "${e}" is not running.`,"Emulator instance is not running.");if(t.type==="battery"&&!await Mf(this.hdcPath,o.name)&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let i=this.buildControlArgs(o.name,t);m(`[EmulatorManager] control ${IP(t)} -> ${qo(this.emulatorPath,i)}`),await this.runEmulatorChecked(i,{extraReject:t.type==="folded-state"?[EP]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(r.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${qo(this.emulatorPath,t)}`);let{stdout:n,stderr:o,exitCode:i}=await Vs(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[n,o].filter(Boolean).join(`
|
|
85
|
+
`).trim(),a=AP(s);if(i!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(k.compareVersion(a,CP)<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){m(`Executing: ${qo(this.emulatorPath,e)}`);let{exitCode:t}=await Vs(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=Ht(e.deviceType),o=Ht(e.osVersion);return jf(t).some(i=>Ht(i.deviceType)===n&&Ht(i.osVersion)===o)}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(i){if(!PP(i))throw i;n=i}(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 listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return $f(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,n){try{for(let o of t)await this.runUninstallImageChecked(e.deviceType,o)}catch(o){let i=n!==void 0?`Primary uninstall failed: ${n.message}
|
|
86
|
+
`:"";throw new Error(`${i}Fallback uninstall failed: ${o.message}`,{cause:o})}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=$l(t),o=Ht(e.deviceType),i=Ht(e.osVersion);return n.filter(s=>Ht(s.deviceType)===o&&(Ht(s.osVersion)===i||Ht(s.softwareVersion)===i))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Hf]})}async runEmulatorChecked(e,t){m(`Executing: ${qo(this.emulatorPath,e)}`);let{stdout:n,stderr:o,exitCode:i}=await Vs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[n,o].filter(Boolean).join(`
|
|
87
|
+
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(i!==0||a||c)throw new Error(s||`emulator exited with code ${i===null?"null":i}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e,t){let n=await this.listEmulators(),o=Ae(e),i=n.find(s=>Ae(s.name)===o);if(i)if(t)await this.deleteVirtualDevice(i.name);else throw new w(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`,"Emulator already exists.");return o}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),n=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(Rf(e.osVersion)&&n.push("-hotBoot","true"),await this.runEmulatorChecked(n,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:i=>i.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
88
|
+
`)}),!await this.waitForEmulatorPresenceByList(t))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=1e4,n=500){let o=Date.now()+t;for(;Date.now()<o;){if((await this.listEmulators()).some(a=>Ae(a.name)===e))return!0;await new Promise(a=>setTimeout(a,n))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),n=Ae(e),o=t.find(s=>Ae(s.name)===n);if(!o)throw new w(`Emulator "${e}" not found.`,"Emulator not found.");let i=o.name;if(o.isRunning===!0||await this.isAlreadyRunning(i,o))throw new w(`Failed to delete device: ${i}
|
|
89
|
+
The device may be running.`,"Failed to delete device, The device may be running.");return await this.runEmulatorChecked(["-delete",i,"-force"],{printOutputOnSuccess:!1}),i}};import{red as NP,yellow as OP,gray as MP}from"colorette";import Gf from"ora";import{green as kP}from"colorette";var DP=[[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]],TP=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],RP=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Uf(r,e){for(let[t,n]of e)if(r>=t&&r<=n)return!0;return!1}function Hl(r){let e=r.replace(RP,""),t=0,n=0;for(;n<e.length;){let o=e.codePointAt(n);if(o===void 0)break;Uf(o,TP)||(Uf(o,DP)?t+=2:t+=1),n+=o>65535?2:1}return t}function Bf(r,e){let t=Hl(r);return r+" ".repeat(Math.max(0,e-t))}function xP(r,e){return r.map((t,n)=>{let o=Hl(t);for(let i of e){let s=i.cells[n]??"";o=Math.max(o,Hl(s))}return o})}function Ut(r,e){let t=xP(r,e),n=[];n.push(r.map((o,i)=>Bf(o,t[i])).join(" ")),n.push(t.map(o=>"-".repeat(o)).join(" "));for(let o of e){let i=o.cells.map((s,a)=>Bf(s??"",t[a])).join(" ").trimEnd();n.push(o.highlight?kP(i):i)}return n.join(`
|
|
90
|
+
`)}async function Jo(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=q(i),console.error(NP(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i)}}function _P(r,e){if(e.size!==0)for(let t of r){if(!t.isEmulator||!t.name)continue;let n=e.get(Ae(t.name));n&&(t.deviceType=n)}}var FP=["Name","Serial","Kind","Device Type"];function jP(r){return{cells:[r.name??r.serial,r.serial,r.isEmulator?"emulator":"device",r.deviceType??"-"],highlight:!0}}function zf(r,e){return r.isEmulator!==e.isEmulator?r.isEmulator?1:-1:(r.name??r.serial).localeCompare(e.name??e.serial)}function $P(){console.log(OP(" No active devices.")),console.log(MP(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function HP(r){let t=[...r].sort(zf).map(jP);console.log(Ut(FP,t))}function UP(r){return{name:r.name??r.serial,serial:r.serial,kind:r.isEmulator?"emulator":"device",deviceType:r.deviceType}}function BP(r){let e=[...r].sort(zf);console.log(JSON.stringify(e.map(UP),null,2))}async function WP(r,e){if(!r.some(o=>o.isEmulator)||!e.emulatorPath)return;let n=await _n.from(e).getDeviceTypeByName();_P(r,n)}async function Wf(r,e,t,n="table"){try{let o=await r.getConnectedEntries();if(await WP(o,e),t?.stop(),n==="json"){BP(o);return}o.length===0?$P():HP(o)}catch(o){throw new w(`Failed to list devices: ${o.message}`,"Failed to list devices.")}finally{t?.stop()}}async function VP(r,e){let t=await r.listDevices();if(t.length<2)return;let n=["Multiple devices connected. Specify a device with:"];for(let o of t){let i=await r.getDeviceName(o.serial);n.push(` ${e} -t ${o.serial} # ${i}`)}throw new w(n.join(`
|
|
91
|
+
`),"Multiple devices connected.")}async function GP(r,e,t="table"){e||await VP(r,"devecocli device view");let n=await r.listDevices(),o=await r.getDeviceInfo(n,e);if(!o){if(t==="json"){console.error("No connected device found."),process.exitCode=1;return}throw new w("No connected device found.")}let i=await r.getDeviceDetail(o.serial),s=await r.getDeviceName(o.serial);if(t==="json"){let a={name:s,serial:o.serial,kind:Dt(o.serial)?"emulator":"device",deviceType:i.deviceType,osVersion:i.osVersion};console.log(JSON.stringify(a,null,2));return}console.log(` Serial: ${o.serial}`),console.log(` Device Name: ${s}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}async function qf(r,e,t,n,o){let i=await gt(r,o),s=new Ze(r),a=e==="send",c=Gf({text:a?`Sending ${t} to ${n} on ${i}...`:`Receiving ${t} from ${i} to ${n}...`,color:"cyan"}).start();try{await s.transferFile(i,e,t,n),c.stop(),console.log(`${a?"Sent to device":"Received from device"} (${i}): ${t} -> ${n}`)}catch(l){c.stop();let d=a?"Send":"Recv";throw new w(`File ${d} failed: ${l.message}`,`File ${d} failed.`)}}async function zP(r,e,t,n){let o=await gt(r,n),i=new Ze(r);try{await i.runSqlite3(o,e,t)}catch(s){throw new w(`sqlite3 failed: ${s.message}`,"sqlite3 failed.")}}async function Yo(){try{let r=await k.new();return{manager:ue.from(r),toolProvider:r}}catch(r){throw new w(`Failed to initialize device manager: ${r.message}`,"Failed to initialize device manager.")}}var Ko=new LP("device").description("Manage connected devices");Ko.command("list").description("List all connected devices").addOption(new Vf("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["device","list",...r.format==="json"?["--format","json"]:[]]};await Jo(e,async()=>{let{manager:t,toolProvider:n}=await Yo();if(r.format==="json"){await Wf(t,n,void 0,"json");return}let o=Gf({text:"Querying connected devices\u2026",color:"cyan"}).start();await Wf(t,n,o,"table")})});Ko.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").addOption(new Vf("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["device","view",...r.target?["--target"]:[],...r.format==="json"?["--format","json"]:[]]};await Jo(e,async()=>{let{manager:t}=await Yo();await GP(t,r.target,r.format)})});var Jf=Ko.command("file").description("Transfer files between the host and a connected device");Jf.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,o={event:S.CommandExecuted,args:["device","file","send",...n?["--device"]:[]]};await Jo(o,async()=>{let{toolProvider:i}=await Yo();await qf(i,"send",r,e,n)})});Jf.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,o={event:S.CommandExecuted,args:["device","file","recv",...n?["--device"]:[]]};await Jo(o,async()=>{let{toolProvider:i}=await Yo();await qf(i,"recv",r,e,n)})});Ko.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:S.CommandExecuted,args:["device","sqlite3",r,...t.device?["--device"]:[]]};await Jo(n,async()=>{let{toolProvider:o}=await Yo();await zP(o,r,e,t.device)})});var Yf=Ko;import{Argument as Jl,Command as Yl,Option as $n}from"commander";import{green as Qo,cyan as jn,red as qs,yellow as xt,gray as ql}from"colorette";import cA from"ora";import qP from"readline/promises";import{execa as Xf}from"execa";import*as mr from"fs/promises";import*as Bl from"os";import*as nn from"path";var Ul=`1/4:\r
|
|
81
92
|
---------------------------------------\r
|
|
82
93
|
Statement About HarmonyOS and Privacy\r
|
|
83
94
|
\r
|
|
@@ -1247,13 +1258,13 @@ Part I: Chinese mainland.\r
|
|
|
1247
1258
|
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
|
|
1248
1259
|
\r
|
|
1249
1260
|
Part III: Other countries and regions.\r
|
|
1250
|
-
---------------------------------------\r`;var
|
|
1251
|
-
`),
|
|
1252
|
-
`)}function
|
|
1253
|
-
${t}.`);return
|
|
1254
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1261
|
+
---------------------------------------\r`;var JP=new Set,Gs=new Map,Wl="HarmonyOS_Software_Service_Agreement",Zf=["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(`
|
|
1262
|
+
`),Qf=Zf,Vl="HarmonyOS_SDK_Agreement";function eh(r,e){return`${r}\0${e}`}function th(){JP.clear(),Gs.clear()}var YP=Zf,Bt=class extends Error{constructor(e=YP){super(e),this.name="EmulatorLicenseBlockedError"}};function rh(r,e){return[r??"",e??""].join(`
|
|
1263
|
+
`)}function nh(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 KP(r){return`Emulator${r.trim()}`}function oh(r){let e=KP(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 nn.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return nn.join(Bl.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||nn.join(Bl.homedir(),".cache");return nn.join(t,"Huawei",e,".emu_config")}async function XP(r,e,t){let n=eh(r,e),o=Gs.get(n);if(o!==void 0)return o;let i=await Xf(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=rh(i.stdout,i.stderr).trim();if(i.exitCode!==0||!s)throw new Bt(t);return Gs.set(n,s),s}function ZP(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function QP(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,o]of Object.entries(e))t[n]={value:typeof o=="string"?o:String(o),delimiter:"json"};return t}}catch{return}}function eA(r){let e=r.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let n=e.indexOf(t);if(n<=0)continue;let o=e.slice(0,n).trim();if(!o||t===":"&&o.includes("//"))continue;let i=ZP(e.slice(n+1).trim());return{key:o,entry:{value:i,delimiter:t}}}}function tA(r){let e={};for(let t of r.split(/\r?\n/)){let n=eA(t);n&&(e[n.key]=n.entry)}return e}function rA(r){let e=r.trim();if(!e)return{};let t=QP(e);return t||tA(r)}function nA(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function ih(r,e,t,n){let o=await XP(r,e,n),i=nh(o);if(!i)throw new Bt(n);let s=oh(i),a;try{a=await mr.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new Bt(n):d}let l=rA(a)[t];if(!l)throw new Bt(n);if(l.delimiter==="=")throw new Bt(n);if(!nA(l.value))throw new Bt(n)}async function Gl(r,e){await ih(r,e,Wl,Qf)}async function zl(r,e){await ih(r,e,Vl,Qf)}async function oA(r,e){let t=await Xf(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=rh(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 o=eh(r,e);return Gs.set(o,n),n}async function sh(r,e){let t=await oA(r,e),n=nh(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1264
|
+
${t}.`);return oh(n)}function Kf(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function iA(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[Wl]="agree",n[Vl]="agree",await mr.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
1265
|
+
`,"utf8"),!0}catch{}return!1}async function sA(r,e){let t=Wl,n=Vl,o=[{k:t,re:new RegExp(`^\\s*${Kf(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${Kf(n)}\\s*[:=]`)}],i=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of i){let l=!1;for(let{k:d,re:g}of o)if(g.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 mr.writeFile(r,s.join(`
|
|
1255
1266
|
`)+(s.length>0?`
|
|
1256
|
-
`:""),"utf8")}async function
|
|
1267
|
+
`:""),"utf8")}async function ah(r){await mr.mkdir(nn.dirname(r),{recursive:!0});let e="";try{e=await mr.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await iA(r,e,t)||await sA(r,e)}async function ch(r,e){return console.log(Ul),0}var aA="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function lh(r,e){try{return await Gl(r,e),await zl(r,e),!0}catch(t){if(t instanceof Bt)return!1;throw t}}async function dh(r,e){if(await lh(r,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(Ul),!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=qP.createInterface({input:process.stdin,output:process.stdout}),o;try{o=await n.question(aA)}finally{n.close()}let i=o.trim().toLowerCase();if(i!=="y"&&i!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await sh(r,e);await ah(s),th()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function uh(r,e){if(await lh(r,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await sh(r,e);await ah(t),th()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}async function dt(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=q(i),console.error(qs(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i)}}var lA=["ohos.qemu.hvd.name","const.product.name","const.product.model"],ph=["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"],dA=`
|
|
1257
1268
|
Folded state scene mappings:
|
|
1258
1269
|
foldableFold (3):
|
|
1259
1270
|
open Fully expanded state
|
|
@@ -1276,41 +1287,41 @@ Folded state scene mappings:
|
|
|
1276
1287
|
left-half-folded-right-folded
|
|
1277
1288
|
left-expanded-right-half-folded
|
|
1278
1289
|
left-half-folded-right-half-folded
|
|
1279
|
-
`,
|
|
1280
|
-
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function
|
|
1281
|
-
${
|
|
1282
|
-
${
|
|
1283
|
-
${
|
|
1284
|
-
`)}});Ef.action(async(n,e)=>{let t={event:S.CommandExecuted,args:["emulator","create","--device-type","--os-version",...e.force?["--force"]:[]]};await ot(t,async()=>{YC(n),KC(e.osVersion);let{manager:r}=await it(),o=await r.listDownloadedImageOsVersions();XC(e.osVersion,o),console.log(Rr(`Creating emulator "${n}"...`)),await r.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Wo(`Emulator "${n}" created successfully.`))})});pe.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let e={event:S.CommandExecuted,args:["emulator","delete"]};await ot(e,async()=>{let{manager:t}=await it();console.log(Rr(`Deleting emulator "${n}"...`));let r=await t.deleteVirtualDevice(n);console.log(Wo(`Emulator "${r}" deleted successfully.`))})});var Cf=pe;import{Command as WP}from"commander";import{red as Nl,cyan as kt}from"colorette";import*as Gf from"readline";import*as Wf from"crypto";import*as Pf from"http";import*as If from"crypto";import{URL as EP}from"url";var Ns=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,o){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=o}async start(){return new Promise((e,t)=>{let r=Pf.createServer((o,i)=>{this.handleRequest(o,i)});r.keepAliveTimeout=1,r.on("error",o=>{t(new Error("Failed to start local auth server",{cause:o}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let o=r.address();this.port=o.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(o)},this.rejectCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(o)},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 i=new EP(e.url??"",`http://${r}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.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 o="",i=0,s=65536;e.on("data",a=>{if(i+=a.length,i>s){e.destroy(new Error("Request body too large"));return}o+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,o)})}handleCallbackRequest(e,t,r,o){try{let i=this.parseParams(r,o),s=i.get("code"),a=i.get("tempToken"),c=i.get("siteId"),l=i.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(i){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(i)}}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&&If.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 Fe from"fs";import*as ln from"path";import{homedir as TP}from"os";var $t={};Lv($t,{LocalCrypto:()=>$t,decryptForLocalStorage:()=>AP,decryptForLocalStorageFromDirectory:()=>DP,encryptForLocalStorage:()=>IP,isEncryptedBlob:()=>kP});import*as ee from"fs";import*as Re from"path";import*as _e from"crypto";import*as Df from"os";import{homedir as kf}from"os";var Te=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Vo=Fn.ALGORITHM,Tf=Fn.IV_LENGTH,Go=Fn.KEY_LENGTH,qo=Fn.KEY_LENGTH,Xn=Fn.KEK_VERSIONS,Os=process.env.DEVECO_CLI_DATA_DIR||Re.join(kf(),be.CONFIG_DIR_NAME,be.APP_NAME),Ms=Re.join(kf(),".local","share",be.APP_NAME,"keys"),Lr=Re.join(Os,be.KEY_FILE_NAME);function Af(n){return Df.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 kl(n){return Re.join(Ms,`${n}.bin`)}function Rf(){if(!ee.existsSync(Os))try{ee.mkdirSync(Os,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Te(Af(Os)):n}if(!ee.existsSync(Ms))try{ee.mkdirSync(Ms,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new Te(Af(Re.dirname(Ms))):n}}function xf(){Rf();for(let n of Xn){let e=kl(n);ee.existsSync(e)||ee.writeFileSync(e,_e.randomBytes(Go),{mode:384})}}function Lf(n){if(!Xn.includes(n))throw new Error(`Invalid kekId: ${n}`);xf();let e=kl(n),t=ee.readFileSync(e);if(t.length===Go)return t;let r=_e.randomBytes(Go);return ee.writeFileSync(e,r,{mode:384}),r}function Tl(n,e){let t=_e.randomBytes(Tf),r=Lf(e),o=_e.createCipheriv(Vo,r,t),i=Buffer.concat([o.update(n),o.final()]),s=o.getAuthTag();return{version:1,algorithm:Vo,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Nf(n,e){return Of(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Of(n,e,t,r){let o=_e.createDecipheriv(Vo,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([o.update(n),o.final()])}function Mf(n,e){return Of(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function CP(){if(xf(),ee.existsSync(Lr))return;let n=_e.randomBytes(qo),e=Tl(n,Xn[0]);ee.writeFileSync(Lr,JSON.stringify(e,null,2),{mode:384})}function _f(){CP();let n=JSON.parse(ee.readFileSync(Lr,"utf8")),e=Nf(n,Lf(n.kekId));if(e.length===qo)return e;let t=_e.randomBytes(qo),r=Tl(t,Xn[0]);return ee.writeFileSync(Lr,JSON.stringify(r,null,2),{mode:384}),t}function PP(){Rf();for(let t of Xn){let r=kl(t);ee.existsSync(r)||ee.writeFileSync(r,_e.randomBytes(Go),{mode:384})}if(ee.existsSync(Lr))return;let n=_e.randomBytes(qo),e=Tl(n,Xn[0]);ee.writeFileSync(Lr,JSON.stringify(e,null,2),{mode:384})}function IP(n){let e=_f(),t=_e.randomBytes(Tf),r=_e.createCipheriv(Vo,e,t),o=Buffer.concat([r.update(n,"utf8"),r.final()]),i=r.getAuthTag();return{version:1,algorithm:Vo,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function AP(n){try{return Mf(n,_f())}catch{throw PP(),new Error("Failed to decrypt local ciphertext")}}function DP(n,e){let t=Re.join(e,be.KEY_FILE_NAME),r=JSON.parse(ee.readFileSync(t,"utf8"));if(!Xn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let o=Re.join(e,"keys",`${r.kekId}.bin`),i=Re.resolve(o),s=Re.resolve(Re.join(e,"keys"));if(!i.startsWith(s+Re.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=ee.readFileSync(i);if(a.length!==Go)throw new Error("Invalid external root key");let c=Nf(r,a);if(c.length!==qo)throw new Error("Invalid external data encryption key");return Mf(n,c)}function kP(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===be.AUTH_SOURCE_DEVECO_CODE}var _s=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||ln.join(TP(),be.CONFIG_DIR_NAME,be.APP_NAME);return ln.join(e,be.TOKEN_FILE_NAME)}ensureConfigDir(){let e=ln.dirname(this.getLocalTokenFilePath());Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=$t.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Fe.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=ln.resolve(e);try{let r=ln.join(t,be.TOKEN_FILE_NAME);if(!Fe.existsSync(r))return null;let o=JSON.parse(Fe.readFileSync(r,"utf8"));return $t.isEncryptedBlob(o)?$t.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Fe.existsSync(e))return null;let t=JSON.parse(Fe.readFileSync(e,"utf8"));return $t.isEncryptedBlob(t)?$t.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(je()){f("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Fe.existsSync(e)&&Fe.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Ht=new _s;import{spawn as RP}from"child_process";function xP(n){try{let e=new URL(n);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||n.includes('"'))}catch{return!1}}function LP(n){return n.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function Ff(n){if(!xP(n))throw new Error(`Invalid URL: ${JSON.stringify(n)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',LP(n)];break;case"darwin":e="open",t=[n];break;default:e="xdg-open",t=[n];break}let r=RP(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((o,i)=>{r.on("error",s=>{i(new Error("Failed to open browser",{cause:s}))}),r.on("close",s=>{s===0?o():i(new Error(`Browser process exited with code ${s}`))})})}import NP from"axios";import{getProxyForUrl as OP}from"proxy-from-env";function MP(n){let e=new URL(n);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 Rl=class{client;constructor(){let e={timeout:ho.HTTP_TIMEOUT_MS,headers:{"User-Agent":ji.USER_AGENT,"accept-language":ji.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=NP.create(e),this.client.interceptors.request.use(t=>{let r=OP(t.url??"");return t.proxy=r?MP(r):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
|
|
1285
|
-
${
|
|
1286
|
-
`)}function GP(){return new Promise(n=>{let e=Gf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var zo=new WP("auth").description("Authentication commands (login, logout, status, team)");zo.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(je()){console.log(Nl("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let n={event:S.CommandExecuted,args:["auth","login"]};await Hs(n,async()=>{let e=await xe.getUserInfo();if(e){console.log(kt(`Already logged in, User Name:${e.userName}`));return}console.log(kt("Starting login process...")),console.log(kt("Press Enter to open browser for login...")),await GP();let t=await xe.login();console.log(kt(`Login successful. Logged in as ${t.userName}.`))},e=>{throw e instanceof Te||(e instanceof Error?e.message:String(e)).includes("Network connection failed")?e:new Error("Login failed",{cause:e})})});zo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(je()){console.log(Nl("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:S.CommandExecuted,args:["auth","logout"]};await Hs(n,async()=>{let e=await xe.logout();console.log(e?kt("Logout successful"):kt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});zo.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:S.CommandExecuted,args:["auth","status"]};await Hs(n,async()=>{let e=await xe.getUserInfo();if(!e){console.log(kt("Not logged in"));return}console.log(kt(`Current user: ${e.userName}`))},()=>{console.log(kt("Not logged in"))})});var qP=zo.command("team").description("Team-related commands");qP.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:S.CommandExecuted,args:["auth","team","list"]};await Hs(n,async()=>{let e=await dn();console.log(VP(e.teamList))},e=>{if(e instanceof Te){console.log(Nl(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var qf=zo;import{Command as aI}from"commander";import{green as cI,red as Zo,cyan as fh,yellow as hh,dim as gh}from"colorette";import lI from"p-limit";import zP from"ora";var ft=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=zP(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 Jf from"fs";import*as Ol from"path";import{homedir as zf}from"os";function un(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}var Yf=["DevEco"];async function Us(){let n=await L.get(Ze.TAGS_API_URL),t=Bs(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 JP(n){let e=[],t=Ze.DEFAULT_PAGE_SIZE,r=Ze.DEFAULT_MAX_PAGES,o=1;for(;o<=r;){let i=await L.post(Ze.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:o,pageSize:t,tagIds:[n]}}),s=Bs(i,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;o++}return e}async function Ml(n){let e=new Map,t=n.map(o=>JP(o)),r=await Promise.all(t);for(let o of r)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!Yf.includes(i.name)))}async function YP(n,e){let t=await L.post(Ze.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Ze.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return Bs(t,"Skills API").data.list}async function _l(n,e){let t=new Map,r=e.map(i=>YP(n,i)),o=await Promise.all(r);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!Yf.includes(s.name)))}function Kf(n){un(n);let e=[];for(let[,t]of Object.entries(dt)){let r=b.ensurePathWithinRoot(Ol.join(zf(),t.path),Ol.join(zf(),t.path,n));Jf.existsSync(r)&&e.push(t.displayName)}return e.sort()}function Bs(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==Ze.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Xf(n){un(n);let e=`${Ze.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return Bs(t,"Checksum API").data}import KP from"adm-zip";import XP from"crypto";import{timingSafeEqual as ZP}from"crypto";import Qf from"fs";import oe from"path";import{fileURLToPath as QP}from"url";import{homedir as eh}from"os";import{red as eI}from"colorette";var Bt=Qf.promises;function Zf(n,e){let t=oe.resolve(e),r=oe.resolve(n),o=oe.relative(r,t);if(o.startsWith("..")||oe.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function Fl(n){return oe.isAbsolute(n)?n:oe.resolve(process.cwd(),n)}function tI(n){return XP.createHash("sha256").update(n).digest("hex")}async function nI(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=tI(n),o=e.sha256.toLowerCase(),i=Buffer.from(r,"hex"),s=Buffer.from(o,"hex");if(i.length!==s.length||!ZP(i,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function th(n){un(n);let e=`${Ze.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await Xf(n);return await nI(t,r),t}async function rI(n,e,t){un(t);let r=new KP(n),o=r.getEntries();try{await Bt.stat(e)}catch{await Bt.mkdir(e,{recursive:!0})}let i=oe.join(e,t);Zf(e,i);for(let s of o){let a=oe.join(i,s.entryName);Zf(i,a)}r.extractAllTo(i,!0)}async function jl(n){let e=dt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(dt).join(", ")}`);let t=oe.join(eh(),e.path.replace("/skills",""));try{return await Bt.access(t),!0}catch{return!1}}function $l(n){let e=dt[n];return oe.join(eh(),e.path)}function oI(n){let e=dt[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(dt).join(", ")}`);return e}function Hl(n,e){let t=oI(e),r="projectPath"in t?t.projectPath:oe.join("."+e,"skills");return oe.join(n,r)}async function iI(n,e,t){un(e);let r=oe.join(n,e);try{if(await Bt.access(r),t)await Bt.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 Ul(n,e,t){await rI(n,e,t),console.log(`Skill ${t} installed to ${oe.join(e,t)}.`)}async function Bl(n,e,t){let r=oe.join(e,t);await Bt.mkdir(r,{recursive:!0});let o=oe.join(r,oe.basename(n));await Bt.copyFile(n,o),console.log(`Skill ${t} installed to ${r}.`)}function nh(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(eI(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Or(n,e,t,r){try{let o=await e(),{shouldSkip:i}=await iI(o,n,r);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return nh(n,o,"Installation failed")}}async function Wl(n,e){try{un(n);let t=await e(),r=oe.join(t,n);try{await Bt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Bt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return nh(n,t,"Removal failed")}}async function rh(n,e,t,r=!1){return Or(n,()=>$l(e),o=>Ul(t,o,n),r)}async function oh(n,e,t,r=!1){return Or(n,()=>t,o=>Ul(e,o,n),r)}async function ih(n,e,t,r,o=!1){return Or(n,()=>Hl(t,r),i=>Ul(e,i,n),o)}async function sh(n,e,t,r=!1){return Or(n,()=>$l(t),o=>Bl(e,o,n),r)}async function ah(n,e,t,r,o=!1){return Or(n,()=>Hl(t,r),i=>Bl(e,i,n),o)}async function ch(n,e,t,r=!1){return Or(n,()=>t,o=>Bl(e,o,n),r)}async function Vl(n,e){return Wl(n,()=>$l(e))}async function lh(n,e){return Wl(n,()=>e)}async function dh(n,e,t){return Wl(n,()=>Hl(e,t))}function uh(){let e=oe.dirname(QP(import.meta.url));for(;;){let t=oe.join(e,"SKILL.md");if(Qf.existsSync(t))return t;let r=oe.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import ph from"fs";import{cyan as sI}from"colorette";async function Jo(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await jl(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function Yo(){let n=[];for(let e of Object.keys(dt))await jl(e)&&n.push(e);return n}function Ko(n){let e=n.filter(o=>o.success&&!o.skipped).length,t=n.filter(o=>o.skipped).length,r=n.filter(o=>!o.success).length;console.log(),console.log(sI("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function pn(n,e,t){if(!ph.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!ph.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function Xo(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Fl(n):void 0,resolvedProject:e?Fl(e):void 0}}async function Ws(n,e,t){let r=[],o=[],i;if(e?i=e:t&&n.agent?o=(await Jo(n.agent)).map(a=>({project:t,agent:a})):t?o=(await Yo()).map(a=>({project:t,agent:a})):n.agent?r=await Jo(n.agent):r=await Yo(),!i&&r.length===0&&o.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:o,customPath:i}}var yh="deveco";async function dI(n){let e=await Us();if(n.all)return(await Ml(e)).map(r=>r.enName);{let r=(await _l(n.skill,e)).find(o=>o.enName===n.skill);if(!r)throw new Qn("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function uI(n,e,t,r){let o=[];if(t.customPath){let i=await oh(n,e,t.customPath,r);return o.push(i),o}for(let i of t.agents){let s=await rh(n,i,e,r);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await ih(n,e,i,s,r);o.push(a)}return o}function pI(n){if(n.all&&n.skill)throw new Qn("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new Qn("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=Xo(n.path,n.project,n.agent);return t&&pn(t,"Project directory",n.force),e&&pn(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}function mI(n,e,t){return!!(e||t||n.path||n.project||n.agent)}function fI(){return{agents:[yh],projectAgents:[],customPath:void 0}}async function hI(n,e,t){let r=je()&&!mI(n,e,t)?fI():await Ws(n,e,t);return{skillNames:await dI(n),targets:r}}async function gI(n,e,t,r){let o=[],i=0,s=n.length,a=lI(5),c=n.map(l=>a(()=>yI(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 w=await c[l];if(!w.success){r.fail(),console.log(Zo(`${d}: Download failed - ${w.error}`)),o.push({success:!1});continue}i+=w.buffer.length,r.stop();let C=await uI(d,w.buffer,e,t);o.push(...C)}return{results:o,diskBytes:i}}async function yI(n){try{let e=await th(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 wI(n){let e=new ft;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=pI(n),{skillNames:o,targets:i}=await hI(n,t,r),{results:s,diskBytes:a}=await gI(o,i,n.force||!1,e);return e.stop(),Ko(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function wh(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,o=n.filter(s=>!s.success).length,i=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>vI(s.error)))];return{opTotal:e,opSuccess:t,opFailed:o,opSkipped:r,...i.length>0?{failedErrors:i}:{}}}function vI(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var Qn=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function SI(n){let e=n;return n instanceof Qn?n.code:e.code??e.name??"UnknownError"}function Gs(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 qs(n,e,t){let r=Date.now(),o=!0,i=null,s={};try{s=await e()}catch(a){throw o=!1,i=SI(a),a}finally{let a={event:S.SkillOperation,subAction:n,args:t,...s};await D.track(a,{duration_ms:Date.now()-r,success:o,error_code:i})}}function bI(n){return qs("add",async()=>{let{diskBytes:e,results:t}=await wI(n);return{diskUsage:ue(e),...n.skill?{skillName:n.skill}:{},...wh(t)}},Gs("add",n))}function EI(n){let{resolvedPath:e,resolvedProject:t}=Xo(n.path,n.project,n.agent);return t&&pn(t,"Project directory"),e&&pn(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function CI(n,e){let t=new ft;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:o}=EI(e);t.stop();let i=await PI(e,n,r,o);return t.stop(),Ko(i),i}catch(r){throw t.stop(),r}}function mh(n,e=""){if(n.length===0)throw new Qn("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function Vs(n,e){let t=[];for(let r of e){let o=r.type==="agent"?await Vl(n,r.agent):await dh(n,r.project,r.agent);t.push(o)}return t}async function PI(n,e,t,r){if(t)return[await lh(e,t)];if(r&&n.agent){let a=(await Jo(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return Vs(e,a)}if(r){let s=await Yo();mh(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return Vs(e,a)}if(n.agent){let a=(await Jo(n.agent)).map(c=>({type:"agent",agent:c}));return Vs(e,a)}if(je())return[await Vl(e,yh)];let o=await Yo();mh(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return Vs(e,i)}var Qo=new aI("skills").description("Manage HarmonyOS skills");Qo.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await qs("list",async()=>{let e=new ft;try{e.start("Fetching skills...");let t=await Us(),r=await Ml(t);if(r.length===0)return e.stop(),console.log(hh("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let o of r)if(n.long){console.log(fh(o.enName)),console.log(gh(o.description));let i=Kf(o.enName);i.length>0&&console.log(cI(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName);return{resultTotal:r.length}}finally{e.stop()}},Gs("list",n))}catch(e){console.error(Zo(e.message)),process.exit(1)}});Qo.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await qs("find",async()=>{let e=new ft;try{e.start("Searching skills...");let t=await Us(),r=await _l(n,t);if(r.length===0)return console.log(hh(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let o of r)console.log(fh(o.enName)),console.log(gh(o.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}},Gs("find"))}catch(e){console.error(Zo(e.message)),process.exit(1)}});Qo.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 bI(n)}catch(e){console.error(Zo(e.message)),process.exit(1)}});Qo.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 qs("remove",async()=>{let e=await CI(n.skill,n);return{skillName:n.skill,...wh(e)}},Gs("remove",n))}catch(e){console.error(Zo(e.message)),process.exit(1)}});var vh=Qo;import{Command as II,InvalidArgumentError as zs}from"commander";import{cyan as Gl,red as bh}from"colorette";import AI from"ora";function DI(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 kI(n){return{event:S.CommandExecuted,args:DI(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function TI(n){return n instanceof v?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function RI(n,e){let t=Date.now(),r=!0,o=null;try{await e()}catch(i){r=!1,o=TI(i),console.error(bh(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await D.track(n,i).catch(()=>{})}}function xI(n){try{return b.parsePositiveInteger(n,"tail")}catch{throw new zs("`tail` must be a positive integer.")}}function Sh(n,e){try{return b.parseDurationToSeconds(n,e)}catch{throw new zs(`${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 LI(n){try{return b.assertHilogLevel(n),n}catch{throw new zs("`level` must be one of: D, I, W, E, F.")}}function NI(n){try{return b.assertBundleNameStrict(n),n}catch(e){throw new zs(e.message)}}function OI(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function MI(n,e,t,r,o){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:o})}function _I(n,e,t,r){let o=b.filterLogsByRelativeWindow(n,t,r);return e.tail?b.getLastLines(o,e.tail):o}var FI=new II("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(bh(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",LI).option("--bundle-name <bundle-name>","Filter by application bundle name",NI).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",xI).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Sh(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Sh(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await RI(kI(n),()=>jI(n))});async function jI(n){let e=AI({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{OI(n);let r=n.from,o=n.to,i=await k.new(),s=new Pr(i),a=await s.selectDevice(n.device);if(!a)throw new v("No active devices found.","No active devices found.");f(Gl(`deviceId: ${a}`)),f(Gl(`type: ${n.crash?"Crash logs":"Common logs"}`)),f(Gl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await MI(s,a,n,r,o);t(),n.crash&&c&&(c=_I(c,n,r,o)),c&&console.log(c)}finally{t()}}var Eh=FI;import ti from"path";import Wt from"fs";import Jl from"process";import xh from"os";import{Command as XI}from"commander";import{green as Dh,red as ql,cyan as ZI,yellow as kh}from"colorette";import me from"fs-extra";import H from"path";import*as Ph from"os";import{fileURLToPath as $I}from"url";var Ch={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"}},HI=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function UI(){let n=import.meta.url,e=$I(n);if(e.includes("dist")){let i=H.dirname(e),s=H.dirname(i);return H.join(s,"templates","application")}let t=H.dirname(e),r=H.dirname(t),o=H.dirname(r);return H.join(o,"templates","application")}function Ih(n,e){me.mkdirSync(e,{recursive:!0});for(let t of me.readdirSync(n,{withFileTypes:!0})){let r=H.join(n,t.name),o=H.join(e,t.name);if(t.isDirectory()){Ih(r,o);continue}me.existsSync(o)||(me.mkdirSync(H.dirname(o),{recursive:!0}),me.copyFileSync(r,o))}}function ei(n,e){let t=me.readFileSync(n,"utf-8"),r=t;for(let[o,i]of e)r=r.replaceAll(o,i);r!==t&&me.writeFileSync(n,r,"utf-8")}function BI(n){if(Ch[n])return Ch[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function WI(n,e){if(e===22)return;let t=BI(e);t&&(ei(H.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),ei(H.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),ei(H.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function VI(n){return HI.filter(t=>!me.existsSync(H.join(n,t))).length===0}function GI(){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 qI(n){return Ph.platform()==="darwin"?H.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):H.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function zI(n,e){let t=qI(e);if(!me.existsSync(t))return!1;let r=[["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[o,i]of r){let s=H.join(t,o),a=H.join(n,i);me.existsSync(s)&&(me.mkdirSync(H.dirname(a),{recursive:!0}),me.copyFileSync(s,a))}return!0}function JI(n){let e=GI(),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 r of t){let o=H.join(n,r);me.mkdirSync(H.dirname(o),{recursive:!0}),me.writeFileSync(o,e)}}function YI(n,e){e&&zI(n,e)||JI(n)}function KI(n){let e=[H.join(n,"gitignore.txt"),H.join(n,"entry","gitignore.txt")];for(let t of e)if(me.existsSync(t)){let r=H.dirname(t);me.renameSync(t,H.join(r,".gitignore"))}}function Ah(n,e,t,r,o){let i=UI();if(!me.existsSync(i))throw new Error(`Template directory not found: ${i}`);me.mkdirSync(n,{recursive:!0}),Ih(i,n),KI(n),YI(n,o),ei(H.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),ei(H.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),WI(n,r);let s=VI(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function QI(n){if(n.length<1||n.length>200)throw new fe("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new fe("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Lh(n){if(xh.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Th(n){if(n.length===0)throw new fe("errorCode","Project path cannot be empty.");if(n.length>120)throw new fe("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=xh.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new fe("errorCode",`Project path can only contain ${i}.`)}let r=Lh(n);if(/[\u4e00-\u9fff]/.test(r))throw new fe("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new fe("errorCode","Project path cannot end with a dot (.)")}function eA(n){let e=n,t=ti.parse(n).root;for(;e!==t;){if(Wt.existsSync(e))return e;e=ti.dirname(e)}return Wt.existsSync(t)?t:null}function Rh(n){let e=eA(n);if(!e)throw new fe("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Wt.accessSync(e,Wt.constants.W_OK)}catch{throw new fe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=ti.join(e,`.deveco_write_test_${Date.now()}`);try{Wt.writeFileSync(t,"test"),Wt.unlinkSync(t)}catch{throw new fe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function tA(n){return`com.example.${n.toLowerCase()}`}function nA(n,e){if(e){let o=Lh(e),i=ti.resolve(o);if(Wt.existsSync(i)){if(Wt.readdirSync(i).length>0)throw new fe("errorCode",`Directory '${i}' is not empty. Cannot create project here.`)}else Rh(i);return i}let t=Jl.cwd(),r=ti.join(t,n);if(Wt.existsSync(r))throw new fe("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return Rh(r),r}function rA(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let o=Number(n.apiLevel);if(!Number.isInteger(o)||o<17)throw new fe("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new fe("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>r)throw new fe("errorCode",`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return o}return t!==void 0?t:23}async function oA(){try{return await k.new()}catch(n){console.error(kh(`DevEco Studio not found: ${n.message}`)),console.log(kh("Use placeholder API level instead."));return}}var fe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function zl(n,e,t,r){let o={event:S.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},i={duration_ms:Date.now()-n,success:e,error_code:t};await D.track(o,i).catch(()=>{})}function iA(n){console.log(`
|
|
1287
|
-
`+
|
|
1288
|
-
Failed to create project.`)),console.error(
|
|
1289
|
-
`)){let s=i.indexOf(
|
|
1290
|
-
`);return/not ready|未初始化|初始中|稍后重试|please retry|retry \d+s|syncing|initializing|初始化失败|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|工程路径/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|不能同时|Must specify|无效/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/不存在|does not exist|not exist|not found|No valid|不是 \.ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function
|
|
1291
|
-
\r
|
|
1292
|
-
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let
|
|
1293
|
-
\r
|
|
1294
|
-
`);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){m.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10);if(!Number.isFinite(s)||s<0||s>OA){m.warn(`[LspClient] Invalid Content-Length: ${i[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){m.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},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 o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var fn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,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){m.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);if(o)try{o(t,r)}finally{this.callbacks.delete(e)}else{let i=[...this.callbacks.keys()].map(s=>String(s));m.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{m.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{o()}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 Qs=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var jr=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 o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}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 Xh=20*1e3,MA=30*1e3,ea=class{client;nextRequestId=1;stopOnce=null;callbacks=new jr;requestCallbacks=new fn;diagnosticMap=new Map;initProgressReset=null;get lspPid(){return this.client.pid}constructor(e){this.client=new mn(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(y.SHUTDOWN,null,this.nextRequestId++),m.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),m.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),m.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,et);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,o=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((i,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(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new Qs(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=MA){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.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 o=r instanceof Error?r.message:String(r);m.error(`[LSP] JSON parse error: ${o}, 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 r=t;if(e.error){let o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:m.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:m.info(`[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 o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}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:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Xh,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Xh}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),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 o of t)this.finalizeDiagnostic(o,[r]);return}this.broadcastToClients({jsonrpc:R,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var ta=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)){m.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Ql(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)}},Ql=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var _A={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"},FA={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",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"},x={..._A,...FA},hn={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"},Zh=new Set([1e3,2e3,3e3,3001]);function jA(n){if(!T(n))return!1;let e=n.textDocument;return T(e)&&typeof e.uri=="string"}function $A(n){return T(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function HA(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 jr;requestCallbacks=new fn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new mn(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:R,method:x.EXIT,params:{}}),hn.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(x.BROADCAST),this.callbacks.register(x.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(x.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(x.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(x.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:R,method:x.INITIALIZED,params:{editors:e}}),hn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),hn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!T(t)){m.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!jA(t)){m.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){m.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let i=t.textDocument.uri,s=ut(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;m.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(m.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!$A(r)){m.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),x.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!T(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:R,method:x.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),hn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=ut(t);e.textDocument.uri=o,m.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new ta(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,x.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),hn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=ut(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,x.PUBLISH_DIAGNOSTICS)),m.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),hn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=ut(e);m.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){m.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.DID_CLOSE,params:{textDocument:{uri:r}}}),hn.DID_CLOSE)}getDiagnosticMessage(e){let t=ut(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);m.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 o of t)this.finalizeDiagnostic(o,x.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:x.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 x.MODULE_INIT_FINISH:return m.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(x.MODULE_INIT_FINISH),this.callbacks.unregister(x.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case x.INDEXING_PROGRESS_UPDATE:return m.info(`[LSP] onIndexingProgressUpdate: ${HA(t.params)}`),this.callbacks.invoke(x.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case x.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case x.ON_PACKAGE_CHANGE_FINISH:m.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case x.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case x.ON_ASYNC_HOVER:this.handleAsyncResponse(t,x.HOVER);return;case x.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,x.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case x.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,x.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;T(t)&&T(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,r={jsonrpc:R,method:x.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){m.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){m.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}m.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){m.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!T(r)){m.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=r.requestId;if(typeof o!="number"){m.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,r)}handleForceOpenFile(e){if(!e){m.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,x.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){m.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let o=this.diagnosticMap.get(t);if(!o){m.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(Zh)&&this.finalizeDiagnostic(t,x.PUBLISH_DIAGNOSTICS,o.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),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}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),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),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 ed from"path";import*as la from"path";var ra=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var oa=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var ia=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var sa=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var aa=class{typeSetting=new ia;parameterNames=new sa};var ca=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=V(la.dirname(t)),this.indexingDataLocation=V(o),this.loggerPath=V(la.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new ra;gutterIconsSetting=new oa;inlayHintsSetting=new aa;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Qh from"path";var ni=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(V(Qh.join(e,"src","main","resources")))}};var UA="OS",$r=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${UA}`;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 ni(e)):this.buildProfileParam=new ni}toString(){return JSON.stringify(this)}};var Hr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Le from"path";import*as Wr from"fs";var da=class{modulePath;dependencies={};dynamicDependencies={}};var er=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 Ur=class{constructor(e,t,r){this.projectPath=e;this.moduleName=t;this.modulePath=r}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Vt from"path";import*as ua from"fs";var Br=class{name="";version="";storePath="";dependencyPath="";path=""};var _={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:De.OH_PACKAGE_JSON5},ri=`${_.HVIGOR_CACHE}/${_.DEPENDENCY}`,tr=`${_.DEPENDENCY}${_.JSON5}`,_G=De.SYNC_OUTPUT_PATH;var oi=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 o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}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=Vt.join(this.dependencyPath,_.OH_PACKAGE_JSON5),r=ze(t);r&&(this.dependencies=this.getDependencyList(r,_.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,_.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,_.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 o=e[t];if(!T(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){m.error(`${i} package dependency value is not String ${t}`);continue}let a=new Br;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Vt.normalize(Vt.join(this.modulePath,_.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Vt.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Vt.resolve(this.modulePath,s)),ua.existsSync(i)&&ua.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){m.error("parser dependency path is invalid",i)}}};import*as nr from"fs";import*as gn from"path";import BA from"json5";var pa=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 gn.join(this.projectPath,_.OH_MODULES_PATH,_.OHPM_PATH,_.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 o of e)if(!n.checkObjectDepth(o,t,r+1))return!1;return!0}for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&!n.checkObjectDepth(e[o],t,r+1))return!1;return!0}readLockFile(e){if(!nr.existsSync(e))return m.error("lock file does not exist"),this.clearDependencies(),null;try{let t=nr.statSync(e);if(t.size>n.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=nr.readFileSync(e,"utf8"),r=BA.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(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(!T(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 r=e.packages;return r?{valid:!0,modules:t,packages:r}:(m.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,_.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,_.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,_.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!T(e))return t;let r=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;let i=e[o];if(!T(i)){m.error(`${o} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof i.storePath=="string"&&t.set(o,i.storePath)}return t}getDependencyList(e,t,r){if(!T(e))return[];let o=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++o>n.MAX_KEYS_PER_OBJECT){m.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[i];if(T(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,i)}}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!T(o))return m.error("moduleJsonObject is null"),[];let i=[],s=o[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){m.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:"",w=new Br;w.name=c,w.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(w,r,c,d,g);let C=`${c}@${g}`;this.storePathMap.has(C)&&(w.storePath=this.storePathMap.get(C)||""),i.push(w)}return i}parseDependencyPath(e,t,r,o,i){let s=gn.resolve(this.projectPath,gn.join(t,_.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=gn.isAbsolute(a)?a:gn.resolve(this.projectPath,a);nr.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?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 eg(n){return T(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var rr=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Nt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Le.join(t,ri),o=Le.join(r,tr);if(!Wr.existsSync(r)||!Wr.existsSync(o)){let c="Dependency map or JSON not found";return m.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Ur(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return m.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];if(eg(l)){try{b.assertModuleName(l.name)}catch{m.warn(`[Parser] Skipping module with invalid name: ${l.name}`);continue}this.parseSingleModule(l,r,i,e),(c+1)%100===0&&m.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`)}}return m.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,o=Le.join(r,ri),i=Le.join(o,tr);if(!Wr.existsSync(o)||!Wr.existsSync(i))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 Ur(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,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(!eg(l))continue;let d=l.name;try{b.assertModuleName(d)}catch{m.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=Le.resolve(this.projectPath,l.srcPath),w=Le.join(o,d),C=V(g),z=this.buildModuleDependencies(d,C,w,a);z.moduleName=d,t.push(z)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Le.resolve(this.projectPath,e.srcPath),a=Le.join(t,i),c=V(s),l=new $r(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new Hr(g),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new Ur(this.projectPath,e,t);oi.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new da;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new er(i);for(let i of e.finalDynamicDependencies)o[i.name]=new er(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Le.join(e,_.OH_PACKAGE_JSON5);if(!Wr.existsSync(r))return;oi.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 pa(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Le.join(e,"src","main","module.json5"),o=ze(r);if(!T(o)||!T(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}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=Le.join(e,"src","main","resources","base","profile","main_pages.json"),r=ze(t);return!T(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="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=Le.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=ze(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[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Le.join(this.projectPath,"build-profile.json5");this.buildProfileCache=ze(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}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 ma=class{constructor(e=[]){this.valueSet=e}valueSet};var Vr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var tg=(I=>(I[I.File=1]="File",I[I.Module=2]="Module",I[I.Namespace=3]="Namespace",I[I.Package=4]="Package",I[I.Class=5]="Class",I[I.Method=6]="Method",I[I.Property=7]="Property",I[I.Field=8]="Field",I[I.Constructor=9]="Constructor",I[I.Enum=10]="Enum",I[I.Interface=11]="Interface",I[I.Function=12]="Function",I[I.Variable=13]="Variable",I[I.Constant=14]="Constant",I[I.String=15]="String",I[I.Number=16]="Number",I[I.Boolean=17]="Boolean",I[I.Array=18]="Array",I[I.Object=19]="Object",I[I.Key=20]="Key",I[I.Null=21]="Null",I[I.EnumMember=22]="EnumMember",I[I.Struct=23]="Struct",I[I.Event=24]="Event",I[I.Operator=25]="Operator",I[I.TypeParameter=26]="TypeParameter",I))(tg||{}),ng=()=>Object.values(tg).filter(n=>typeof n=="number");var fa=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var ha=class{applyEdit=!0;workspaceEdit=new fa;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new ma(ng());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Vr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var ga=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var ya=class{constructor(e=[]){this.valueSet=e}valueSet};var wa=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var rg=(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))(rg||{}),og=()=>Object.values(rg).filter(n=>typeof n=="number");var va=class{completionItemKind=new ya(og());completionItem=new wa;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Sa=class{synchronization=new ga;completion=new va;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 Vr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var ba=class{workspace=new ha;textDocument=new Sa;notebookDocument=null;window=null;general=null;experimental=null};var Ea=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Ca=class{constructor(e,t,r,o,i,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=i;this.useStandardProtocol=s;this.serverPath=vo(t,this.useStandardProtocol),this.logPath=xp(),this.indexLogPath=o||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new ea(a):new na(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;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){let r=!1;try{m.info(`serverPath: ${this.serverPath}`),m.info(`rootUri: ${this.rootUri}`),m.info(`sdkPath: ${this.sdkPath}`),m.info(`logPath: ${this.logPath}`);let o=ut(this.rootUri),i=new ca(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new rr(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=ds(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Ea(o,i,new ba),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,et),m.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),m.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",et),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){m.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let o=T(r)?r:{};m.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:R,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new rr(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){m.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),m.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return m.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];m.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);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(),r=new Map(this.lastDepsOnlyForDiff.map(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new er({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new $r(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Hr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=hr(ed.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=hr(ed.join(t,"default/openharmony/ets/api")),i=hr(ed.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:m.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Yh(e)){m.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.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(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Gt from"fs";import*as $e from"path";import{createHash as VA}from"crypto";import{EventEmitter as GA}from"events";var Pa=class extends GA{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;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 o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),m.info(`[ConfigFileWatcher] Stopped watching: ${o}`));m.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Gt.existsSync(t)){m.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Gt.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{m.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),m.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){m.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let o of t){let i=$e.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=$e.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=$e.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=$e.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.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 o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){m.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=ze(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return m.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=$e.join(this.projectRoot,_.OH_PACKAGE_JSON5);Gt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=$e.resolve(this.projectRoot,i.srcPath),a=$e.join(s,_.OH_PACKAGE_JSON5);Gt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return $e.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Gt.readFileSync(t,"utf-8");return VA("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 o=Gt.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{m.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(r){m.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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){m.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){m.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),m.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:$e.basename(t),relativePath:$e.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}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 yn from"fs";import*as ht from"path";import{createHash as qA}from"crypto";import{EventEmitter as zA}from"events";var Ia=class extends zA{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ht.join(t,ri)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!yn.existsSync(this.depMapDir)){m.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=yn.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),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 V(ht.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===_.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===tr)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=ht.join(this.depMapDir,r);yn.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=ht.join(this.depMapDir,_.OH_PACKAGE_JSON5),r=ht.join(this.depMapDir,tr),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:(b.assertModuleName(s.name),ht.join(this.depMapDir,s.name,_.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!yn.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=ht.join(this.depMapDir,tr);try{let r=ze(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return m.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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){m.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(m.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.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 o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){m.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return V(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){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"}}),o.add(a.name),i.add(c.name);let l=(b.assertModuleName(a.name),ht.join(this.depMapDir,a.name,_.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),m.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,o,i){for(let[s,a]of t){if(o.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"}}),o.add(s),i.add(s),m.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=(b.assertModuleName(i),ht.join(this.depMapDir,i,_.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);m.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=yn.readFileSync(t,"utf-8");return qA("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as JA}from"child_process";var YA=["install","--all"];async function KA(n,e,t,r){return new Promise(o=>{let i=JA(n,[e,...YA],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1290
|
+
`,uA="6.1.0";function pA(r){let e=r.trim();if(!e)throw new Error("--target must not be empty.");return e}function mA(r){let e=r.trim();if(!ph.includes(e))throw new Error(`Invalid fold state "${r}". Available values: ${ph.join(", ")}`);return e}function fh(r,e,t,n){let o=e.trim();if(!/^-?\d+$/.test(o))throw new Error(`${r} must be an integer in [${t}, ${n}].`);let i=Number(o);if(i<t||i>n)throw new Error(`${r} must be in [${t}, ${n}].`);return i}function hh(r,e,t,n,o){let i=e.trim(),s=Number(i);if(!i||Number.isNaN(s))throw new Error(`${r} must be a number in [${t}, ${n}].`);if(o!==void 0&&!fA(i,o))throw new Error(`${r} supports at most ${o} decimal place(s).`);if(s<t||s>n)throw new Error(`${r} must be in [${t}, ${n}].`);return i}function fA(r,e){let t=r.split(".")[1];return t===void 0||t.length<=e}function hA(r,e,t,n,o){return Number(hh(r,e,t,n,o))}function gA(r){let e=r.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function yA(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${r}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function vA(r,e){let t=o=>o.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(xt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(xt("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(o=>t(o)===n)){console.error(qs("--os-version does not match any downloaded image (exact string required).")),console.log(xt("Use one of these --os-version values:"));for(let o of e)console.log(` ${o}`);throw new Error(`No downloaded image matches --os-version "${r}".`)}}var wA=["Name","Status","Serial","Device Type","OS Version"];function SA(r){return{cells:[r.name,r.status,r.serial??"-",r.deviceType??"-",r.osVersion??"-"],highlight:r.status==="running"}}async function bA(r,e){let t=await Promise.all(e.map(async n=>{let o=await Cn(r,n,lA);return[n,o]}));return new Map(t)}async function EA(r){let e=await _l(r),t=await bA(r,e);return{serials:e,params:t}}function CA(r,e,t,n,o){if(e)for(let i of["const.product.name","const.product.model"]){let s=e.get(i);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),o.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function PA(r,e,t){let n=new Map,o=new Map,i=[...r],s=[...t];for(let a of r){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&o.set(l,a),t.length>0&&CA(a,c,s,i,n)}for(let a=0;a<s.length&&a<i.length;a++)n.set(s[a],i[a]);return{productSerialMap:n,hvdSerialMap:o}}function AA(r,e,t){let n=r.map(o=>({emu:o,serial:e.get(o.name)??t.get(o.name),effectiveRunning:o.isRunning===!0||t.has(o.name)}));return n.sort((o,i)=>o.effectiveRunning!==i.effectiveRunning?o.effectiveRunning?-1:1:o.emu.name.localeCompare(i.emu.name)),n.map(({emu:o,serial:i,effectiveRunning:s})=>({name:o.name,status:s?"running":"stopped",serial:i??null,deviceType:o.deviceType??null,osVersion:o.osVersion??null}))}async function IA(r,e,t,n){try{let[o,i]=await Promise.all([r.listEmulators(),EA(e)]);if(o.length===0){n?.stop(),console.log(t==="json"?"[]":xt(" No emulator instances found."));return}let s=o.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=PA(i.serials,i.params,s);n?.stop();let l=AA(o,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(SA);console.log(Ut(wA,d))}catch(o){throw n?.stop(),new Error(`Failed to list emulators: ${o.message}`,{cause:o})}}function gh(r,e,t){let n=!1;for(let o=0;o<r.length;o++){let i=r[o];if(i.status!=="rejected")continue;n=!0;let s=i.reason;console.error(qs(`Failed to ${t} emulator "${e[o]}": ${s.message}`)),s.stdout&&console.error(ql(s.stdout)),s.stderr&&console.error(ql(s.stderr))}return n}var kA=2e3,DA=6e4;async function TA(r,e){let t=Ae(e);return(await Fl(r)).some(o=>Ae(o)===t)}async function yh(r,e,t,n=DA,o=kA){let i=Date.now()+n;for(;Date.now()<i;){if(await TA(r,e)===t)return!0;await new Promise(a=>setTimeout(a,o))}return!1}async function RA(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(xt(`Emulator "${t}" is already running.`));return}console.log(jn(`Starting emulator "${t}"...`));let o=await yh(e,t,!0);console.log(o?Qo(`Emulator "${t}" started successfully.`):xt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function xA(r,e,t){let n=await Promise.allSettled(t.map(o=>RA(r,e,o)));if(gh(n,t,"start"))throw new w("One or more emulators failed to start.")}async function vh(r,e){let t=e.trim();if(!Dt(t))return t;let n=await ue.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 LA(r,e,t){let n=await vh(e,t);if(console.log(jn(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(xt(`Emulator "${n}" is already stopped.`));return}let i=await yh(e,n,!1);console.log(i?Qo(`Emulator "${n}" stopped successfully.`):xt(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function NA(r,e,t){let n=await Promise.allSettled(t.map(o=>LA(r,e,o)));gh(n,t,"stop")}async function ut(){let r=await k.new();return{manager:_n.from(r),toolProvider:r}}async function Wt(r,e,t){let n={event:S.CommandExecuted,args:["emulator",t,"--target"]};await dt(n,async()=>{let o=pA(r.target),i=e(),{manager:s,toolProvider:a}=await ut(),c=await vh(a.hdcPath,o);await s.controlEmulator(c,i),console.log(Qo(`Emulator "${o}" operation completed.`))})}function OA(r){let e=[];return zs(e,"longitude",r.longitude,-180,180,8),zs(e,"latitude",r.latitude,-90,90,8),zs(e,"altitude",r.altitude,-1e4,1e4,2),zs(e,"bearing",r.direction,0,359.99,2,"--direction"),Kl(e,"Specify one geolocation option.")}function MA(r){let e=[];return Xo(e,"light",r.lightIntensity,0,1e5,!1,"--light-intensity"),Xo(e,"humidity",r.humidity,0,100,!1),Xo(e,"temperature",r.temperature,-273.1,100,!1),Xo(e,"steps",r.steps,0,1e4,!0),Xo(e,"heartrate",r.heartrate,0,255,!0),Kl(e,"Specify one sensor option.")}function Kl(r,e){if(r.length===0)throw new Error(e);if(r.length>1)throw new Error("Only one operation option can be specified.");return r[0]}function zs(r,e,t,n,o,i,s=`--${e}`){t!==void 0&&r.push({type:"gps",key:e,value:hh(s,t,n,o,i)})}function Xo(r,e,t,n,o,i,s=`--${e}`){if(t===void 0)return;let a=i?fh(s,t,n,o):hA(s,t,n,o,1);r.push({type:"sensor",key:e,value:a})}function _A(r){let e=[];return r.level!==void 0&&e.push({type:"battery",level:fh("--level",r.level,0,100)}),r.status!==void 0&&e.push({type:"battery-status",status:r.status==="charging"?1:0}),Kl(e,"Specify --level or --status.")}var fe=new Yl("emulator").description("Manage emulator instances");fe.hook("preAction",async()=>{(await k.new()).require({studio:uA})});var FA=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Js(r){let e=new $n("--device-type <type>","Emulator device type").choices([...FA]);return r?e.makeOptionMandatory():e}function Fn(r,e){for(let t of e)if(t in r)return r[t]}function Zo(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function mh(r){let e=Zo(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var jA=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],$A="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function HA(r,e,t){if(!await r.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Invalid --os-version value "${t}".
|
|
1291
|
+
Run \`devecocli emulator image list --all\` and use an exact OS Version value.`)}function wh(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function Sh(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let o=n,i=Zo(Fn(o,["osVersion","OsVersion","OSVersion","os_version"])),s=Zo(Fn(o,["deviceType","DeviceType","device_type"])),a=mh(Fn(o,["downloaded","Downloaded","isDownloaded"])),c=Zo(Fn(o,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Zo(Fn(o,["releaseType","ReleaseType","release_type"])),d=mh(Fn(o,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[i,s,c,l,d,a],highlight:e&&a==="true"})}return t}function UA(r){let e=r.trim();if(!e)return!0;let t=wh(e);return t===null?!1:t.length===0?!0:Sh(t,!0).length===0}function BA(r,e){let t=r.trim();if(!t)return"";let n=wh(t);if(!n)return r.trimEnd();let o=Sh(n,e);return Ut(jA,o)}var Ys=new Yl("image").description("HarmonyOS emulator system images (download, list, remove)");Ys.command("download").description("Download system image").addOption(Js(!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:S.CommandExecuted,args:["emulator","image","download",...r.deviceType?["--device-type"]:[],...r.osVersion?["--os-version"]:[],...r.force?["--force"]:[]]};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut();await zl(n.emulatorPath,n.sdkPath);let o=r.deviceType?.trim(),i=r.osVersion?.trim();if(!o)throw new w("Error: missing required option '--device-type <type>'","Missing required device type.");if(!i)throw new w("Error: misssing required option '--os-version <version>'","Missing required OS version.");await HA(t,o,i),await t.installEmulatorImage({deviceType:o,osVersion:i,force:r.force===!0})})});Ys.command("remove").description("Remove a downloaded system image").addOption(Js(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let e={event:S.CommandExecuted,args:["emulator","image","remove","--device-type","--os-version"]};await dt(e,async()=>{let{manager:t}=await ut();await t.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})})});Ys.command("list").description("List system images").addOption(Js(!1)).option("--all","List all images (local and remote)").addOption(new $n("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["emulator","image","list",...r.deviceType?["--device-type"]:[],...r.all?["--all"]:[],...r.format!=="table"?["--format"]:[]]};await dt(e,async()=>{let{manager:t}=await ut(),n;r.all?n=void 0:n=!0;let o=await t.listEmulatorImages({deviceType:r.deviceType,downloaded:n});if(UA(o)){console.log(xt($A));return}if(r.format==="json"){console.log(o.trimEnd());return}let i=BA(o,r.all===!0);console.log(i)})});fe.addCommand(Ys);var Ks=new Yl("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Ks.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let r={event:S.CommandExecuted,args:["emulator","license","view"]};await dt(r,async()=>{let{toolProvider:e}=await ut(),t=await ch(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ks.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let r={event:S.CommandExecuted,args:["emulator","license","accept"]};await dt(r,async()=>{let{toolProvider:e}=await ut(),t=await uh(e.emulatorPath,e.sdkPath);process.exitCode=t})});Ks.action(async()=>{let r={event:S.CommandExecuted,args:["emulator","license"]};await dt(r,async()=>{let{toolProvider:e}=await ut(),t=await dh(e.emulatorPath,e.sdkPath);process.exitCode=t})});fe.addCommand(Ks);fe.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(r=>Wt(r,()=>({type:"shake"}),"shake"));fe.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(r=>Wt(r,()=>({type:"power"}),"power"));fe.command("rotate").description("Rotate emulator").addOption(new $n("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Jl("<direction>").choices(["left","right"])).action((r,e)=>Wt(e,()=>({type:"rotation",direction:r}),"rotate"));fe.command("volume").description("Change volume").addOption(new $n("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Jl("<direction>").choices(["up","down"])).action((r,e)=>Wt(e,()=>({type:"volume",direction:r}),"volume"));fe.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",dA).action((r,e)=>Wt(e,()=>({type:"folded-state",state:mA(r)}),"fold"));fe.command("battery").description("Set battery level 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 $n("--status <status>","Charging status").choices(["charging","discharging"])).action(r=>Wt(r,()=>_A(r),"battery"));fe.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=>Wt(r,()=>OA(r),"geolocation"));fe.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Jl("<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 Wt(e,()=>t[r],"scene")});fe.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=>Wt(r,()=>MA(r),"sensor"));fe.command("list").description("List all emulator instances").addOption(new $n("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let e={event:S.CommandExecuted,args:["emulator","list"]};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut(),o=r.format==="table"?cA({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await IA(t,n.hdcPath,r.format,o)})});fe.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let e={event:S.CommandExecuted,args:["emulator","start"]};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut();if(await Gl(n.emulatorPath,n.sdkPath),!r?.length)throw new w("Error: missing required argument 'names'","Missing required emulator name.");await xA(t,n.hdcPath,r)})});fe.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:S.CommandExecuted,args:["emulator","stop"]};await dt(e,async()=>{let{manager:t,toolProvider:n}=await ut();if(!r?.length){console.error(qs("Error: missing required argument 'names'")),process.exitCode=1;return}await NA(t,n.hdcPath,r)})});var bh=fe.command("create <name>").description("Create a local emulator instance.").addOption(Js(!0)).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`').option("--force","Overwrite if supported");bh.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1292
|
+
${xt("Tip: ")}${ql("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1293
|
+
${jn('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1294
|
+
${jn('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1295
|
+
`)}});bh.action(async(r,e)=>{let t={event:S.CommandExecuted,args:["emulator","create","--device-type","--os-version",...e.force?["--force"]:[]]};await dt(t,async()=>{gA(r),yA(e.osVersion);let{manager:n}=await ut(),o=await n.listDownloadedImageOsVersions();vA(e.osVersion,o),console.log(jn(`Creating emulator "${r}"...`)),await n.createVirtualDevice({name:r,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Qo(`Emulator "${r}" created successfully.`))})});fe.command("delete <name>").description("Delete a local emulator instance").action(async r=>{let e={event:S.CommandExecuted,args:["emulator","delete"]};await dt(e,async()=>{let{manager:t}=await ut();console.log(jn(`Deleting emulator "${r}"...`));let n=await t.deleteVirtualDevice(r);console.log(Qo(`Emulator "${n}" deleted successfully.`))})});var Eh=fe;import{Command as dI}from"commander";import{red as rd,cyan as Lt}from"colorette";import*as Vh from"readline";import*as Bh from"crypto";import*as Ch from"http";import*as Ph from"crypto";import{URL as WA}from"url";var Xs=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,n,o){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=n,this.failedRedirectUrl=o}async start(){return new Promise((e,t)=>{let n=Ch.createServer((o,i)=>{this.handleRequest(o,i)});n.keepAliveTimeout=1,n.on("error",o=>{t(new Error("Failed to start local auth server",{cause:o}))}),n.listen(0,"127.0.0.1",()=>{this.server=n;let o=n.address();this.port=o.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,n)=>{this.resolveCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(o)},this.rejectCallback=o=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),n(o)},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 i=new WA(e.url??"",`http://${n}`);if(i.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=i.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 o="",i=0,s=65536;e.on("data",a=>{if(i+=a.length,i>s){e.destroy(new Error("Request body too large"));return}o+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,n,o)})}handleCallbackRequest(e,t,n,o){try{let i=this.parseParams(n,o),s=i.get("code"),a=i.get("tempToken"),c=i.get("siteId"),l=i.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(i){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(i)}}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&&Ph.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 Be from"fs";import*as fr from"path";import{homedir as KA}from"os";var Vt={};bS(Vt,{LocalCrypto:()=>Vt,decryptForLocalStorage:()=>qA,decryptForLocalStorageFromDirectory:()=>JA,encryptForLocalStorage:()=>zA,isEncryptedBlob:()=>YA});import*as ne from"fs";import*as Oe from"path";import*as Ue from"crypto";import*as Ih from"os";import{homedir as kh}from"os";var Ne=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var ei=Br.ALGORITHM,Dh=Br.IV_LENGTH,ti=Br.KEY_LENGTH,ri=Br.KEY_LENGTH,on=Br.KEK_VERSIONS,Zs=process.env.DEVECO_CLI_DATA_DIR||Oe.join(kh(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME),Qs=Oe.join(kh(),".local","share",Ee.APP_NAME,"keys"),Hn=Oe.join(Zs,Ee.KEY_FILE_NAME);function Ah(r){return Ih.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 Xl(r){return Oe.join(Qs,`${r}.bin`)}function Th(){if(!ne.existsSync(Zs))try{ne.mkdirSync(Zs,{recursive:!0,mode:448})}catch(r){throw r.code==="EACCES"?new Ne(Ah(Zs)):r}if(!ne.existsSync(Qs))try{ne.mkdirSync(Qs,{recursive:!0,mode:448})}catch(r){throw r.code==="EACCES"?new Ne(Ah(Oe.dirname(Qs))):r}}function Rh(){Th();for(let r of on){let e=Xl(r);ne.existsSync(e)||ne.writeFileSync(e,Ue.randomBytes(ti),{mode:384})}}function xh(r){if(!on.includes(r))throw new Error(`Invalid kekId: ${r}`);Rh();let e=Xl(r),t=ne.readFileSync(e);if(t.length===ti)return t;let n=Ue.randomBytes(ti);return ne.writeFileSync(e,n,{mode:384}),n}function Zl(r,e){let t=Ue.randomBytes(Dh),n=xh(e),o=Ue.createCipheriv(ei,n,t),i=Buffer.concat([o.update(r),o.final()]),s=o.getAuthTag();return{version:1,algorithm:ei,kekId:e,encryptedDek:i.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function Lh(r,e){return Nh(Buffer.from(r.encryptedDek,"base64"),e,r.iv,r.authTag)}function Nh(r,e,t,n){let o=Ue.createDecipheriv(ei,e,Buffer.from(t,"base64"));return o.setAuthTag(Buffer.from(n,"base64")),Buffer.concat([o.update(r),o.final()])}function Oh(r,e){return Nh(Buffer.from(r.ciphertext,"base64"),e,r.iv,r.authTag).toString("utf8")}function VA(){if(Rh(),ne.existsSync(Hn))return;let r=Ue.randomBytes(ri),e=Zl(r,on[0]);ne.writeFileSync(Hn,JSON.stringify(e,null,2),{mode:384})}function Mh(){VA();let r=JSON.parse(ne.readFileSync(Hn,"utf8")),e=Lh(r,xh(r.kekId));if(e.length===ri)return e;let t=Ue.randomBytes(ri),n=Zl(t,on[0]);return ne.writeFileSync(Hn,JSON.stringify(n,null,2),{mode:384}),t}function GA(){Th();for(let t of on){let n=Xl(t);ne.existsSync(n)||ne.writeFileSync(n,Ue.randomBytes(ti),{mode:384})}if(ne.existsSync(Hn))return;let r=Ue.randomBytes(ri),e=Zl(r,on[0]);ne.writeFileSync(Hn,JSON.stringify(e,null,2),{mode:384})}function zA(r){let e=Mh(),t=Ue.randomBytes(Dh),n=Ue.createCipheriv(ei,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i=n.getAuthTag();return{version:1,algorithm:ei,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:i.toString("base64"),timeStamp:Date.now()}}function qA(r){try{return Oh(r,Mh())}catch{throw GA(),new Error("Failed to decrypt local ciphertext")}}function JA(r,e){let t=Oe.join(e,Ee.KEY_FILE_NAME),n=JSON.parse(ne.readFileSync(t,"utf8"));if(!on.includes(n.kekId))throw new Error(`Invalid kekId: ${n.kekId}`);let o=Oe.join(e,"keys",`${n.kekId}.bin`),i=Oe.resolve(o),s=Oe.resolve(Oe.join(e,"keys"));if(!i.startsWith(s+Oe.sep)&&i!==s)throw new Error("kekId resolves outside the keys directory");let a=ne.readFileSync(i);if(a.length!==ti)throw new Error("Invalid external root key");let c=Lh(n,a);if(c.length!==ri)throw new Error("Invalid external data encryption key");return Oh(r,c)}function YA(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 We(){return process.env.DEVECO_CLI_AUTH_SOURCE===Ee.AUTH_SOURCE_DEVECO_CODE}var ea=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||fr.join(KA(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME);return fr.join(e,Ee.TOKEN_FILE_NAME)}ensureConfigDir(){let e=fr.dirname(this.getLocalTokenFilePath());Be.existsSync(e)||Be.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=Vt.encryptForLocalStorage(e);this.ensureConfigDir();let n=this.getLocalTokenFilePath();Be.writeFileSync(n,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return We()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!We())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=fr.resolve(e);try{let n=fr.join(t,Ee.TOKEN_FILE_NAME);if(!Be.existsSync(n))return null;let o=JSON.parse(Be.readFileSync(n,"utf8"));return Vt.isEncryptedBlob(o)?Vt.decryptForLocalStorageFromDirectory(o,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Be.existsSync(e))return null;let t=JSON.parse(Be.readFileSync(e,"utf8"));return Vt.isEncryptedBlob(t)?Vt.decryptForLocalStorage(t):null}catch(t){let n=t.code;return n==="EACCES"||n==="EPERM"||n==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(We()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Be.existsSync(e)&&Be.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Gt=new ea;import{spawn as XA}from"child_process";function ZA(r){try{let e=new URL(r);return!(!["http:","https:"].includes(e.protocol)||e.hostname===""||r.includes('"'))}catch{return!1}}function QA(r){return r.replace(/[&|<>()^%!]/g,e=>`^${e}`)}async function _h(r){if(!ZA(r))throw new Error(`Invalid URL: ${JSON.stringify(r)}`);let e,t;switch(process.platform){case"win32":e="cmd",t=["/c","start",'""',QA(r)];break;case"darwin":e="open",t=[r];break;default:e="xdg-open",t=[r];break}let n=XA(e,t,{stdio:"ignore",shell:!1,windowsHide:!0});return new Promise((o,i)=>{n.on("error",s=>{i(new Error("Failed to open browser",{cause:s}))}),n.on("close",s=>{s===0?o():i(new Error(`Browser process exited with code ${s}`))})})}import eI from"axios";import{getProxyForUrl as tI}from"proxy-from-env";function rI(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 Ql=class{client;constructor(){let e={timeout:So.HTTP_TIMEOUT_MS,headers:{"User-Agent":qi.USER_AGENT,"accept-language":qi.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=eI.create(e),this.client.interceptors.request.use(t=>{let n=tI(t.url??"");return t.proxy=n?rI(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`;throw new Error(`${t.message}
|
|
1296
|
+
${n}`)})}async get(e,t){let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}async post(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}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){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)}async postAllowFailure(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(n)}async deleteAllowFailure(e,t){let n=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(n)}async getBinaryAllowFailure(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),o=Buffer.from(n.data),i=o.toString("utf8");return{statusCode:n.status,statusText:n.statusText??"",buffer:o,body:i}}},L=new Ql;function Fh(r){let e=r.split(".");return e.length===3&&e.every(t=>t.length>0)}var zt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},sn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},ta={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},nI={[zt.CHINA]:sn.CHINA,[zt.RUSSIA]:sn.RUSSIA,[zt.EUROPE]:sn.EUROPE,[zt.SINGAPORE]:sn.CHINA},oI={[ta.CHINA]:zt.CHINA,[ta.SINGAPORE]:zt.SINGAPORE,[ta.EUROPE]:zt.EUROPE,[ta.RUSSIA]:zt.RUSSIA};function jh(r){return nI[r]??sn.CHINA}function $h(r){return oI[r]??zt.CHINA}var ed=class{async getJwtToken(e,t,n,o,i){let s=e.split("&")[0],a=$h(t),c={tempToken:s,site:a,version:Ee.API_VERSION,appid:i},l=`${n}/${o}`,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(!Fh(g))throw new Error("Invalid jwtToken format");return g}},Hh=new ed;var td=class{async checkJwtToken(e,t,n=!1){let o={refresh:String(n),jwtToken:e},i=`${t}/${X.JWT_TOKEN_CHECK_PATH}`,s=await L.get(i,{headers:o});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return L.parseJson(s)}async refreshToken(e){let t=await Gt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let n={refresh:"true",jwtToken:e},o=`${t}/${X.JWT_TOKEN_CHECK_PATH}`,i=await L.get(o,{headers:n});if(i.statusCode!==200)return null;let s=L.parseJson(i);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(n){let o=n;return console.error(`Failed to refresh token: ${o.code??""} ${o.message??""}`),null}}async getUserInfoFromJwt(e,t,n=!1){let o=await this.checkJwtToken(e,t,n);return!o.status||!o.userInfo||!o.userInfo.accessToken?(m("jwtToken invalid."),await Gt.clearToken(),null):{userId:o.userInfo.userId??"",userName:o.userInfo.name??"",accessToken:o.userInfo.accessToken,refreshToken:o.userInfo.refreshToken??"",jwtToken:e,countryCode:o.userInfo.nationalCode,language:jh(o.userInfo.nationalCode),isRealName:String(o.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let n=await Gt.loadJwtToken();return n?this.getUserInfoFromJwt(n,e,t):null}},Un=new td;import iI from"querystring";import{spawn as sI}from"child_process";function Uh(r){try{let e=JSON.stringify({signInfo:[{agrType:bo.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=iI.stringify({nsp_svc:"as.user.sign",access_token:r,request:e}),n=sI("curl",["-s","-X","POST",bo.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",o=>{let i=o.toString().trim();i==="200"?m("Agreement sign reported successfully"):m(`Agreement sign failed: HTTP ${i}`)}).on("error",()=>{})}catch(e){m(`Agreement sign error: ${e.message}`)}}var ra=class{config;server=null;constructor(e){this.config={...Eo,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${We()}`);let e=this.generateClientSecret();this.server=new Xs(e,X.CN_LOGIN_URL,this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),m(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),m("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(m(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new Ne("Non-China accounts are not supported.");let n=await Hh.getJwtToken(t.tempToken,t.siteId,X.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let o=await Un.getUserInfoFromJwt(n,X.CN_LOGIN_URL);if(!o)throw new Ne("Login failed: failed to get user info");return m(`User info received: ${o.userName}`),await Gt.saveJwtToken(n),m("JWT token saved"),Uh(o.accessToken),o}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await Gt.loadJwtToken();if(!e)return!1;let n=`${X.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await L.post(n,{timeout:5e3})}catch{m("Logout: server notification failed, local token cleared")}finally{await Gt.clearToken()}return!0}async getUserInfo(e=!0){return Un.fetchUserInfo(X.CN_LOGIN_URL,e)}generateClientSecret(){return Bh.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let o=`${X.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await _h(o)}async refreshToken(){return Un.refreshToken(X.CN_LOGIN_URL)}},Me=new ra;function cI(){return We()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function lI(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: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 na=class{config;constructor(e){this.config={...Eo,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Un.fetchUserInfo(X.CN_LOGIN_URL,!0);if(!e)throw new Ne(cI());let t=await this.fetchTeamList(e.accessToken,e.userId),n=lI(t);return{userId:e.userId,teamList:n}}async fetchTeamList(e,t){let n=this.config.agcTeamListUrl,o;try{o=await L.get(n,{headers:{oauth2Token:e,uid:t,source:"cli",lang:sn.CHINA},timeout:15e3})}catch(i){let s=i.message;throw s.includes("401")?new Ne("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:i})}if(o.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${o.statusCode}`);return typeof o.data=="string"?JSON.parse(o.data):o.data}},Wh=new na;async function hr(){return Wh.listTeams()}async function oa(r,e,t){let n=Date.now(),o=!0,i=null;try{await e()}catch(s){o=!1,i=q(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-n,success:o,error_code:i};await I.track(r,s)}}function uI(r){if(r.length===0)return Lt("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))),o=s=>s.map((a,c)=>a.padEnd(n[c])).join(" "),i=n.map(s=>"-".repeat(s)).join(" ");return[o(e),i,...t.map(o)].join(`
|
|
1297
|
+
`)}function pI(){return new Promise(r=>{let e=Vh.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),r()})})}var ni=new dI("auth").description("Authentication commands (login, logout, status, team)");ni.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(We()){console.log(rd("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let r={event:S.CommandExecuted,args:["auth","login"]};await oa(r,async()=>{let e=await Me.getUserInfo();if(e){console.log(Lt(`Already logged in, User Name:${e.userName}`));return}console.log(Lt("Starting login process...")),console.log(Lt("Press Enter to open browser for login...")),await pI();let t=await Me.login();console.log(Lt(`Login successful. Logged in as ${t.userName}.`))},e=>{throw e instanceof Ne||(e instanceof Error?e.message:String(e)).includes("Network connection failed")?e:new Error("Login failed",{cause:e})})});ni.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(We()){console.log(rd("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let r={event:S.CommandExecuted,args:["auth","logout"]};await oa(r,async()=>{let e=await Me.logout();console.log(e?Lt("Logout successful"):Lt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});ni.command("status").description("Show the currently logged-in user").action(async()=>{let r={event:S.CommandExecuted,args:["auth","status"]};await oa(r,async()=>{let e=await Me.getUserInfo();if(!e){console.log(Lt("Not logged in"));return}console.log(Lt(`Current user: ${e.userName}`))},()=>{console.log(Lt("Not logged in"))})});var mI=ni.command("team").description("Team-related commands");mI.command("list").description("List team accounts the current user has joined").action(async()=>{let r={event:S.CommandExecuted,args:["auth","team","list"]};await oa(r,async()=>{let e=await hr();console.log(uI(e.teamList))},e=>{if(e instanceof Ne){console.log(rd(e.message));return}throw new Error("Failed to list teams",{cause:e})})});var Gh=ni;import{Command as DI}from"commander";import{green as TI,red as ci,cyan as mg,yellow as fg,dim as hg}from"colorette";import RI from"p-limit";import fI from"ora";var Qe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=fI(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 qh from"fs";import*as nd from"path";import{homedir as zh}from"os";function gr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}var Jh=["DevEco"];async function ia(){let r=await L.get(ot.TAGS_API_URL),t=sa(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 hI(r){let e=[],t=ot.DEFAULT_PAGE_SIZE,n=ot.DEFAULT_MAX_PAGES,o=1;for(;o<=n;){let i=await L.post(ot.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:o,pageSize:t,tagIds:[r]}}),s=sa(i,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;o++}return e}async function od(r){let e=new Map,t=r.map(o=>hI(o)),n=await Promise.all(t);for(let o of n)for(let i of o)e.has(i.id)||e.set(i.id,i);return Array.from(e.values()).filter(o=>o.tags?.every(i=>!Jh.includes(i.name)))}async function gI(r,e){let t=await L.post(ot.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ot.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return sa(t,"Skills API").data.list}async function id(r,e){let t=new Map,n=e.map(i=>gI(r,i)),o=await Promise.all(n);for(let i of o)for(let s of i)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(i=>i.tags?.every(s=>!Jh.includes(s.name)))}function Yh(r){gr(r);let e=[];for(let[,t]of Object.entries(ft)){let n=E.ensurePathWithinRoot(nd.join(zh(),t.path),nd.join(zh(),t.path,r));qh.existsSync(n)&&e.push(t.displayName)}return e.sort()}function sa(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=L.parseJson(r);if(t.code!==ot.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Kh(r){gr(r);let e=`${ot.SKILL_API_BASE}/${r}/checksum`,t=await L.get(e);return sa(t,"Checksum API").data}import yI from"adm-zip";import vI from"crypto";import{timingSafeEqual as wI}from"crypto";import Zh from"fs";import ae from"path";import{fileURLToPath as SI}from"url";import{homedir as Qh}from"os";import{red as bI}from"colorette";var qt=Zh.promises;function Xh(r,e){let t=ae.resolve(e),n=ae.resolve(r),o=ae.relative(n,t);if(o.startsWith("..")||ae.isAbsolute(o))throw new Error(`Path traversal detected: ${e}.`)}function sd(r){return ae.isAbsolute(r)?r:ae.resolve(process.cwd(),r)}function EI(r){return vI.createHash("sha256").update(r).digest("hex")}async function CI(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=EI(r),o=e.sha256.toLowerCase(),i=Buffer.from(n,"hex"),s=Buffer.from(o,"hex");if(i.length!==s.length||!wI(i,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function eg(r){gr(r);let e=`${ot.SKILL_API_BASE}/${r}/install?format=zip`,t=await L.getBinary(e),n=await Kh(r);return await CI(t,n),t}async function PI(r,e,t){gr(t);let n=new yI(r),o=n.getEntries();try{await qt.stat(e)}catch{await qt.mkdir(e,{recursive:!0})}let i=ae.join(e,t);Xh(e,i);for(let s of o){let a=ae.join(i,s.entryName);Xh(i,a)}n.extractAllTo(i,!0)}async function ad(r){let e=ft[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ft).join(", ")}`);let t=ae.join(Qh(),e.path.replace("/skills",""));try{return await qt.access(t),!0}catch{return!1}}function cd(r){let e=ft[r];return ae.join(Qh(),e.path)}function AI(r){let e=ft[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ft).join(", ")}`);return e}function ld(r,e){let t=AI(e),n="projectPath"in t?t.projectPath:ae.join("."+e,"skills");return ae.join(r,n)}async function II(r,e,t){gr(e);let n=ae.join(r,e);try{if(await qt.access(n),t)await qt.rm(n,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${r}.`),{skillDir:n,shouldSkip:!0}}catch{}return{skillDir:n,shouldSkip:!1}}async function dd(r,e,t){await PI(r,e,t),console.log(`Skill ${t} installed to ${ae.join(e,t)}.`)}async function ud(r,e,t){let n=ae.join(e,t);await qt.mkdir(n,{recursive:!0});let o=ae.join(n,ae.basename(r));await qt.copyFile(r,o),console.log(`Skill ${t} installed to ${n}.`)}function tg(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(bI(`Faild to exute operation for skill "${r}": ${n}`)),{success:!1,error:n}}async function Bn(r,e,t,n){try{let o=await e(),{shouldSkip:i}=await II(o,r,n);return i?{success:!0,skipped:!0}:(await t(o),{success:!0})}catch(o){return tg(r,o,"Installation failed")}}async function pd(r,e){try{gr(r);let t=await e(),n=ae.join(t,r);try{await qt.access(n)}catch{return console.log(`Skill ${r} not found in ${t}`),{success:!0,skipped:!0}}return await qt.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}.`),{success:!0}}catch(t){return tg(r,t,"Removal failed")}}async function rg(r,e,t,n=!1){return Bn(r,()=>cd(e),o=>dd(t,o,r),n)}async function ng(r,e,t,n=!1){return Bn(r,()=>t,o=>dd(e,o,r),n)}async function og(r,e,t,n,o=!1){return Bn(r,()=>ld(t,n),i=>dd(e,i,r),o)}async function ig(r,e,t,n=!1){return Bn(r,()=>cd(t),o=>ud(e,o,r),n)}async function sg(r,e,t,n,o=!1){return Bn(r,()=>ld(t,n),i=>ud(e,i,r),o)}async function ag(r,e,t,n=!1){return Bn(r,()=>t,o=>ud(e,o,r),n)}async function md(r,e){return pd(r,()=>cd(e))}async function cg(r,e){return pd(r,()=>e)}async function lg(r,e,t){return pd(r,()=>ld(e,t))}function dg(){let e=ae.dirname(SI(import.meta.url));for(;;){let t=ae.join(e,"SKILL.md");if(Zh.existsSync(t))return t;let n=ae.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import ug from"fs";import{cyan as kI}from"colorette";async function oi(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await ad(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function ii(){let r=[];for(let e of Object.keys(ft))await ad(e)&&r.push(e);return r}function si(r){let e=r.filter(o=>o.success&&!o.skipped).length,t=r.filter(o=>o.skipped).length,n=r.filter(o=>!o.success).length;console.log(),console.log(kI("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function yr(r,e,t){if(!ug.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!ug.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function ai(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?sd(r):void 0,resolvedProject:e?sd(e):void 0}}async function aa(r,e,t){let n=[],o=[],i;if(e?i=e:t&&r.agent?o=(await oi(r.agent)).map(a=>({project:t,agent:a})):t?o=(await ii()).map(a=>({project:t,agent:a})):r.agent?n=await oi(r.agent):n=await ii(),!i&&n.length===0&&o.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:n,projectAgents:o,customPath:i}}var gg="deveco";async function xI(r){let e=await ia();if(r.all)return(await od(e)).map(n=>n.enName);{let n=(await id(r.skill,e)).find(o=>o.enName===r.skill);if(!n)throw new an("errorCode",`Skill "${r.skill}" not found`);return[n.enName]}}async function LI(r,e,t,n){let o=[];if(t.customPath){let i=await ng(r,e,t.customPath,n);return o.push(i),o}for(let i of t.agents){let s=await rg(r,i,e,n);o.push(s)}for(let{project:i,agent:s}of t.projectAgents){let a=await og(r,e,i,s,n);o.push(a)}return o}function NI(r){if(r.all&&r.skill)throw new an("errorCode","`--all` and `--skill` cannot be specified together.");if(!r.all&&!r.skill)throw new an("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=ai(r.path,r.project,r.agent);return t&&yr(t,"Project directory",r.force),e&&yr(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}function OI(r,e,t){return!!(e||t||r.path||r.project||r.agent)}function MI(){return{agents:[gg],projectAgents:[],customPath:void 0}}async function _I(r,e,t){let n=We()&&!OI(r,e,t)?MI():await aa(r,e,t);return{skillNames:await xI(r),targets:n}}async function FI(r,e,t,n){let o=[],i=0,s=r.length,a=RI(5),c=r.map(l=>a(()=>jI(l)));for(let l=0;l<r.length;l++){let d=r[l],g=s>1?` (${l+1}/${s})`:"";n.start(`Installing ${d}${g}...`);let v=await c[l];if(!v.success){n.fail(),console.log(ci(`${d}: Download failed - ${v.error}`)),o.push({success:!1});continue}i+=v.buffer.length,n.stop();let b=await LI(d,v.buffer,e,t);o.push(...b)}return{results:o,diskBytes:i}}async function jI(r){try{let e=await eg(r);return{name:r,buffer:e,success:!0}}catch(e){let t=e instanceof Error?e.message:"unknown error";return{name:r,error:t,success:!1}}}async function $I(r){let e=new Qe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=NI(r),{skillNames:o,targets:i}=await _I(r,t,n),{results:s,diskBytes:a}=await FI(o,i,r.force||!1,e);return e.stop(),si(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function yg(r){let e=r.length,t=r.filter(s=>s.success&&!s.skipped).length,n=r.filter(s=>s.skipped).length,o=r.filter(s=>!s.success).length,i=[...new Set(r.filter(s=>!s.success&&typeof s.error=="string").map(s=>HI(s.error)))];return{opTotal:e,opSuccess:t,opFailed:o,opSkipped:n,...i.length>0?{failedErrors:i}:{}}}function HI(r){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(r.trim());return e?e[1].slice(0,32):"error"}var an=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function UI(r){let e=r;return r instanceof an?r.code:e.code??e.name??"UnknownError"}function la(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 da(r,e,t){let n=Date.now(),o=!0,i=null,s={};try{s=await e()}catch(a){throw o=!1,i=UI(a),a}finally{let a={event:S.SkillOperation,subAction:r,args:t,...s};await I.track(a,{duration_ms:Date.now()-n,success:o,error_code:i})}}function BI(r){return da("add",async()=>{let{diskBytes:e,results:t}=await $I(r);return{diskUsage:de(e),...r.skill?{skillName:r.skill}:{},...yg(t)}},la("add",r))}function WI(r){let{resolvedPath:e,resolvedProject:t}=ai(r.path,r.project,r.agent);return t&&yr(t,"Project directory"),e&&yr(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function VI(r,e){let t=new Qe;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:o}=WI(e);t.stop();let i=await GI(e,r,n,o);return t.stop(),si(i),i}catch(n){throw t.stop(),n}}function pg(r,e=""){if(r.length===0)throw new an("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ca(r,e){let t=[];for(let n of e){let o=n.type==="agent"?await md(r,n.agent):await lg(r,n.project,n.agent);t.push(o)}return t}async function GI(r,e,t,n){if(t)return[await cg(e,t)];if(n&&r.agent){let a=(await oi(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return ca(e,a)}if(n){let s=await ii();pg(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return ca(e,a)}if(r.agent){let a=(await oi(r.agent)).map(c=>({type:"agent",agent:c}));return ca(e,a)}if(We())return[await md(e,gg)];let o=await ii();pg(o,"or use --path for a custom location.");let i=o.map(s=>({type:"agent",agent:s}));return ca(e,i)}var li=new DI("skills").description("Manage HarmonyOS skills");li.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{try{await da("list",async()=>{let e=new Qe;try{e.start("Fetching skills...");let t=await ia(),n=await od(t);if(n.length===0)return e.stop(),console.log(fg("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${n.length} skills`);for(let o of n)if(r.long){console.log(mg(o.enName)),console.log(hg(o.description));let i=Yh(o.enName);i.length>0&&console.log(TI(`Installed for: ${i.join(", ")}`)),console.log()}else console.log(o.enName);return{resultTotal:n.length}}finally{e.stop()}},la("list",r))}catch(e){console.error(ci(e.message)),process.exit(1)}});li.command("find <keyword>").description("Search skills by keyword").action(async r=>{try{await da("find",async()=>{let e=new Qe;try{e.start("Searching skills...");let t=await ia(),n=await id(r,t);if(n.length===0)return console.log(fg(`No skills found matching '${r}'.`)),e.stop(),{resultTotal:0,queryLen:r.length,keyword:r};e.succeed(`Found ${n.length} skills.`);for(let o of n)console.log(mg(o.enName)),console.log(hg(o.description)),console.log();return{resultTotal:n.length,queryLen:r.length,keyword:r}}finally{e.stop()}},la("find"))}catch(e){console.error(ci(e.message)),process.exit(1)}});li.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 r=>{try{await BI(r)}catch(e){console.error(ci(e.message)),process.exit(1)}});li.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 da("remove",async()=>{let e=await VI(r.skill,r);return{skillName:r.skill,...yg(e)}},la("remove",r))}catch(e){console.error(ci(e.message)),process.exit(1)}});var vg=li;import{Command as zI,InvalidArgumentError as ua}from"commander";import{cyan as fd,red as Sg}from"colorette";import qI from"ora";function JI(r){return["log",...r.device?["--device"]:[],...r.crash?["--crash"]:[],...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 YI(r){return{event:S.CommandExecuted,args:JI(r),logType:r.crash?"crash":"common",level:r.level??"ALL",bundleName:r.bundleName??"ALL"}}function KI(r){return r instanceof w?r.traceMessage:r instanceof Error?r.code??r.name:"UnknownError"}async function XI(r,e){let t=Date.now(),n=!0,o=null;try{await e()}catch(i){n=!1,o=KI(i),console.error(Sg(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(r,i).catch(()=>{})}}function ZI(r){try{return E.parsePositiveInteger(r,"tail")}catch{throw new ua("`tail` must be a positive integer.")}}function wg(r,e){try{return E.parseDurationToSeconds(r,e)}catch{throw new ua(`${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 QI(r){try{return E.assertHilogLevel(r),r}catch{throw new ua("`level` must be one of: D, I, W, E, F.")}}function ek(r){try{return E.assertBundleNameStrict(r),r}catch(e){throw new ua(e.message)}}function tk(r){if(r.to&&r.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function rk(r,e,t,n,o){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:o})}function nk(r,e,t,n){let o=E.filterLogsByRelativeWindow(r,t,n);return e.tail?E.getLastLines(o,e.tail):o}var ok=new zI("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(Sg(r))}).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",QI).option("--bundle-name <bundle-name>","Filter by application bundle name",ek).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",ZI).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>wg(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>wg(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await XI(YI(r),()=>ik(r))});async function ik(r){let e=qI({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{tk(r);let n=r.from,o=r.to,i=await k.new(),s=new lr(i),a=await s.selectDevice(r.device);if(!a)throw new w("No active devices found.","No active devices found.");m(fd(`deviceId: ${a}`)),m(fd(`type: ${r.crash?"Crash logs":"Common logs"}`)),m(fd("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await rk(s,a,r,n,o);t(),r.crash&&c&&(c=nk(c,r,n,o)),c&&console.log(c)}finally{t()}}var bg=ok;import ui from"path";import Jt from"fs";import yd from"process";import Rg from"os";import{Command as vk}from"commander";import{green as Ig,red as hd,cyan as wk,yellow as kg}from"colorette";import he from"fs-extra";import B from"path";import*as Cg from"os";import{fileURLToPath as sk}from"url";var Eg={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"}},ak=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function ck(){let r=import.meta.url,e=sk(r);if(e.includes("dist")){let i=B.dirname(e),s=B.dirname(i);return B.join(s,"templates","application")}let t=B.dirname(e),n=B.dirname(t),o=B.dirname(n);return B.join(o,"templates","application")}function Pg(r,e){he.mkdirSync(e,{recursive:!0});for(let t of he.readdirSync(r,{withFileTypes:!0})){let n=B.join(r,t.name),o=B.join(e,t.name);if(t.isDirectory()){Pg(n,o);continue}he.existsSync(o)||(he.mkdirSync(B.dirname(o),{recursive:!0}),he.copyFileSync(n,o))}}function di(r,e){let t=he.readFileSync(r,"utf-8"),n=t;for(let[o,i]of e)n=n.replaceAll(o,i);n!==t&&he.writeFileSync(r,n,"utf-8")}function lk(r){if(Eg[r])return Eg[r];if(r>=26){let e=`${r}.0.0`;return{sdkVersion:e,modelVersion:e}}}function dk(r,e){if(e===22)return;let t=lk(e);t&&(di(B.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),di(B.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),di(B.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function uk(r){return ak.filter(t=>!he.existsSync(B.join(r,t))).length===0}function pk(){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 mk(r){return Cg.platform()==="darwin"?B.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):B.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function fk(r,e){let t=mk(e);if(!he.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[o,i]of n){let s=B.join(t,o),a=B.join(r,i);he.existsSync(s)&&(he.mkdirSync(B.dirname(a),{recursive:!0}),he.copyFileSync(s,a))}return!0}function hk(r){let e=pk(),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 o=B.join(r,n);he.mkdirSync(B.dirname(o),{recursive:!0}),he.writeFileSync(o,e)}}function gk(r,e){e&&fk(r,e)||hk(r)}function yk(r){let e=[B.join(r,"gitignore.txt"),B.join(r,"entry","gitignore.txt")];for(let t of e)if(he.existsSync(t)){let n=B.dirname(t);he.renameSync(t,B.join(n,".gitignore"))}}function Ag(r,e,t,n,o){let i=ck();if(!he.existsSync(i))throw new Error(`Template directory not found: ${i}`);he.mkdirSync(r,{recursive:!0}),Pg(i,r),yk(r),gk(r,o),di(B.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),di(B.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),dk(r,n);let s=uk(r);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function Sk(r){if(r.length<1||r.length>200)throw new ge("errorCode",`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new ge("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function xg(r){if(Rg.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function Dg(r){if(r.length===0)throw new ge("errorCode","Project path cannot be empty.");if(r.length>120)throw new ge("errorCode",`Project path cannot exceed 120 characters (current: ${r.length}).`);let e=Rg.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(r)){let i=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new ge("errorCode",`Project path can only contain ${i}.`)}let n=xg(r);if(/[\u4e00-\u9fff]/.test(n))throw new ge("errorCode","Project path cannot contain Chinese characters.");if(n.endsWith("."))throw new ge("errorCode","Project path cannot end with a dot (.)")}function bk(r){let e=r,t=ui.parse(r).root;for(;e!==t;){if(Jt.existsSync(e))return e;e=ui.dirname(e)}return Jt.existsSync(t)?t:null}function Tg(r){let e=bk(r);if(!e)throw new ge("errorCode",`No existing parent directory found for '${r}'. Cannot create project directory.`);try{Jt.accessSync(e,Jt.constants.W_OK)}catch{throw new ge("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=ui.join(e,`.deveco_write_test_${Date.now()}`);try{Jt.writeFileSync(t,"test"),Jt.unlinkSync(t)}catch{throw new ge("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function Ek(r){return`com.example.${r.toLowerCase()}`}function Ck(r,e){if(e){let o=xg(e),i=ui.resolve(o);if(Jt.existsSync(i)){if(Jt.readdirSync(i).length>0)throw new ge("errorCode",`Directory '${i}' is not empty. Cannot create project here.`)}else Tg(i);return i}let t=yd.cwd(),n=ui.join(t,r);if(Jt.existsSync(n))throw new ge("errorCode",`Directory '${n}' already exists. Cannot create project here.`);return Tg(n),n}function Pk(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let o=Number(r.apiLevel);if(!Number.isInteger(o)||o<17)throw new ge("errorCode",`Invalid API version ${r.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(o>t)throw new ge("errorCode",`Invalid API version ${r.apiLevel}. Your SDK supports API version 17-${t}`)}else if(o>n)throw new ge("errorCode",`Invalid API version ${r.apiLevel}. Without DevEco Studio, supported range is API version 17-${n}`);return o}return t!==void 0?t:23}async function Ak(){try{return await k.new()}catch(r){console.error(kg(`DevEco Studio not found: ${r.message}`)),console.log(kg("Use placeholder API level instead."));return}}var ge=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function gd(r,e,t,n){let o={event:S.CommandExecuted,args:["create"],apiLevel:n?.apiLevel??null},i={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(o,i).catch(()=>{})}function Ik(r){console.log(`
|
|
1298
|
+
`+Ig("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(Ig("Template integrity check passed."))}var kk=new vk("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)").action(async r=>{let e=Date.now();try{r.appName||(console.error(hd("Error: --app-name is required")),await gd(e,!1,"errorCode",r),yd.exit(1));let t=r.appName;Sk(t);let n=r.bundleName||Ek(t);E.assertBundleNameStrict(n),r.projectPath&&Dg(r.projectPath);let o=Ck(t,r.projectPath);Dg(o),console.log(wk("Initializing project...")),console.log(`Project path: ${o}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${n}`);let i=await Ak(),s=Pk(r,i);console.log(`API level: ${s}`);let a=i?.devecoStudioPath,c=Ag(o,t,n,s,a);Ik(c),await gd(e,!0,null,r)}catch(t){let n=t,i=t instanceof ge?t.code:n.code??n.name??"UnknownError";console.error(hd(`
|
|
1299
|
+
Failed to create project.`)),console.error(hd(n.message)),await gd(e,!1,i,r),yd.exit(1)}}),Lg=kk;import{Command as Ok}from"commander";import{red as Mk,cyan as Hg}from"colorette";import Dk from"fs";import pa from"path";import{cyan as Tk}from"colorette";import*as ma from"smol-toml";var Wn=Dk.promises;async function Rk(r){try{let e=await Wn.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 xk(r){try{let e=await Wn.readFile(r,"utf8");return e.trim()===""?{}:ma.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 Lk(r,e){let t=pa.dirname(r);await Wn.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Wn.writeFile(r,n,"utf8")}async function Nk(r,e){let t=pa.dirname(r);await Wn.mkdir(t,{recursive:!0});let n=ma.stringify(e);await Wn.writeFile(r,n,"utf8")}function Ng(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function Og(r,e,t,n,o){(!r[e]||typeof r[e]!="object")&&(r[e]={});let i=r[e];return t in i&&!o?!1:(i[t]=n,!0)}async function Mg(r,e){return r.format==="codex"?xk(e):Rk(e)}async function _g(r,e,t){return r.format==="codex"?Nk(e,t):Lk(e,t)}async function Fg(r,e,t=!1){let n=or[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(or).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 o=await Mg(n,n.globalConfigPath);if(Ng(o,n.mcpServersKey,kt)&&!t)return console.log(`MCP server ${kt} already configured in ${n.globalConfigPath}.`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let i=us(n,void 0);return Og(o,n.mcpServersKey,kt,i,t),await _g(n,n.globalConfigPath,o),console.log(`MCP server ${kt} configured in ${n.globalConfigPath}.`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}async function vd(r,e,t=!1){let n=or[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(or).join(", ")}`};let o=pa.isAbsolute(n.projectConfigPath)?n.projectConfigPath:pa.join(e,n.projectConfigPath);try{let i=await Mg(n,o);if(Ng(i,n.mcpServersKey,kt)&&!t)return console.log(`MCP server ${kt} already configured in ${o}.`),{success:!0,skipped:!0,configPath:o,agentName:r,installType:"project"};let s=us(n,e);return Og(i,n.mcpServersKey,kt,s,t),await _g(n,o,i),console.log(`MCP server ${kt} configured in ${o}.`),{success:!0,configPath:o,agentName:r,installType:"project"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}function jg(r){let e=r.filter(o=>o.success&&!o.skipped).length,t=r.filter(o=>o.skipped).length,n=r.filter(o=>!o.success).length;console.log(),console.log(Tk("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let o of r)!o.success&&o.error&&console.error(` - ${o.agentName??"unknown"}: ${o.error}`);n>0&&(process.exitCode=1)}var wd="deveco-cli";async function _k(r,e,t){if(r.customPath)return[await ag(wd,e,r.customPath,t.force)];let n=[...r.projectAgents.map(({project:s,agent:a})=>()=>sg(wd,e,s,a,t.force)),...r.agents.map(s=>()=>ig(wd,e,s,t.force))],o=5,i=[];for(let s=0;s<n.length;s+=o){let a=n.slice(s,s+o);i.push(...await Promise.all(a.map(c=>c())))}return i}function Fk(r){return[...new Set([...r.agents,...r.projectAgents.map(({agent:e})=>e)])]}async function $g(r,e,t,n){await I.track(r,{duration_ms:Date.now()-e,success:t,error_code:n}).catch(()=>{})}async function jk(r,e,t,n,o){let i={event:S.SkillConfigOperation,subAction:"install",targetType:n?"path":o?"project":"global",agents:Fk(r)},s=Date.now();try{let a=await _k(r,e,t),c=a.every(l=>l.success||l.skipped);return await $g(i,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await $g(i,s,!1,c),a}}async function $k(r,e,t){let n=[];for(let{project:o,agent:i}of r.projectAgents){let s=await vd(i,o,t);n.push(s)}for(let o of r.agents){let i=await vd(o,e,t);n.push(i)}return n}async function Hk(r,e){let t=[];for(let n of r){if(!or[n])continue;let i=await Fg(n,process.cwd(),e);t.push(i)}return t}async function Uk(r,e,t){let n=["qoder","dsh"];if(t.agent){let l=t.agent.split(",").map(d=>d.trim());for(let d of n)if(l.includes(d))throw new Error(`${d} does not support MCP configuration via DevEco CLI. Use --skill instead, or use other supported agents for MCP.`)}let o=t.force??!1,i=r.projectAgents.filter(l=>!n.includes(l.agent)),s=r.agents.filter(l=>!n.includes(l)),a={...r,projectAgents:i,agents:s},c=e?await $k(a,e,o):await Hk(a.agents,o);c.length>0&&(console.log(Hg("MCP Configuration:")),jg(c))}async function Bk(r,e,t){let n={event:S.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},o=Date.now(),i=!0,s=null;try{await Uk(r,e,t)}catch(a){throw i=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-o,success:i,error_code:s};await I.track(n,a)}}async function Wk(r){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}=ai(r.path,r.project,r.agent);t&&yr(t,"Project directory",r.force),e&&yr(e,"Directory",r.force);let n=await aa(r,e,t);if(r.mcp){await Bk(n,t,r);return}let o=dg(),i=await jk(n,o,r,e,t);console.log(),i.length>0&&(console.log(Hg("Skill Installation:")),si(i))}var Vk=new Ok("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","Overwrite existing skill/MCP configuration").action(async r=>{try{await Wk(r)}catch(e){console.error(Mk(e instanceof Error?e.message:String(e))),process.exit(1)}}),Ug=Vk;import{Command as JD}from"commander";import{McpServer as LD}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ND}from"@modelcontextprotocol/sdk/server/stdio.js";import*as vi from"fs";import*as Pr from"path";import{z as ye}from"zod";import fa from"path";function Vg(r,e,t,n,o){if(e.isError)return{};let i=e.content?.[0]?.text??"";if(!i)return{};let s;switch(r){case"check":s=Gk(i);break;case"hover":s={hit:Vn(i)!=null};break;case"definition":case"declaration":s=Bg(i,t,n,o,!0);break;case"references":s=qk(i);break;case"implementation":s=Bg(i,t,n,o,!1);break;case"documentSymbol":s=Jk(i);break;case"callHierarchy":s=Yk(i,t,n,o);break;case"workspaceSymbol":s=Kk(i,t);break;default:s={}}return s}function Gg(r){let e=Array.isArray(r.files)?r.files[0]:r.file;return typeof e!="string"||!e?void 0:fa.extname(e).toLowerCase().replace(/^\./,"")||void 0}function Vn(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 Gk(r){let e={total:0,error:0,warn:0,info:0},t=new Set,n=" => Diagnostic: ";for(let i of r.split(`
|
|
1300
|
+
`)){let s=i.indexOf(n);if(s<0)continue;let a;try{a=JSON.parse(i.slice(s+n.length))}catch{continue}if(Array.isArray(a))for(let c of a)c&&typeof c=="object"&&zk(c,e,t)}let o={diagTotal:e.total,diagError:e.error,diagWarn:e.warn,diagInfo:e.info};return t.size>0&&(o.rules=[...t]),o}function zk(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 qk(r){let e=Vn(r),t=Array.isArray(e)?e:[],n=new Set;for(let o of t){let i=o?.uri;typeof i=="string"&&n.add(i)}return{refTotal:t.length,fileCount:n.size}}function Bg(r,e,t,n,o){let i=Vn(r);if(i==null)return{found:!1};let s=Array.isArray(i)?i:[i],a=s[0]?.uri;return o?{found:!0,sameFile:Xk(a,e),sourceType:qg(a,t,n)}:{implTotal:s.length,found:!0}}function Jk(r){let e=Vn(r),t=Array.isArray(e)?e:[],n=0,o=new Map,i=s=>{for(let a of s){if(!a||typeof a!="object")continue;n++;let c=a.kind;typeof c=="number"&&o.set(c,(o.get(c)??0)+1);let l=a.children;Array.isArray(l)&&i(l)}};return i(t),{symbolTotal:n,kindDist:Sd(o)}}function Yk(r,e,t,n){let i=Vn(r)?.calls,s=Array.isArray(i)?i:[],a=e.direction,c=new Map;for(let l of s){if(!l||typeof l!="object")continue;let g=(a==="incoming"?l.from:l.to)?.uri,v=qg(g,t,n);c.set(v,(c.get(v)??0)+1)}return{callsTotal:s.length,calleeSrcDist:Sd(c)}}function Kk(r,e){let t=Vn(r),n=Array.isArray(t)?t:[],o=new Map,i=0;for(let c of n){if(!c||typeof c!="object")continue;let l=c.kind;typeof l=="number"&&o.set(l,(o.get(l)??0)+1);let d=c.tags;(Array.isArray(d)&&d.includes(1)||c.deprecated===!0)&&i++}let s={resultTotal:n.length,kindDist:Sd(o),deprecatedHit:i},a=e.query;return typeof a=="string"&&(s.queryLen=a.length),s}function zg(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 qg(r,e,t){let n=zg(r);return n?e&&Wg(n,e)?"user_project":t&&Wg(n,t)?"sdk":"system":"unknown"}function Xk(r,e){let t=zg(r),n=e.file;return!t||typeof n!="string"?!1:ha(t)===ha(n)}function ha(r){try{return fa.resolve(r).replace(/\\/g,"/").toLowerCase()}catch{return r.replace(/\\/g,"/").toLowerCase()}}function Wg(r,e){let t=fa.relative(ha(e),ha(r));return t!==""&&!t.startsWith("..")&&!fa.isAbsolute(t)}function Sd(r){let e={};for(let[t,n]of r)e[String(t)]=n;return e}var ga=class{constructor(e,t,n,o){this.telemetry=e;this.getAceServerPid=t;this.getProjectPath=n;this.getSdkPath=o}telemetry;getAceServerPid;getProjectPath;getSdkPath;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 o=>this.invokeTool(t.name,o,n)))}async invokeTool(e,t,n){if(h.info(`[telemetry] mcp tool call: ${e}`),!this.telemetry)return n(t);let o=de(process.memoryUsage().rss),i=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,o,i,a,c)}return l}async trackToolCall(e,t,n,o,i,s,a,c){if(!this.telemetry)return;let l=n?.isError===!0,d=n&&!l?Vg(e,n,t,this.getProjectPath?.()??"",this.getSdkPath?.()??""):{},g=l?!1:a,v=l&&n?Zk(n):c,b={event:S.McpToolCall,subAction:e,mcpMemory:i,lspMemory:s,fileExt:Gg(t),...d};typeof t.direction=="string"&&(b.direction=t.direction),await this.telemetry.track(b,{duration_ms:Date.now()-o,success:g,error_code:v})}async resolveLspMemory(){let e=this.getAceServerPid?.()??null;if(e===null)return"unknown";let t=await $e(e);return t===null?"unknown":de(Number(t)*1024)}};function Zk(r){let e=r.content.map(t=>t.text).join(`
|
|
1301
|
+
`);return/not ready|未初始化|初始中|稍后重试|please retry|retry \d+s|syncing|initializing|初始化失败|C\+\+ project initialization failed/i.test(e)?"NotReady":/No project detected|PROJECT_PATH|工程路径/i.test(e)?"NoProject":/Missing.*parameter|invalid parameters|Unknown feature|must be|不能同时|Must specify|无效/i.test(e)?"BadRequest":/Too many files|Maximum allowed/i.test(e)?"TooManyFiles":/不存在|does not exist|not exist|not found|No valid|不是 \.ets|not a supported|Unsupported/i.test(e)?"InvalidFile":"ToolError"}function bd(r,e,t,n){return new ga(r,e,t,n)}import*as et from"fs";import*as Ie from"path";import{z as Pd}from"zod";function Jg(r){return"method"in r&&!("id"in r)}import{spawn as Qk}from"child_process";import{EventEmitter as eD}from"events";import*as Gn from"fs";import*as Yg from"path";var tD=50*1024*1024,vr=class extends eD{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;get pid(){return this.process?.pid??null}ensureDirectories(){let t=Yg.join(this.config.logPath,"lspLog");return Gn.existsSync(t)||Gn.mkdirSync(t,{recursive:!0}),Gn.existsSync(this.config.indexingDataLocation)||Gn.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let n=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let o=J(n),i=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,this.config.serverPath,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${i.join(" ")}`);let s=process.execPath??"node";f.info(`[LspClient] nodePath: ${s}`),this.process=Qk(s,i,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,n){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(n?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",n=>{this.handleData(n)}),this.process.stderr?.on("data",n=>{let o=n.toString("utf8").trim();f.error(`[LspClient] stderr: ${o}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${o}`))}),this.process.on("exit",n=>{f.info(`[LSP EXIT] code=${n}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${n}`))}))}sendRaw(t,n){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${n}`);let o=this.buildLspMessage(t);this.process.stdin.write(o,"utf8")}send(t,n,o){let i={jsonrpc:"2.0",method:t,params:n};o!==void 0&&(i.id=o),this.sendRaw(JSON.stringify(i),t)}sendNotification(t,n){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:n}),t)}sendRequest(t,n,o){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:o,method:t,params:n}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1302
|
+
\r
|
|
1303
|
+
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
|
|
1304
|
+
\r
|
|
1305
|
+
`);if(n===-1)break;let i=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(i[1],10);if(!Number.isFinite(s)||s<0||s>tD){f.warn(`[LspClient] Invalid Content-Length: ${i[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){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let n=this.process;return!n||n.exitCode!==null||n.signalCode!==null?Promise.resolve():new Promise(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),n.off("exit",a),o())},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 o=0,i=!1,s=!1;for(let a=n;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(n,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var wr=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,n){return new Promise((o,i)=>{let s;n>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${n}ms`))},n),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,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){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let o=this.callbacks.get(e);if(o)try{o(t,n)}finally{this.callbacks.delete(e)}else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,n,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{o()}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 ya=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var zn=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 o of n)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}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(r){return typeof r=="object"&&r!==null}var Kg=20*1e3,rD=30*1e3,Xg=300,nD=300;function oD(){let r=process.env.DEVECO_CLI_LSP_STANDARD_EXIT_TIMEOUT_MS;if(r===void 0||r==="")return Xg;let e=parseInt(r,10);return Number.isFinite(e)?Math.max(nD,e):Xg}var va=class{client;nextRequestId=1;stopOnce=null;callbacks=new zn;requestCallbacks=new wr;diagnosticMap=new Map;initProgressReset=null;get lspPid(){return this.client.pid}constructor(e){this.client=new vr(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()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(oD()),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,n=this.requestCallbacks.registerPending(t,y.INITIALIZE,it);return this.client.sendRequest(y.INITIALIZE,e,t),n}sendInitializeResettable(e,t){let n=this.nextRequestId++,o=this.requestCallbacks.registerPending(n,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,n),new Promise((i,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(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new ya(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,n=rD){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,n);return this.client.sendRequest(e,t,o),i}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.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 o=n instanceof Error?n.message:String(n);f.error(`[LSP] JSON parse error: ${o}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.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 o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(n,o)}else this.requestCallbacks.resolvePending(n,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[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 o=e.diagnostics||[];this.normalizeDiagnostics(o),n.set(o),this.finalizeDiagnostic(t,o)}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){T(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Kg,()=>{let t=this.diagnosticMap.get(e),n=t?t.get():[];this.finalizeDiagnostic(e,n,n.length>0?void 0:`received no diagnostics within ${Kg}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,n){let o={uri:e,diagnostics:t,...n?{errorMessage:n}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),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 o of t)this.finalizeDiagnostic(o,[n]);return}this.broadcastToClients({jsonrpc:R,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var wa=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)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${n}`);return}this.uniqueMessages.add(n),this.messages.push(new Ed(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)}},Ed=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var iD={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"},sD={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",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"},x={...iD,...sD},Sr={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"},Zg=new Set([1e3,2e3,3e3,3001]);function aD(r){if(!T(r))return!1;let e=r.textDocument;return T(e)&&typeof e.uri=="string"}function cD(r){return T(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}function lD(r){return T(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 Sa=class r{client;isInitialized=!1;stopOnce=null;callbacks=new zn;requestCallbacks=new wr;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;get lspPid(){return this.client.pid}constructor(e){this.client=new vr(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()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.EXIT,params:{}}),Sr.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(x.BROADCAST),this.callbacks.register(x.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(x.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(x.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(x.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:R,method:x.INITIALIZED,params:{editors:e}}),Sr.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),Sr.EMPTY)}sendAsyncRequest(e,t,n,o){if(!T(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!aD(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof n!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(n)}`);return}let i=t.textDocument.uri,s=ht(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!cD(n)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),x.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!T(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Sr.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let o=ht(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new wa(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,x.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Sr.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=ht(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,x.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Sr.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=ht(e);f.info(`[LSP] didClose, uri: ${n}`);let o=this.diagnosticMap.get(n);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:x.DID_CLOSE,params:{textDocument:{uri:n}}}),Sr.DID_CLOSE)}getDiagnosticMessage(e){let t=ht(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);f.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 o of t)this.finalizeDiagnostic(o,x.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:R,method:x.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 x.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(x.MODULE_INIT_FINISH),this.callbacks.unregister(x.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case x.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${lD(t.params)}`),this.callbacks.invoke(x.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case x.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case x.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case x.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case x.ON_ASYNC_HOVER:this.handleAsyncResponse(t,x.HOVER);return;case x.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,x.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case x.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,x.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.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){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:R,method:x.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(n);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(n);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let n=e.params;if(!T(n)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let o=n.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,t,n)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,x.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let n=e.version??-1;if(n===-1)return;let o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(n,JSON.stringify(s))}):o.setReceivedType(n),o.hasReceivedAllTypes(Zg)&&this.finalizeDiagnostic(t,x.PUBLISH_DIAGNOSTICS,o.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),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[n]||"Unknown";t.severityStr=i,t.severity=i}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),o=n?n.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${r.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,n,o){let i={uri:e,diagnostics:n,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),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 Cd from"path";import*as ka from"path";var ba=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Ea=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Ca=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Pa=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Aa=class{typeSetting=new Ca;parameterNames=new Pa};var Ia=class{constructor(e,t,n,o){this.rootUri=e;this.lspServerWorkspacePath=J(ka.dirname(t)),this.indexingDataLocation=J(o),this.loggerPath=J(ka.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new ba;gutterIconsSetting=new Ea;inlayHintsSetting=new Aa;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Qg from"path";var pi=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(J(Qg.join(e,"src","main","resources")))}};var dD="OS",qn=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${dD}`;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 pi(e)):this.buildProfileParam=new pi}toString(){return JSON.stringify(this)}};var Jn=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as _e from"path";import*as Xn from"fs";var Da=class{modulePath;dependencies={};dynamicDependencies={}};var cn=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 Yn=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as Yt from"path";import*as Ta from"fs";var Kn=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:Re.OH_PACKAGE_JSON5},mi=`${F.HVIGOR_CACHE}/${F.DEPENDENCY}`,ln=`${F.DEPENDENCY}${F.JSON5}`,xq=Re.SYNC_OUTPUT_PATH;var fi=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 o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new r(e,t,n),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}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=Yt.join(this.dependencyPath,F.OH_PACKAGE_JSON5),n=Xe(t);n&&(this.dependencies=this.getDependencyList(n,F.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,F.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,F.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!T(e))return n;let o=e[t];if(!T(o))return n;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Kn;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,o){if(!(!e||!t))try{let i=Yt.normalize(Yt.join(this.modulePath,F.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=i;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=i;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),Yt.isAbsolute(s)){n.dependencyPath=i;return}o||(i=Yt.resolve(this.modulePath,s)),Ta.existsSync(i)&&Ta.statSync(i).isDirectory()&&(n.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as dn from"fs";import*as br from"path";import uD from"json5";var Ra=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 br.join(this.projectPath,F.OH_MODULES_PATH,F.OHPM_PATH,F.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 o of e)if(!r.checkObjectDepth(o,t,n+1))return!1;return!0}for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&!r.checkObjectDepth(e[o],t,n+1))return!1;return!0}readLockFile(e){if(!dn.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=dn.statSync(e);if(t.size>r.MAX_LOCK_FILE_SIZE)return f.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return f.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=dn.readFileSync(e,"utf8"),n=uD.parse(t);return n?r.checkObjectDepth(n,r.MAX_JSON_DEPTH)?n:(f.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!T(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,F.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,F.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,F.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!T(e))return t;let n=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;let i=e[o];if(!T(i)){f.error(`${o} value is not json object`);continue}if(++n>r.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof i.storePath=="string"&&t.set(o,i.storePath)}return t}getDependencyList(e,t,n){if(!T(e))return[];let o=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++o>r.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[i];if(T(s)){let a=typeof s.name=="string"?s.name:"";if(n==="."&&a===""||a===n)return this.getFinalDependencyList(e,t,i)}}return[]}getFinalDependencyList(e,t,n){let o=e[n];if(!T(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!T(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){f.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:"",v=new Kn;v.name=c,v.version=g.startsWith(r.FILE_DEPENDENCY_PREFIX)?g.substring(r.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(v,n,c,d,g);let b=`${c}@${g}`;this.storePathMap.has(b)&&(v.storePath=this.storePathMap.get(b)||""),i.push(v)}return i}parseDependencyPath(e,t,n,o,i){let s=br.resolve(this.projectPath,br.join(t,F.OH_MODULES_PATH,n));try{let a=i.startsWith(r.FILE_DEPENDENCY_PREFIX)?i.substring(r.FILE_DEPENDENCY_PREFIX.length):i,c=br.isAbsolute(a)?a:br.resolve(this.projectPath,a);dn.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function ey(r){return T(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var un=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new _t(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,n=_e.join(t,mi),o=_e.join(n,ln);if(!Xn.existsSync(n)||!Xn.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new Yn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];if(ey(l)){try{E.assertModuleName(l.name)}catch{f.warn(`[Parser] Skipping module with invalid name: ${l.name}`);continue}this.parseSingleModule(l,n,i,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`)}}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,o=_e.join(n,mi),i=_e.join(o,ln);if(!Xn.existsSync(o)||!Xn.existsSync(i))return f.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 Yn(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!ey(l))continue;let d=l.name;try{E.assertModuleName(d)}catch{f.warn(`[Parser] Skipping module with invalid name: ${d}`);continue}if(s&&!s.has(d))continue;let g=_e.resolve(this.projectPath,l.srcPath),v=_e.join(o,d),b=J(g),N=this.buildModuleDependencies(d,b,v,a);N.moduleName=d,t.push(N)}return t}parseSingleModule(e,t,n,o){let i=e.name,s=_e.resolve(this.projectPath,e.srcPath),a=_e.join(t,i),c=J(s),l=new qn(c),d=this.buildModuleDependencies(i,c,a,n);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new Jn(g),o.push(l)}buildModuleDependencies(e,t,n,o){let i=new Yn(this.projectPath,e,t);fi.getInstance(n,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Da;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let n={},o={};for(let i of e.finalDependencies)n[i.name]=new cn(i);for(let i of e.finalDynamicDependencies)o[i.name]=new cn(i);t.dependencies=n,t.dynamicDependencies=o}parseProjectDependencies(e,t){let n=_e.join(e,F.OH_PACKAGE_JSON5);if(!Xn.existsSync(n))return;fi.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 Ra(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let n=_e.join(e,"src","main","module.json5"),o=Xe(n);if(!T(o)||!T(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}parseRequestPermissions(e){let t=[];if(T(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)T(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=_e.join(e,"src","main","resources","base","profile","main_pages.json"),n=Xe(t);return!T(n)||!Array.isArray(n.src)?[]:n.src.filter(o=>typeof o=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!T(t)||!T(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=_e.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Xe(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 n=t.app.products[0];if(!T(n)||typeof n.compatibleSdkVersion!="string")return;let[o,i]=this.parseBySplit(n.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=_e.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Xe(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let n=e.substring(0,t),o=e.substring(t+1,e.length-1);return[n,o]}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 xa=class{constructor(e=[]){this.valueSet=e}valueSet};var Zn=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var ty=(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))(ty||{}),ry=()=>Object.values(ty).filter(r=>typeof r=="number");var La=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Na=class{applyEdit=!0;workspaceEdit=new La;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new xa(ry());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Zn;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Oa=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Ma=class{constructor(e=[]){this.valueSet=e}valueSet};var _a=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ny=(D=>(D[D.Text=1]="Text",D[D.Method=2]="Method",D[D.Function=3]="Function",D[D.Constructor=4]="Constructor",D[D.Field=5]="Field",D[D.Variable=6]="Variable",D[D.Class=7]="Class",D[D.Interface=8]="Interface",D[D.Module=9]="Module",D[D.Property=10]="Property",D[D.Unit=11]="Unit",D[D.Value=12]="Value",D[D.Enum=13]="Enum",D[D.Keyword=14]="Keyword",D[D.Snippet=15]="Snippet",D[D.Color=16]="Color",D[D.File=17]="File",D[D.Reference=18]="Reference",D[D.Folder=19]="Folder",D[D.EnumMember=20]="EnumMember",D[D.Constant=21]="Constant",D[D.Struct=22]="Struct",D[D.Event=23]="Event",D[D.Operator=24]="Operator",D[D.TypeParameter=25]="TypeParameter",D))(ny||{}),oy=()=>Object.values(ny).filter(r=>typeof r=="number");var Fa=class{completionItemKind=new Ma(oy());completionItem=new _a;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var ja=class{synchronization=new Oa;completion=new Fa;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 Zn;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var $a=class{workspace=new Na;textDocument=new ja;notebookDocument=null;window=null;general=null;experimental=null};var Ha=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};var Ua=class{constructor(e,t,n,o,i,s=!0){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=i;this.useStandardProtocol=s;this.serverPath=Po(t,this.useStandardProtocol),this.logPath=nm(),this.indexLogPath=o||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new va(a):new Sa(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;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){let n=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let o=ht(this.rootUri),i=new Ia(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new un(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=ws(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Ha(o,i,new $a),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,it),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);n=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(n)}async startLegacy(e,t){let n=this.messageHandle;n.sendInitialize(e,1),n.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{n.onIndexingProgressUpdate(i),n.onInitializationCompleted(o)},"LSP initialization",it),n.sendInitialized(t)}withResettableTimeout(e,t,n){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${n}ms`))},n)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,n)=>{let o=T(n)?n:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:R,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new un(this.rootUri,this.sdkPath),o=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=n.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=n.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.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(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,n),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,n){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=n.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,n){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||n(o,e[o])}makeDeleteEntry(e,t){return new cn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new qn(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Jn([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let o=new Map(n.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=En(Cd.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=En(Cd.join(t,"default/openharmony/ets/api")),i=En(Cd.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Jg(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.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"){f.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"){f.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(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Kt from"fs";import*as Ve from"path";import{createHash as mD}from"crypto";import{EventEmitter as fD}from"events";var Ba=class extends fD{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}projectRoot;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 o of t)n.has(o)||this.watchFile(o);for(let o of n)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Kt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Kt.watch(t,n=>{n==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",n=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${n.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(n){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${n instanceof Error?n.message:String(n)}`)}}emitModuleAddedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:n,moduleName:o.name})}}emitModuleRemovedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:n,removedModuleName:o.name})}}emitModuleRenamedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:n,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,n){for(let o of t){let i=Ve.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:n,moduleName:o.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 o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,this.lastModulesSnapshot=s,f.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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,n){let o=this.buildModuleMatchState(n),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(n,o,i),i}buildModuleMatchState(t){let n=new Map,o=new Map;for(let i of t)n.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:o}}matchExactModules(t,n){for(let o of t){let i=n.newBySrc.get(o.srcPath);i&&i.name===o.name&&(n.matchedOld.add(o),n.matchedNew.add(i))}}matchRenamedModules(t,n,o){for(let i of t){if(n.matchedOld.has(i))continue;let s=n.newBySrc.get(i.srcPath);s&&!n.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),n.matchedOld.add(i),n.matchedNew.add(s))}}matchMovedModules(t,n,o){for(let i of t){if(n.matchedOld.has(i))continue;let s=n.newByName.get(i.name);s&&!n.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),n.matchedOld.add(i),n.matchedNew.add(s))}}collectRemovedModules(t,n,o){for(let i of t)n.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,n,o){for(let i of t)n.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=Xe(t);if(typeof n!="object"||n===null)return[];let o=n.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=Ve.join(this.projectRoot,F.OH_PACKAGE_JSON5);Kt.existsSync(n)&&t.push(n);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Ve.resolve(this.projectRoot,i.srcPath),a=Ve.join(s,F.OH_PACKAGE_JSON5);Kt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Ve.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=Kt.readFileSync(t,"utf-8");return mD("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 o=Kt.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}catch(n){f.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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let n=this.debounceTimers.get(t);n&&clearTimeout(n);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Ve.basename(t),relativePath:Ve.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}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(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as Er from"fs";import*as vt from"path";import{createHash as hD}from"crypto";import{EventEmitter as gD}from"events";var Wa=class extends gD{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=vt.join(t,mi)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Er.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Er.watch(this.depMapDir,{recursive:!0},(t,n)=>this.onDirEvent(t,n)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return J(vt.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let o=n.replace(/\\/g,"/"),i;if(o===F.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===ln)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=vt.join(this.depMapDir,n);Er.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,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=vt.join(this.depMapDir,F.OH_PACKAGE_JSON5),n=vt.join(this.depMapDir,ln),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...o.map(s=>({path:(E.assertModuleName(s.name),vt.join(this.depMapDir,s.name,F.OH_PACKAGE_JSON5)),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!Er.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),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=vt.join(this.depMapDir,ln);try{let n=Xe(t);if(typeof n!="object"||n===null)return[];let o=n.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return f.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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of n)o.add(i.info.newName);return o}emitIncrementalReload(t,n,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(n,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return J(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let n=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:n,bySrcPath:o}}detectModuleRenames(t,n,o,i){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"}}),o.add(a.name),i.add(c.name);let l=(E.assertModuleName(a.name),vt.join(this.depMapDir,a.name,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,o,i){for(let[s,a]of t){if(o.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"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,o){for(let[i]of t)o.has(i)||n.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,n,o){for(let[i]of t)if(!o.has(i)&&!n.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=(E.assertModuleName(i),vt.join(this.depMapDir,i,F.OH_PACKAGE_JSON5));this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),n=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(n,i,a,c),this.detectAddedModules(i,n,c),this.detectRemovedModules(n,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=Er.readFileSync(t,"utf-8");return hD("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as yD}from"child_process";var vD=["install","--all"];async function wD(r,e,t,n){return new Promise(o=>{let i=yD(r,[e,...vD],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1295
1306
|
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1296
1307
|
`);o({exitCode:-1,output:l+`
|
|
1297
|
-
`+c.message})})})}function XA(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>m.info("[ohpm] %s",e))}async function ig(n,e,t,r){try{if(!t)return m.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!r)return m.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o,output:i}=await KA(t,r,n,e);return XA(i),o===0?(m.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(m.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),m.error("ohpm \u8F93\u51FA: %s",i),!1)}catch(o){return m.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var sg={UNINITIALIZED:-32099,UNKNOWN:-32e3},ii=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,sg.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,sg.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Gr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=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=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw m.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}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,r,o,i,s){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 a=s?.skipHvigorSync===!0,c=await is(e,async()=>await ig(e,t,r??"",o??"")?a?(m.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await _p(e,t,r??"",i??"")?(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 c.acquired?c.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}`)}if(this.configWatcher=null,this.depMapWatcher=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){let t=new Ca(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)m.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();m.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?ii.uninitialized(t):ii.unknown();this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZATION_FAILED,params:r.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:R,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Pa(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Ia(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){m.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){m.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var ZA=10080*60*1e3,QA=7200*60*1e3,eD=120*1e3,qr=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;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r,o){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=o}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:td.object({files:td.array(td.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}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 o=ge(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{Ic(s,ZA,"[ArkTS-Check]"),Ic(i,QA,"[ArkTS-Check]")}),ls(i);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}`),this.manager=new Gr({sdkPath:l,arktsLangServerPath:t,workspaceRoot:V(o),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),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(et),this.manager.start([]).catch(w=>{let C=w instanceof Error?w:new Error(String(w));this.failInit(C)})})}resolveProjectAndDeveco(){let e=Lt(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=Gi(t);return h.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),{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=Hn(e),o=await Je.promises.readFile(e,"utf8"),s=`deveco.apptool.${Pe.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,o,s):this.checkFileLegacy(t,e,r,o,s)}async checkFileStandard(e,t,r,o){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return tD(i)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,o,i){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"))},eD);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${o.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:o,languageId:i,version:o.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=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1298
|
-
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,t,
|
|
1299
|
-
`).length,i=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:o,character:0}}}));return{content:[{type:"text",text:i==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(i,null,2)}`}]}}catch(
|
|
1300
|
-
`)),t.length>0&&
|
|
1301
|
-
`));let o=
|
|
1302
|
-
`).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.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,
|
|
1303
|
-
`):"No valid C/C++ files"}],isError:!0};for(let c of o){await
|
|
1304
|
-
`)),
|
|
1308
|
+
`+c.message})})})}function SD(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function iy(r,e,t,n){try{if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;if(!n)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:o,output:i}=await wD(t,n,r,e);return SD(i),o===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",o),f.error("ohpm \u8F93\u51FA: %s",i),!1)}catch(o){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",o),!1}}var sy={UNINITIALIZED:-32099,UNKNOWN:-32e3},hi=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,sy.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,sy.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Qn=class{config;lspProxy=null;configWatcher=null;depMapWatcher=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=[]){this.lastEditorOpenFiles=e;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw f.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.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,o,i,s){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let a=s?.skipHvigorSync===!0,c=await fs(e,async()=>await iy(e,t,n??"",o??"")?a?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await cm(e,t,n??"",i??"")?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return c.acquired?c.result:(f.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){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Ua(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?hi.uninitialized(t):hi.unknown();this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:R,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Ba(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Wa(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let n=this.lspProxy.reloadDependenciesOnly(e).map(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:n}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var bD=10080*60*1e3,ED=7200*60*1e3,CD=120*1e3,eo=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;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;documentVersion=0;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,n,o){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=n,this.nodeMaxOldSpaceSize=o}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Pd.object({files:Pd.array(Pd.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}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 o=ve(e),{logPath:i,indexPath:s}=this.getLogAndIndexPath(o);setImmediate(()=>{Bc(s,bD,"[ArkTS-Check]"),Bc(i,ED,"[ArkTS-Check]")}),vs(i);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=${n}`),this.manager=new Qn({sdkPath:l,arktsLangServerPath:t,workspaceRoot:J(o),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:n}),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(it),this.manager.start([]).catch(v=>{let b=v instanceof Error?v:new Error(String(v));this.failInit(b)})})}resolveProjectAndDeveco(){let e=Mt(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=es(t);return h.info(`ArktsCheck protocol: ${n?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${n})`),{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=Gr(e),o=await et.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ie.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,n,o,s):this.checkFileLegacy(t,e,n,o,s)}async checkFileStandard(e,t,n,o){h.debug(`textDocument/didOpen uri=${t} content_len=${n.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:n,languageId:o,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return PD(i)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,n,o,i){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"))},CD);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${n} content_len=${o.length}`),e.onAsyncOpenFile({textDocument:{uri:n,text:o,languageId:i,version:o.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=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1309
|
+
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,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:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let o=r.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){let s=i instanceof Error?i.message:String(i);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.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 h.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(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.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:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let n=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){let o=n instanceof Error?n.message:String(n);return h.error(`handleDocumentSymbol failed: ${o}`),{content:[{type:"text",text:`documentSymbol failed: ${o}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.withOpenFile(t,async i=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:i},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"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){let o=n instanceof Error?n.message:String(n);return h.error(`handleCallHierarchy failed: ${o}`),{content:[{type:"text",text:`callHierarchy failed: ${o}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let n=await this.withOpenFile(t,async i=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:i},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:n==null?"codeAction: no result":`codeAction: ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("codeAction",n)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let n=await this.withOpenFile(t,async i=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:i},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:i},position:s,newName:e.newName})});return{content:[{type:"text",text:n==null?"rename: no result":`rename: ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("rename",n)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let n=await this.fetchTypeHierarchy(t,e.line,e.character,e.direction);return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("typeHierarchy",n)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async fetchTypeHierarchy(e,t,n,o){return this.withOpenFile(e,async i=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:i},position:{line:t,character:n}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=o==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=await this.collectHierarchyItems(c,a);return{items:a,results:l}})}async collectHierarchyItems(e,t){let n=[];for(let o of t){let i=await this.manager.sendFeatureRequest(e,{item:o});Array.isArray(i)?n.push(...i):i&&n.push(i)}return n}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let o=(await et.promises.readFile(t,"utf8")).split(`
|
|
1310
|
+
`).length,i=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:o,character:0}}}));return{content:[{type:"text",text:i==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(i,null,2)}`}]}}catch(n){return this.buildErrorResponse("inlayHint",n)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let n=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:i}}));return{content:[{type:"text",text:n==null?"documentLink: no result":`documentLink: ${JSON.stringify(n,null,2)}`}]}}catch(n){return this.buildErrorResponse("documentLink",n)}}buildErrorResponse(e,t){let n=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${n}`),{content:[{type:"text",text:`${e} failed: ${n}`}],isError:!0}}async withOpenFile(e,t){let n=Gr(e),o=await et.promises.readFile(e,"utf8"),s=`deveco.apptool.${Ie.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${n} len=${o.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,text:o,languageId:s,version:++this.documentVersion}});try{return await t(n)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}resolveSingleFile(e){let t=Ie.isAbsolute(e)?e:Ie.join(this.projectPath,e);return!et.existsSync(t)||!et.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let n=Ie.resolve(this.projectPath),o=[];for(let i of e){let s=Ie.resolve(Ie.isAbsolute(i)?i:Ie.join(n,i));if(!et.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!et.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,n){for(let o of e){await Cp(500);try{let i=await this.checkFile(o);n.push(AD(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let n=[];e.length>0&&n.push(e.join(`
|
|
1311
|
+
`)),t.length>0&&n.push(t.join(`
|
|
1312
|
+
`));let o=n.join(`
|
|
1313
|
+
`).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.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.initResolve&&(this.armInitTimer(it),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";h.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}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"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),n.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;h.debug(`diagnostics received uri=${t} count=${i}`),n.resolve(Array.isArray(o)?o:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Ie.join(tr(),"ArkTSCheck"),n=Ie.join(t,"mapping-config.properties"),o=Pp(e,n),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Ie.join(t,"lsp-log",String(o),i),a=Ie.join(t,"lsp-index",String(o));return et.mkdirSync(s,{recursive:!0}),et.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function PD(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 AD(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 Cr from"fs";import*as pn from"path";import{z as Ad}from"zod";function to(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Va(r,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${r} failed: ${t}`),{content:[{type:"text",text:`${r} failed: ${t}`}],isError:!0}}var ID=500,ro=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:Ad.object({files:Ad.array(Ad.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return to();let t=[],n=[],o=this.collectValidFiles(e.files,t);if(o.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1314
|
+
`):"No valid C/C++ files"}],isError:!0};for(let c of o){await DD(ID);try{let l=await this.checkFile(c);n.push(kD(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let i=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1315
|
+
`)),n.length>0&&s.push(n.join(`
|
|
1305
1316
|
`));let a=s.join(`
|
|
1306
|
-
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Hn(e),r=await wn.promises.readFile(e,"utf8"),o=qi(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=or.resolve(this.manager.projectRoot),o=[];for(let i of e){let s=or.resolve(or.isAbsolute(i)?i:or.join(r,i));if(!wn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!wn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!$n(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(wn.realpathSync(s))}catch{o.push(s)}}return o}};function oD(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 iD(n){return new Promise(e=>setTimeout(e,n))}import*as Kr from"fs";import*as Da from"path";var Yr=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return zr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return Aa(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return zr();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 i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Aa("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return zr();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,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Aa("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Hn(e),o=await Kr.promises.readFile(e,"utf8"),i=qi(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Da.isAbsolute(e)?e:Da.join(this.manager.projectRoot,e);return!Kr.existsSync(t)||!Kr.statSync(t).isFile()||!$n(t)?null:t}};import{spawn as sD}from"child_process";import*as Ta from"fs";import*as ag from"path";var aD=30*1e3,cD=30*1e3,ka=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new fn;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 r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new mn(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,et),m.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),m.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){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 r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},cD);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{m.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.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=${V(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];m.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=sD(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=hr(this.config.workspaceRoot),t=ut(e),r=ag.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.3-Test.1"},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=aD){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);m.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):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 r=t;if(e.error!==void 0&&e.error!==null){let o=e.error;m.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:R,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:m.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:m.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;m.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Ta.existsSync(this.config.logPath)||Ta.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)),ut(r)}}catch{}return e}};import*as si from"path";import*as rd from"fs";var ai=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){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,r,o,i){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(rn(e).length===0)return m.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=i?.skipCompileNative===!0,c=await is(e,a?async()=>(m.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,o));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,r,o){try{return await Hp(e,t,r,o),m.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);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(et);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Lt(this.config.workspaceRoot);this.resolvedRoot=e?ge(e):ge(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();ls(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";m.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=si.dirname(jn(this.resolvedRoot));try{rd.mkdirSync(o,{recursive:!0})}catch(s){m.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}m.info(`[ClangdLspManager] clangdPath: ${r}`),m.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),m.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new ka({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,m.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";m.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){m.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){m.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=si.join(Xt(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=si.join(e,"lsp-log",t);return rd.mkdirSync(r,{recursive:!0}),ge(r)}catch{return"auto"}}};function cg(n){let e=as(n);return m.info(`[SyncGuard] ${e.reason}`),e}var sd=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(sd||{}),lg=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(lg||{}),Tt=3,od=600*1e3,id=100,Ra=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;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;constructor(e={}){this.config=e,Un(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 o=Lt(t);h.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??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,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}`),this.server=new lD({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Zl(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). 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:he.object({target:he.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:he.object({files:he.array(he.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=he.object({file:he.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:he.number().describe("Line number (0-based)"),character:he.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:he.object({query:he.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:he.object({file:he.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:he.object({file:he.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:he.number().describe("Line number (0-based)"),character:he.number().describe("Character offset in the line (0-based)"),direction:he.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=Gi(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}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=b.isPathContainedWithSymlink(i,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1307
|
-
`)}],isError:!0}:null}let
|
|
1308
|
-
`)}],isError:!0}):null}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>
|
|
1317
|
+
`).trim();return!i&&n.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Gr(e),n=await Cr.promises.readFile(e,"utf8"),o=ts(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:n,languageId:o,version:n.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let n=pn.resolve(this.manager.projectRoot),o=[];for(let i of e){let s=pn.resolve(pn.isAbsolute(i)?i:pn.join(n,i));if(!Cr.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!Cr.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!Vr(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(Cr.realpathSync(s))}catch{o.push(s)}}return o}};function kD(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 DD(r){return new Promise(e=>setTimeout(e,r))}import*as oo from"fs";import*as Ga from"path";var no=class r{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return to();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 o=r.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${n} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return Va(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return to();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 n=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:n==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(n,null,2)}`}]}}catch(n){return Va("documentSymbol",n)}}async handleCallHierarchy(e){if(!this.manager.ready)return to();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 n=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(n,null,2)}`}]}}catch(n){return Va("callHierarchy",n)}}async fetchCallHierarchyResult(e,t){let n=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),o=this.normalizeCallHierarchyItems(n);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let n of e)t.push(...await this.fetchIncomingCalls(n));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let n=Gr(e),o=await oo.promises.readFile(e,"utf8"),i=ts(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${n} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:n,text:o,languageId:i,version:o.length}}});try{return await t(n)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:n}}})}}resolveSingleFile(e){let t=Ga.isAbsolute(e)?e:Ga.join(this.manager.projectRoot,e);return!oo.existsSync(t)||!oo.statSync(t).isFile()||!Vr(t)?null:t}};import{spawn as TD}from"child_process";import*as qa from"fs";import*as ay from"path";var RD=30*1e3,xD=30*1e3,za=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new wr;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{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let n={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new vr(n),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,it),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(n){this.lastStartErrorMessage=n instanceof Error?n.message:String(n),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let n=this.diagnosticWaiters.get(t);clearTimeout(n.timer),this.diagnosticWaiters.delete(t)}return new Promise((n,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},xD);this.diagnosticWaiters.set(t,{resolve:n,reject:o,timer:i})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${J(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=TD(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=En(this.config.workspaceRoot),t=ht(e),n=ay.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.3-Test.2"},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=RD){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,n);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(n){let o=n instanceof Error?n.message:String(n);f.error(`[ClangdLspProxy] JSON parse error: ${o}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let n=t;if(e.error!==void 0&&e.error!==null){let o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${n}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(n,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(n,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:R,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,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 o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),n.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{qa.existsSync(this.config.logPath)||qa.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(n)&&(n=n.slice(1)),ht(n)}}catch{}return e}};import*as gi from"path";import*as Id from"fs";var yi=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){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.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,o,i){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(ar(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=i?.skipCompileNative===!0,c=await fs(e,a?async()=>(f.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>r.executeCompileNative(e,t,n,o));return c.acquired?c.result:(f.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,o){try{return await pm(e,t,n,o),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}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=Mt(this.config.workspaceRoot);this.resolvedRoot=e?ve(e):ve(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();vs(t);let n=this.config.clangdPath;if(!n){let s="clangd not found (install DevEco Studio / CLT)";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=gi.dirname(Wr(this.resolvedRoot));try{Id.mkdirSync(o,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${n}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${o}`);let i=new za({clangdPath:n,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let n=this.initResolve;this.clearInitHandlers(),n?.()}else{let n=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${n}`),this.isInitialized=!1,this.proxy=null;let o=this.initReject;this.clearInitHandlers(),o?.(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){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let o=t.params;switch(n){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(n,o)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=gi.join(tr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,n=gi.join(e,"lsp-log",t);return Id.mkdirSync(n,{recursive:!0}),ve(n)}catch{return"auto"}}};function cy(r){let e=gs(r);return f.info(`[SyncGuard] ${e.reason}`),e}var Td=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(Td||{}),ly=(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))(ly||{}),Nt=3,kd=600*1e3,Dd=100,Ja=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;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;constructor(e={}){this.config=e,zr(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,h.info(`Constructor: using configured path as startPath: '${t}'`));let o=Mt(t);h.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??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,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}`),this.server=new LD({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=bd(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). 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:ye.object({target:ye.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:ye.object({files:ye.array(ye.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=ye.object({file:ye.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:ye.number().describe("Line number (0-based)"),character:ye.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:n,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:n,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:ye.object({query:ye.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:ye.object({file:ye.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:ye.object({file:ye.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:ye.number().describe("Line number (0-based)"),character:ye.number().describe("Character offset in the line (0-based)"),direction:ye.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=es(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}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=E.isPathContainedWithSymlink(i,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1318
|
+
`)}],isError:!0}:null}let n=e.filter(o=>Pr.isAbsolute(o));return n.length>0?(h.warn(`Absolute paths rejected (no project root): ${n.join(", ")}`),{content:[{type:"text",text:n.map(o=>`Absolute path is not allowed: ${o}`).join(`
|
|
1319
|
+
`)}],isError:!0}):null}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>Dd)return h.warn(`check tool called with ${t.length} files (max: ${Dd})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Dd}.`}],isError:!0};let{etsFiles:n,cppFiles:o,unsupported:i}=OD(t);i.length>0&&h.warn(`Unsupported file types in check request: ${i.join(", ")}`);let s=i.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];n.length>0&&this.mergeCheckResult(await this.callArktsCheck(n),s,a),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1309
1320
|
`),s.join(`
|
|
1310
1321
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1311
|
-
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${sd[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.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 r=t.file,o=t.line,i=t.character;return typeof r!="string"||typeof o!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:o,character:i});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:o,character:i})})}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,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let o=[],i=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:o.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(o,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",o=t?.location?.range?.start?.line??0,i=t?.location?.range?.start?.character??0;return`${r}:${o}:${i}`}mergeSymbolItems(e,t,r){if(e)for(let o of e){let i=this.symbolDedupKey(o);t.has(i)||(t.add(i),r.push(o))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${Tt})`;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}/${Tt})`;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,r=e.line,o=e.character,i=e.direction;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:i!=="incoming"&&i!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${i})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}))}async handleCodeActionCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:o})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleRenameCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.newName;return!t||typeof i!="string"||i.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0}:this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:o,newName:i}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.direction;return t?i!=="supertypes"&&i!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${i})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:o,direction:i})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,o=e.character;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:o}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${sd[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.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="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.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>=Tt?(h.error(`Init retry limit reached (${this.initRetryCount}/${Tt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Tt}). 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}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Tt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${lg[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.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 h.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,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):$n(e)?this.routeCppRequest(t,r):{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",h.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>=Tt?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Tt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Tt}). 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}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Tt})`),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,r){let o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
|
|
1312
|
-
`);o&&(e.isError?t.push(o):r.push(o))}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 o=this.assertRestartAllowed(r);return o||(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 ~10 seconds.`}]})}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)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{h.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{h.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new dD;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=np();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=Lt(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?Lt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Lt(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()||!await this.ensureProjectSynced())return;this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsCheckTool=new qr(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,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=W(t),o=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,r,o)}}async ensureProjectSynced(){let e=this.config.projectPath,t=cg(e),r=ci.existsSync(vn.join(e,"oh-package-lock.json5")),o=ci.existsSync(vn.join(e,"oh_modules"))&&ci.readdirSync(vn.join(e,"oh_modules")).length>0;if(r&&o)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let i=!t.required;return h.info(`Sync check: skipHvigor=${i}, ohpm install forced (lock=${r}, ohModules=${o}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:i})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await Gr.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=od?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${od/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${r.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}this.cppProjectState=1;let t=rn(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(i=>i.name).join(", ")}`);let r=Vp(e),o=!r.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${o}, reason=${r.reason}`),await this.runSyncCpp(e,{skipCompileNative:o})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new ai({workspaceRoot:e,clangdPath:this.clangdPath??""});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new Jr(this.cppLspManager),this.cppLspTool=new Yr(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 o=W(r),i=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,o,i)}}async trackInit(e,t,r,o,i){if(!this.config.telemetry)return;let s="unknown";if(i!==null){let l=await Qe(i);l!==null&&(s=ue(Number(l)*1024))}let a={event:S.McpToolCall,subAction:e,mcpMemory:ue(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:r,error_code:o};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 ai.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 o=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(o/1e3);return o>=od?(h.error(`[Cpp] C++ sync skipped for ${i}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 ${i}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"),tp(),ep()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function uD(n){let e=[],t=[],r=[];for(let o of n)vn.extname(o).toLowerCase()===".ets"?e.push(o):$n(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function ad(n={}){return new Ra(n)}import*as cd from"fs";import*as li from"path";import{spawn as pD}from"child_process";async function dg(n){Un(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:o,serverMaxSize:i}=await mD(n),s=gD(e,t,r,o,i);h.info("ace-server started, bridging stdio (initialize is left to the client)"),wD(s),await dd(s.pid,ld("--arkts",n))}function ld(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function dd(n,e){let t="unknown";if(n!==null){let o=await Qe(n);o!==null&&(t=ue(Number(o)*1024))}let r={event:S.ServeLsp,args:e,lspMemory:t};await D.track(r)}async function mD(n){let e=await k.new(),t;if(n.projectPath)t=ge(li.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let c=Vi(process.cwd());t=ge(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=ge(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,o=e.arktsLangServerPath;o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let i=vo(o,!0),s=li.join(Xt(),"lsp-server",String(Date.now()));cd.mkdirSync(s,{recursive:!0});let a=fD(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, arktsLangServerPath=${o}, serverPath=${i}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:i,logPath:s,serverMaxSize:a}}function fD(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,o=Number.isFinite(r)&&r>0?r:void 0,i=hD(n,e),s=ds(i,o);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function hD(n,e){try{let t=[];return new rr(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Nt(n).getAllModuleInfo().length}catch{return 0}}function gD(n,e,t,r,o){let i=li.join(e,"lspLog");cd.mkdirSync(i,{recursive:!0});let s=yD(n,i,t,r,o),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),pD(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function yD(n,e,t,r,o){let i=V(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,n,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${V(t)}`,`--sdkPath=${V(r)}`]}function wD(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 ug from"fs";import*as ir from"path";import{spawn as vD}from"child_process";async function pg(n){Un(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await SD(n),o=ir.join(t,"compile_commands.json");ug.existsSync(o)||h.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=ED(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),PD(i),await dd(i.pid,ld("--cpp",n))}async function SD(n){let e=await bD();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(n.projectPath)t=ge(ir.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=Vi(process.cwd());t=ge(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ge(ir.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=e.sdkPath,o=e.clangdPath,i=jn(t),s=ir.dirname(i);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${o}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:o,compileCommandsDir:s}}async function bD(){try{return await k.new()}catch{let n=Ku();if(!n)return null;try{return k.fromIDE(n)}catch{return null}}}function ED(n,e,t){let r=CD(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),vD(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function CD(n){return[`--compile-commands-dir=${V(n)}`,"--log=info","--pch-storage=memory"]}function PD(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 AD(){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",o=n,i=await k.new(),s=ad({projectPath:o,sdkPath:i.sdkPath,arktsLangServerPath:i.arktsLangServerPath??void 0,nodePath:i.nodePath,ohpmJsPath:i.ohpmJsPath,hvigorJsPath:i.hvigorJsPath,clangdPath:i.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:r,telemetry:D}),a,c=new Promise(d=>{a=d}),l=async()=>{await s.shutdown(),a()};process.once("SIGINT",l),process.once("SIGTERM",l),process.platform==="win32"&&process.once("SIGBREAK",l);try{await s.start()}catch(d){console.error("Failed to start MCP server:",d instanceof Error?d.message:String(d)),process.exit(1)}await c}var ud=new ID("serve").description("Host bundled auxiliary protocol servers");ud.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await AD()});ud.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 dg({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await pg({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var mg=ud;import{Command as PT,InvalidArgumentError as Yd}from"commander";import{red as IT,dim as AT}from"colorette";var qt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Sn={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};import*as Di from"fs";import pT from"proper-lockfile";import Oy from"ora";import*as gt from"fs";import*as gi from"path";var Xr="1.9.1",DD=48*1024*1024;var Zr=200,fg=12,hg=4,pd=8,gg=6;var yg=1320,wg=120,vg=450,Sg=250,bg=500,Eg=480,Cg=80,Pg=200,Ig=60,Ag=200;var Dg=200,kg=40,md=500,kD=Object.fromEntries(qt.map((n,e)=>[Sn[n],e])),bn=Object.fromEntries(qt.map((n,e)=>[n,e]));import*as di from"fs";import*as G from"path";import{fileURLToPath as Tg}from"url";var TD="docs";function fd(){return G.join(rt(),TD)}function Ie(){return G.join(fd(),".index")}function xa(){return G.join(Ie(),"build.lock")}function ui(){return G.join(Ie(),"build-status.json")}function Qr(){return G.join(Ie(),"build-meta.json")}function En(){return G.join(Ie(),"search.db")}function eo(){return G.join(Ie(),".tmp")}function RD(n,e){let t=e;for(;!t.endsWith(`${G.sep}dist`)&&t!==G.dirname(t);)t=G.dirname(t);return t}function Rg(n,e){return G.dirname(RD(n,e))}function xg(){let n=Tg(import.meta.url),e=G.dirname(n);return n.includes(`${G.sep}dist${G.sep}`)?Rg(n,e):G.join(e,"..","..","..")}function xD(...n){let e=Tg(import.meta.url),t=G.dirname(e);return e.includes(`${G.sep}dist${G.sep}`)?[G.join(Rg(e,t),...n)]:[G.join(t,"..","..","..",...n)]}function Lg(...n){let e=xg(),t=di.realpathSync(e);for(let r of xD(...n))try{let o=di.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=di.realpathSync(r);if(!Po(i,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function Cn(){return Lg("docs.zip")}function hd(){return Lg("index.zip")}function Ng(){return G.join(xg(),"index","data")}import*as sr from"fs";import*as pi from"path";var zt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],gd=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var Og=null;function LD(){if(Og)return Og;let n=Ie();if(zt.every(o=>sr.existsSync(pi.join(n,o))))return n;let t=Ng();if(zt.every(o=>sr.existsSync(pi.join(t,o))))return t;throw new gd("Lexicon files not found. Install the documentation index first (index.zip).")}function to(n){let e=pi.join(LD(),n);return sr.readFileSync(e,"utf-8")}function Mg(n,e){return sr.readFileSync(pi.join(e,n),"utf-8")}import*as La from"fs";import*as _g from"path";import*as Fg from"yauzl";var mi=null;function ND(n){return new Promise((e,t)=>{Fg.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function OD(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function MD(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=OD(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function _D(){mi?.zipfile.close(),mi=null}async function FD(n){let e=_g.resolve(n),t=await La.promises.stat(e),r=mi;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;_D();let o=await ND(e),i;try{i=await MD(o)}catch(s){throw o.close(),new Error(`Failed to read entries from zip: ${e}`,{cause:s})}return mi={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},mi}function jD(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function $D(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await jD(n.zipfile,e)}finally{r()}}function HD(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function UD(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function yd(n){let e=Cn();if(!e)throw new Error("docs.zip not found");let t=await FD(e),r=UD(t.entries,HD(n));if(!r)throw new Error(`Document not found: ${n}`);return(await $D(t,r)).toString("utf-8")}function wd(){let n=Cn();return n!==null&&La.existsSync(n)}import*as He from"fs";import*as Pn from"path";import jg from"adm-zip";import*as fi from"fs";import*as Oa from"path";var Na=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function no(n){return n instanceof Jn||n instanceof Na||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function bd(n){return new Na(n)}function BD(){return Et(rt())}function Sd(n,e,t){let r=es(n,e);if(r===null)throw bd(`${t} resolves outside the data directory.`);return r}async function vd(n,e){await fi.promises.mkdir(n,{recursive:!0});let t=Sd(n,e,"directory");if(!(await fi.promises.stat(t)).isDirectory())throw bd("path must be a directory.")}function WD(n){let e=BD();try{let t=Sd(n,e,"file");if(!fi.statSync(t).isFile())throw bd("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Sd(Oa.dirname(n),e,"file parent");return}throw t}}async function ro(n={}){let e=n.mode??"write",t=await Cm();await vd(fd(),t),await vd(Ie(),t),e==="write"&&await vd(eo(),t);for(let r of[En(),Qr(),ui(),xa(),...zt.map(o=>Oa.join(Ie(),o))])WD(r)}var Ed=["search.db","build-meta.json",...zt],VD=["corpus.json","corpus-offsets.json","orama.dpack"];async function GD(n){for(let e of VD)await He.promises.rm(Pn.join(n,e),{force:!0})}function $g(n){let t=new jg(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function qD(n){let e=Ie();await He.promises.mkdir(e,{recursive:!0});for(let t of Ed){let r=Pn.join(e,t);await He.promises.rm(r,{force:!0}),await He.promises.rename(Pn.join(n,t),r)}await GD(e),await He.promises.rm(eo(),{recursive:!0,force:!0})}function Hg(n){let e=hd();if(!e)return!1;try{let t=$g(e);return t.indexVersion===Xr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Ug(n){await ro({mode:"write"});let e=hd();if(!e)throw new Error("index.zip not found");let t=$g(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=eo();await He.promises.rm(r,{recursive:!0,force:!0}),await He.promises.mkdir(r,{recursive:!0});let o=new jg(e);for(let s of Ed){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await He.promises.writeFile(Pn.join(r,s),a.getData())}let i=JSON.parse(await He.promises.readFile(Pn.join(r,"build-meta.json"),"utf-8"));if(!He.existsSync(Pn.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await qD(r),i}async function Bg(){await He.promises.rm(eo(),{recursive:!0,force:!0});let n=Ie();for(let e of Ed)await He.promises.rm(Pn.join(n,e),{force:!0})}import{createHash as Wg}from"crypto";import*as Vg from"fs";async function hi(n){return new Promise((e,t)=>{let r=Wg("sha256"),o=Vg.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function Gg(n){return Wg("sha256").update(n,"utf8").digest("hex")}var Cd=null;function zD(){let n=to("harmonyos-synonyms.json");return JSON.parse(n)}function JD(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function YD(){let n=JD(zD()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function KD(){return Cd||(Cd=YD()),Cd}function Pd(n,e){let t=KD(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function qg(n,e){let t=e?Mg(n,e):to(n);return Gg(t)}function Id(n){return qg("harmonyos-synonyms.json",n)}function Ad(n){return qg("harmonyos-terms.txt",n)}var XD={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Ma(){try{let n=await gt.promises.readFile(ui(),"utf-8");return JSON.parse(n)}catch{return{...XD}}}async function Dd(n){let e=ui();await gt.promises.mkdir(gi.dirname(e),{recursive:!0}),await gt.promises.writeFile(e,JSON.stringify(n,null,2))}function zg(n){let e=Date.now();return{state:"installing",phase:1,phaseLabel:"Preparing documentation index",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function yi(n){let t={...await Ma(),...n,updatedAt:Date.now()};return await Dd(t),t}async function kd(){let n=Cn();return n?hi(n):null}async function Td(){try{let n=await gt.promises.readFile(Qr(),"utf-8");return JSON.parse(n)}catch{return null}}async function _a(n=!1){if(n)return"no-index";let e=await Td();if(!e||e.segmentCount===0)return"no-index";let t=await kd();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Xr?"engine-upgraded":e.termsHash!==Ad()?"terms-changed":e.synonymsHash!==Id()?"synonyms-changed":null}function wi(){if(!wd()||!gt.existsSync(En())||!gt.existsSync(Qr()))return!1;let n=gi.dirname(En());if(!zt.every(e=>gt.existsSync(gi.join(n,e))))return!1;try{let e=gt.readFileSync(Qr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Rd(n=!1){return n?!0:wd()?wi()?await _a()!==null:!0:!1}async function Jg(){let n=await Ma();return["installing","indexing","persisting"].includes(n.state)}var Yg=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),xd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Kg=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Xg=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var ZD=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,QD=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,ek=/[A-Z][a-zA-Z0-9]{2,}/g,tk=/@[A-Z][a-zA-Z0-9]*/g,nk=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Zg=6,rk=/^[a-z][a-z0-9]{2,}$/,ok=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,ik=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,sk=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,ak=/^[A-Z][a-zA-Z0-9]+$/;function ck(n){return`"${n.replace(/"/g,'""')}"`}function Si(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(ck).join(` ${e} `)}function vi(n){return Si(n,"OR")}function Qg(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?vi([...t,...r]):`(${vi(t)}) AND (${vi(r)})`}function bi(n){return ik.test(n)}function ey(n){return sk.test(n)&&n.length>=Zg}function lk(n){return ak.test(n)}function Ei(n){return bi(n)||ey(n)||lk(n)}function dk(n){let e=n.trim().toLowerCase();return Xg.has(e)?!1:Yg.has(e)}function uk(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ld(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function ty(n){return[...n.matchAll(ZD)].map(e=>e[0])}function ny(n,e=Zg){let t=[];for(let r of n.matchAll(QD))r[0].length>=e&&t.push(r[0]);return t}function Ci(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function In(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function pk(n){let e=new Set;In(e,n);let t=Ld(n);return t&&In(e,t),Ci([...e])}function Fa(n){if(bi(n))return pk(n);let e=new Set;return In(e,n),Ci([...e])}function ja(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(ok);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!rk.test(r)||Kg.has(r)||!dk(o))return null;let i=uk(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Nd(n){let e=ja(n.trim());return!e||e.second!=="manager"?null:e}function mk(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function ry(n){let e=n.trim(),t=Nd(e);if(t&&xd.has(t.first))return!0;if(ey(e)){let r=mk(e);return r!==null&&xd.has(r)}return!1}function Od(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function Md(n){let e=n.trim();if(Ei(e))return Fa(e);let t=new Set;for(let r of ty(n)){In(t,r);let o=Ld(r);o&&In(t,o)}for(let r of ny(n))In(t,r);for(let r of n.matchAll(tk))t.add(r[0]);for(let r of n.matchAll(nk))t.add(r[0]);for(let r of n.matchAll(ek))r[0].length>=4&&t.add(r[0]);return Ci([...t])}function oy(n){let e=n.trim();if(Ei(e))return Fa(e);let t=new Set,r=ja(e);r&&In(t,r.camelCase);for(let o of Md(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Ci([...t])}function iy(n){return Ei(n)}var te={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function sy(n){return te.pureApiSymbol.test(n.trim())}function Pi(n){let e=n.trim();return te.stageModelExact.test(e)||te.stageModelEnglishExact.test(e)}function ay(n){let e=[];return Pi(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),te.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),te.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function cy(n){return Pi(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var fk=[{matches:n=>te.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Pi(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Pi(n)&&te.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>te.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>te.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>te.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>te.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>te.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>te.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function hk(n,e){for(let{catalog:t,multiplier:r}of e){let o=bn[t];n.set(o,(n.get(o)??1)*r)}}function ly(n,e){for(let t of fk)t.matches(n)&&hk(e,t.weights)}function dy(n,e){if(e!==void 0)return!1;let t=n.trim();return bi(t)||te.pureApiSymbol.test(t)||ry(t)}function uy(n){let e=n.trim();if(bi(e)||te.pureApiSymbol.test(e))return"harmonyos-references";if(Pi(e)||te.uiAbilityLifecycleCatalog.test(e)||te.stateDecoratorCatalog.test(e)||te.stateManagement.test(e)||te.declarePermissionCatalog.test(e)||te.stageModelEntryPage.test(e)||te.routerRoute.test(e)||te.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as gk}from"module";var yk=gk(import.meta.url),$a=null,_d=null,Fd=null;function wk(){if($a)return $a;let n=to("harmonyos-stopwords.txt");return $a=new Set(n.split(`
|
|
1313
|
-
`).map(e=>e.trim()).filter(Boolean))
|
|
1322
|
+
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${Td[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.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,o=t.line,i=t.character;return typeof n!="string"||typeof o!="number"||typeof i!="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:o,character:i});let s=e;return this.cppLspTool.handleLspFeature(s,{file:n,line:o,character:i})})}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 h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let o=[],i=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(n)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:o.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(o,null,2)}`}]}}symbolDedupKey(e){let t=e,n=t?.location?.uri??"",o=t?.location?.range?.start?.line??0,i=t?.location?.range?.start?.character??0;return`${n}:${o}:${i}`}mergeSymbolItems(e,t,n){if(e)for(let o of e){let i=this.symbolDedupKey(o);t.has(i)||(t.add(i),n.push(o))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${Nt})`;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}/${Nt})`;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,o=e.character,i=e.direction;return typeof t!="string"||typeof n!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:i!=="incoming"&&i!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${i})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:n,character:o,direction:i}):this.cppLspTool.handleCallHierarchy({file:t,line:n,character:o,direction:i}))}async handleCodeActionCall(e){let{file:t,line:n,character:o}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:n,character:o})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleRenameCall(e){let{file:t,line:n,character:o}=this.extractPositionArgs(e),i=e.newName;return!t||typeof i!="string"||i.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0}:this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:n,character:o,newName:i}))}async handleTypeHierarchyCall(e){let{file:t,line:n,character:o}=this.extractPositionArgs(e),i=e.direction;return t?i!=="supertypes"&&i!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${i})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:n,character:o,direction:i})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,n=e.line,o=e.character;return typeof t!="string"||typeof n!="number"||typeof o!="number"?{file:null,line:0,character:0}:{file:t,line:n,character:o}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${Td[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.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="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.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>=Nt?(h.error(`Init retry limit reached (${this.initRetryCount}/${Nt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${Nt}). 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}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Nt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${ly[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.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 h.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):Vr(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",h.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>=Nt?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${Nt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${Nt}). 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}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${Nt})`),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 o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
|
|
1323
|
+
`);o&&(e.isError?t.push(o):n.push(o))}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 o=this.assertRestartAllowed(n);return o||(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 ~10 seconds.`}]})}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)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{h.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{h.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new ND;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Dp();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 n=Mt(t);n?(h.info(`Detected project path from client root: ${n}`),this.config.projectPath=n):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 n=t.uri;return this.resolveFileUri(n)}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 n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}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(n=>{h.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=>{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?Mt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Mt(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()||!await this.ensureProjectSynced())return;this.ensureCppProjectReady().catch(t=>{h.warn("Background C++ project init failed:",t)}),this.projectState=3,this.arktsCheckTool=new eo(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});let e=Date.now();try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,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 n=q(t),o=this.arktsCheckTool?.aceServerPid??null;this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5,await this.trackInit("init_arkts",e,!1,n,o)}}async ensureProjectSynced(){let e=this.config.projectPath,t=cy(e),n=vi.existsSync(Pr.join(e,"oh-package-lock.json5")),o=vi.existsSync(Pr.join(e,"oh_modules"))&&vi.readdirSync(Pr.join(e,"oh_modules")).length>0;if(n&&o)return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e,{skipHvigorSync:!1})):(h.info(`Sync skipped: ${t.reason}`),!0);let i=!t.required;return h.info(`Sync check: skipHvigor=${i}, ohpm install forced (lock=${n}, ohModules=${o}), reason=${t.reason}`),this.runSync(e,{skipHvigorSync:i})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let n=await Qn.handleSyncProject(e,this.sdkPath,this.nodePath,this.ohpmJsPath,this.hvigorJsPath,t);switch(n.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=kd?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${n.reason}, resetting to IDLE for retry (elapsed ${i}s / ${kd/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${n.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${n.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}this.cppProjectState=1;let t=ar(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(i=>i.name).join(", ")}`);let n=gm(e),o=!n.required;h.info(`[Cpp] C++ sync check: skipCompileNative=${o}, reason=${n.reason}`),await this.runSyncCpp(e,{skipCompileNative:o})&&await this.initCppLsp(e)}async initCppLsp(e){this.cppProjectState=3,this.cppLspManager=new yi({workspaceRoot:e,clangdPath:this.clangdPath??""});let t=Date.now();try{await this.cppLspManager.start(),this.cppCheckTool=new ro(this.cppLspManager),this.cppLspTool=new no(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(n){h.error("[Cpp] C++ LSP initialization failed:",n);let o=q(n),i=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,o,i)}}async trackInit(e,t,n,o,i){if(!this.config.telemetry)return;let s="unknown";if(i!==null){let l=await $e(i);l!==null&&(s=de(Number(l)*1024))}let a={event:S.McpToolCall,subAction:e,mcpMemory:de(process.memoryUsage().rss),lspMemory:s},c={duration_ms:Date.now()-t,success:n,error_code:o};await this.config.telemetry.track(a,c).catch(()=>{})}async runSyncCpp(e,t){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let n=await yi.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 o=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(o/1e3);return o>=kd?(h.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${n.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return h.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){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),kp(),Ip()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function OD(r){let e=[],t=[],n=[];for(let o of r)Pr.extname(o).toLowerCase()===".ets"?e.push(o):Vr(o)?t.push(o):n.push(o);return{etsFiles:e,cppFiles:t,unsupported:n}}function Rd(r={}){return new Ja(r)}import*as xd from"fs";import*as wi from"path";import{spawn as MD}from"child_process";async function dy(r){zr(!1);let{serverPath:e,logPath:t,projectPath:n,sdkPath:o,serverMaxSize:i}=await _D(r),s=$D(e,t,n,o,i);h.info("ace-server started, bridging stdio (initialize is left to the client)"),UD(s),await Nd(s.pid,Ld("--arkts",r))}function Ld(r,e){return[r,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function Nd(r,e){let t="unknown";if(r!==null){let o=await $e(r);o!==null&&(t=de(Number(o)*1024))}let n={event:S.ServeLsp,args:e,lspMemory:t};await I.track(n)}async function _D(r){let e=await k.new(),t;if(r.projectPath)t=ve(wi.resolve(r.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(r.autoDetect){let c=Qi(process.cwd());t=ve(c??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${c??"null, fallback to cwd"}`)}else t=ve(process.cwd()),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let n=e.sdkPath,o=e.arktsLangServerPath;o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let i=Po(o,!0),s=wi.join(tr(),"lsp-server",String(Date.now()));xd.mkdirSync(s,{recursive:!0});let a=FD(t,n);return h.info(`projectPath=${t}, sdkPath=${n}, arktsLangServerPath=${o}, serverPath=${i}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:n,serverPath:i,logPath:s,serverMaxSize:a}}function FD(r,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=t?parseInt(t,10):NaN,o=Number.isFinite(n)&&n>0?n:void 0,i=jD(r,e),s=ws(i,o);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function jD(r,e){try{let t=[];return new un(r,e).getAllDependencyMap(t).status==="OK"?t.length:new _t(r).getAllModuleInfo().length}catch{return 0}}function $D(r,e,t,n,o){let i=wi.join(e,"lspLog");xd.mkdirSync(i,{recursive:!0});let s=HD(r,i,t,n,o),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),MD(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function HD(r,e,t,n,o){let i=J(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,r,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${J(t)}`,`--sdkPath=${J(n)}`]}function UD(r){r.on("error",e=>{h.error(`[ace-server] spawn error: ${e.message}`),process.exit(1)}),r.stdout?.on("error",e=>{h.error(`[ace-server] stdout error: ${e.message}`)}),r.stdout?.on("data",e=>process.stdout.write(e)),r.stderr?.on("error",e=>{h.error(`[ace-server] stderr error: ${e.message}`)}),r.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),r.stdin?.on("error",e=>{h.error(`[ace-server] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{r.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),r.kill(),process.exit(0)}),r.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as uy from"fs";import*as mn from"path";import{spawn as BD}from"child_process";async function py(r){zr(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:n}=await WD(r),o=mn.join(t,"compile_commands.json");uy.existsSync(o)||h.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=GD(e,t,n);h.info("clangd started, bridging stdio (initialize is left to the client)"),qD(i),await Nd(i.pid,Ld("--cpp",r))}async function WD(r){let e=await VD();e?.clangdPath||(h.error("clangd not found. Ensure DevEco Studio / CLT is installed."),process.exit(1));let t;if(r.projectPath)t=ve(mn.resolve(r.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(r.autoDetect){let a=Qi(process.cwd());t=ve(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ve(mn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let n=e.sdkPath,o=e.clangdPath,i=Wr(t),s=mn.dirname(i);return h.info(`projectPath=${t}, sdkPath=${n}, clangdPath=${o}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:o,compileCommandsDir:s}}async function VD(){try{return await k.new()}catch{let r=Ep();if(!r)return null;try{return k.fromIDE(r)}catch{return null}}}function GD(r,e,t){let n=zD(e);return h.info(`[serve-lsp-cpp] spawn: ${r} ${n.join(" ")}`),BD(r,n,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function zD(r){return[`--compile-commands-dir=${J(r)}`,"--log=info","--pch-storage=memory"]}function qD(r){r.on("error",e=>{h.error(`[clangd] spawn error: ${e.message}`),process.exit(1)}),r.stdout?.on("error",e=>{h.error(`[clangd] stdout error: ${e.message}`)}),r.stdout?.on("data",e=>process.stdout.write(e)),r.stderr?.on("error",e=>{h.error(`[clangd] stderr error: ${e.message}`)}),r.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),r.stdin?.on("error",e=>{h.error(`[clangd] stdin error: ${e.message}`)}),process.stdin.on("data",e=>{r.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),r.kill(),process.exit(0)}),r.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function YD(){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",o=r,i=await k.new(),s=Rd({projectPath:o,sdkPath:i.sdkPath,arktsLangServerPath:i.arktsLangServerPath??void 0,nodePath:i.nodePath,ohpmJsPath:i.ohpmJsPath,hvigorJsPath:i.hvigorJsPath,clangdPath:i.clangdPath??void 0,nodeMaxOldSpaceSize:e,debug:t,cppEnabled:n,telemetry:I}),a,c=new Promise(d=>{a=d}),l=async()=>{await s.shutdown(),a()};process.once("SIGINT",l),process.once("SIGTERM",l),process.platform==="win32"&&process.once("SIGBREAK",l);try{await s.start()}catch(d){console.error("Failed to start MCP server:",d instanceof Error?d.message:String(d)),process.exit(1)}await c}var Od=new JD("serve").description("Host bundled auxiliary protocol servers");Od.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await YD()});Od.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 dy({projectPath:r.projectPath,autoDetect:r.autoDetect}):r.cpp?await py({projectPath:r.projectPath,autoDetect:r.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var my=Od;import{Command as qR,InvalidArgumentError as vu}from"commander";import{red as JR,dim as YR}from"colorette";var Xt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Ar={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};import*as Fi from"fs";import MR from"proper-lockfile";import Ov from"ora";import*as wt from"fs";import*as Ii from"path";var io="1.9.1",KD=48*1024*1024;var so=200,fy=12,hy=4,Md=8,gy=6;var yy=1320,vy=120,wy=450,Sy=250,by=500,Ey=480,Cy=80,Py=200,Ay=60,Iy=200;var ky=200,Dy=40,_d=500,XD=Object.fromEntries(Xt.map((r,e)=>[Ar[r],e])),Ir=Object.fromEntries(Xt.map((r,e)=>[r,e]));import*as Si from"fs";import*as Y from"path";import{fileURLToPath as Ty}from"url";var ZD="docs";function Fd(){return Y.join(lt(),ZD)}function ke(){return Y.join(Fd(),".index")}function Ya(){return Y.join(ke(),"build.lock")}function bi(){return Y.join(ke(),"build-status.json")}function ao(){return Y.join(ke(),"build-meta.json")}function kr(){return Y.join(ke(),"search.db")}function co(){return Y.join(ke(),".tmp")}function QD(r,e){let t=e;for(;!t.endsWith(`${Y.sep}dist`)&&t!==Y.dirname(t);)t=Y.dirname(t);return t}function Ry(r,e){return Y.dirname(QD(r,e))}function xy(){let r=Ty(import.meta.url),e=Y.dirname(r);return r.includes(`${Y.sep}dist${Y.sep}`)?Ry(r,e):Y.join(e,"..","..","..")}function eT(...r){let e=Ty(import.meta.url),t=Y.dirname(e);return e.includes(`${Y.sep}dist${Y.sep}`)?[Y.join(Ry(e,t),...r)]:[Y.join(t,"..","..","..",...r)]}function Ly(...r){let e=xy(),t=Si.realpathSync(e);for(let n of eT(...r))try{let o=Si.lstatSync(n);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${r.join("/")} must be a regular file.`);let i=Si.realpathSync(n);if(!To(i,t))throw new Error(`Unsafe documentation package asset: ${r.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function Dr(){return Ly("docs.zip")}function jd(){return Ly("index.zip")}function Ny(){return Y.join(xy(),"index","data")}import*as fn from"fs";import*as Ei from"path";var Zt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],$d=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var Oy=null;function tT(){if(Oy)return Oy;let r=ke();if(Zt.every(o=>fn.existsSync(Ei.join(r,o))))return r;let t=Ny();if(Zt.every(o=>fn.existsSync(Ei.join(t,o))))return t;throw new $d("Lexicon files not found. Install the documentation index first (index.zip).")}function lo(r){let e=Ei.join(tT(),r);return fn.readFileSync(e,"utf-8")}function My(r,e){return fn.readFileSync(Ei.join(e,r),"utf-8")}import*as Ka from"fs";import*as _y from"path";import*as Fy from"yauzl";var Ci=null;function rT(r){return new Promise((e,t)=>{Fy.open(r,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(n,o)=>{if(n||!o){t(n??new Error(`Failed to open zip: ${r}`));return}e(o)})})}function nT(r){let e=r.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function oT(r){let e=new Map;return new Promise((t,n)=>{r.readEntry(),r.on("entry",o=>{let i=nT(o);i.endsWith("/")||e.set(i,o),r.readEntry()}),r.on("end",()=>{t(e)}),r.on("error",n)})}function iT(){Ci?.zipfile.close(),Ci=null}async function sT(r){let e=_y.resolve(r),t=await Ka.promises.stat(e),n=Ci;if(n&&n.zipPath===e&&n.mtimeMs===t.mtimeMs&&n.size===t.size)return n;iT();let o=await rT(e),i;try{i=await oT(o)}catch(s){throw o.close(),new Error(`Failed to read entries from zip: ${e}`,{cause:s})}return Ci={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},Ci}function aT(r,e){return new Promise((t,n)=>{r.openReadStream(e,(o,i)=>{if(o||!i){n(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",n)})})}async function cT(r,e){let t=r.readChain,n;r.readChain=new Promise(o=>{n=o}),await t;try{return await aT(r.zipfile,e)}finally{n()}}function lT(r){let e=r.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function dT(r,e){for(let t of e){let n=r.get(t.replace(/\\/g,"/"));if(n)return n}return null}async function Hd(r){let e=Dr();if(!e)throw new Error("docs.zip not found");let t=await sT(e),n=dT(t.entries,lT(r));if(!n)throw new Error(`Document not found: ${r}`);return(await cT(t,n)).toString("utf-8")}function Ud(){let r=Dr();return r!==null&&Ka.existsSync(r)}import*as Ge from"fs";import*as Tr from"path";import jy from"adm-zip";import*as Pi from"fs";import*as Za from"path";var Xa=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function uo(r){return r instanceof rn||r instanceof Xa||r instanceof Error&&(r.name==="CliDataDirError"||r.name==="DocPathSafetyError")}function Vd(r){return new Xa(r)}function uT(){return At(lt())}function Wd(r,e,t){let n=ls(r,e);if(n===null)throw Vd(`${t} resolves outside the data directory.`);return n}async function Bd(r,e){await Pi.promises.mkdir(r,{recursive:!0});let t=Wd(r,e,"directory");if(!(await Pi.promises.stat(t)).isDirectory())throw Vd("path must be a directory.")}function pT(r){let e=uT();try{let t=Wd(r,e,"file");if(!Pi.statSync(t).isFile())throw Vd("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Wd(Za.dirname(r),e,"file parent");return}throw t}}async function po(r={}){let e=r.mode??"write",t=await Cf();await Bd(Fd(),t),await Bd(ke(),t),e==="write"&&await Bd(co(),t);for(let n of[kr(),ao(),bi(),Ya(),...Zt.map(o=>Za.join(ke(),o))])pT(n)}var Gd=["search.db","build-meta.json",...Zt],mT=["corpus.json","corpus-offsets.json","orama.dpack"];async function fT(r){for(let e of mT)await Ge.promises.rm(Tr.join(r,e),{force:!0})}function $y(r){let t=new jy(r).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function hT(r){let e=ke();await Ge.promises.mkdir(e,{recursive:!0});for(let t of Gd){let n=Tr.join(e,t);await Ge.promises.rm(n,{force:!0}),await Ge.promises.rename(Tr.join(r,t),n)}await fT(e),await Ge.promises.rm(co(),{recursive:!0,force:!0})}function Hy(r){let e=jd();if(!e)return!1;try{let t=$y(e);return t.indexVersion===io&&t.docsZipSha256===r&&t.segmentCount>0}catch{return!1}}async function Uy(r){await po({mode:"write"});let e=jd();if(!e)throw new Error("index.zip not found");let t=$y(e);if(t.docsZipSha256!==r)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let n=co();await Ge.promises.rm(n,{recursive:!0,force:!0}),await Ge.promises.mkdir(n,{recursive:!0});let o=new jy(e);for(let s of Gd){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Ge.promises.writeFile(Tr.join(n,s),a.getData())}let i=JSON.parse(await Ge.promises.readFile(Tr.join(n,"build-meta.json"),"utf-8"));if(!Ge.existsSync(Tr.join(n,"search.db")))throw new Error("index.zip is missing search.db");return await hT(n),i}async function By(){await Ge.promises.rm(co(),{recursive:!0,force:!0});let r=ke();for(let e of Gd)await Ge.promises.rm(Tr.join(r,e),{force:!0})}import{createHash as Wy}from"crypto";import*as Vy from"fs";async function Ai(r){return new Promise((e,t)=>{let n=Wy("sha256"),o=Vy.createReadStream(r);o.on("data",i=>n.update(i)),o.on("error",t),o.on("end",()=>e(n.digest("hex")))})}function Gy(r){return Wy("sha256").update(r,"utf8").digest("hex")}var zd=null;function gT(){let r=lo("harmonyos-synonyms.json");return JSON.parse(r)}function yT(r){let e=new Map;for(let t of r){let n=t.map(o=>o.trim()).filter(Boolean);for(let o of n){let i=n.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function vT(){let r=yT(gT()),e=new Map;for(let[t,n]of r)e.set(t,new Set(n));return e}function wT(){return zd||(zd=vT()),zd}function qd(r,e){let t=wT(),n=r.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:n.length;for(let s=0;s<n.length&&o.size<i;s+=1){let a=n[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function zy(r,e){let t=e?My(r,e):lo(r);return Gy(t)}function Jd(r){return zy("harmonyos-synonyms.json",r)}function Yd(r){return zy("harmonyos-terms.txt",r)}var ST={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Qa(){try{let r=await wt.promises.readFile(bi(),"utf-8");return JSON.parse(r)}catch{return{...ST}}}async function Kd(r){let e=bi();await wt.promises.mkdir(Ii.dirname(e),{recursive:!0}),await wt.promises.writeFile(e,JSON.stringify(r,null,2))}function qy(r){let e=Date.now();return{state:"installing",phase:1,phaseLabel:"Preparing documentation index",current:0,total:0,message:r,startedAt:e,updatedAt:e,error:null}}async function ki(r){let t={...await Qa(),...r,updatedAt:Date.now()};return await Kd(t),t}async function Xd(){let r=Dr();return r?Ai(r):null}async function Zd(){try{let r=await wt.promises.readFile(ao(),"utf-8");return JSON.parse(r)}catch{return null}}async function ec(r=!1){if(r)return"no-index";let e=await Zd();if(!e||e.segmentCount===0)return"no-index";let t=await Xd();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==io?"engine-upgraded":e.termsHash!==Yd()?"terms-changed":e.synonymsHash!==Jd()?"synonyms-changed":null}function Di(){if(!Ud()||!wt.existsSync(kr())||!wt.existsSync(ao()))return!1;let r=Ii.dirname(kr());if(!Zt.every(e=>wt.existsSync(Ii.join(r,e))))return!1;try{let e=wt.readFileSync(ao(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Qd(r=!1){return r?!0:Ud()?Di()?await ec()!==null:!0:!1}async function Jy(){let r=await Qa();return["installing","indexing","persisting"].includes(r.state)}var Yy=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),eu=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Ky=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Xy=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var bT=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,ET=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,CT=/[A-Z][a-zA-Z0-9]{2,}/g,PT=/@[A-Z][a-zA-Z0-9]*/g,AT=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Zy=6,IT=/^[a-z][a-z0-9]{2,}$/,kT=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,DT=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,TT=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,RT=/^[A-Z][a-zA-Z0-9]+$/;function xT(r){return`"${r.replace(/"/g,'""')}"`}function Ri(r,e){let t=[...new Set(r.filter(Boolean))];return t.length===0?'""':t.map(xT).join(` ${e} `)}function Ti(r){return Ri(r,"OR")}function Qy(r,e){let t=[...new Set(r.filter(Boolean))],n=[...new Set(e.filter(Boolean))];return t.length===0||n.length===0?Ti([...t,...n]):`(${Ti(t)}) AND (${Ti(n)})`}function xi(r){return DT.test(r)}function ev(r){return TT.test(r)&&r.length>=Zy}function LT(r){return RT.test(r)}function Li(r){return xi(r)||ev(r)||LT(r)}function NT(r){let e=r.trim().toLowerCase();return Xy.has(e)?!1:Yy.has(e)}function OT(r,e){let t=e.trim().charAt(0).toUpperCase(),n=e.trim().slice(1).toLowerCase();return`${r.trim().toLowerCase()}${t}${n}`}function tu(r){let t=r.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function tv(r){return[...r.matchAll(bT)].map(e=>e[0])}function rv(r,e=Zy){let t=[];for(let n of r.matchAll(ET))n[0].length>=e&&t.push(n[0]);return t}function Ni(r){return r.filter(e=>{let t=e.toLowerCase();return!r.some(n=>{if(n===e)return!1;let o=n.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function Rr(r,e){let t=e.trim();if(!t)return;r.add(t);let n=t.toLowerCase();n!==t&&r.add(n)}function MT(r){let e=new Set;Rr(e,r);let t=tu(r);return t&&Rr(e,t),Ni([...e])}function tc(r){if(xi(r))return MT(r);let e=new Set;return Rr(e,r),Ni([...e])}function rc(r){let e=r.trim();if(/[A-Z]/.test(e))return null;let t=e.match(kT);if(!t)return null;let n=t[1].toLowerCase(),o=t[2].toLowerCase();if(!IT.test(n)||Ky.has(n)||!NT(o))return null;let i=OT(n,o);return{first:n,second:o,camelCase:i,lower:i.toLowerCase()}}function ru(r){let e=rc(r.trim());return!e||e.second!=="manager"?null:e}function _T(r){let e=r.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function nv(r){let e=r.trim(),t=ru(e);if(t&&eu.has(t.first))return!0;if(ev(e)){let n=_T(e);return n!==null&&eu.has(n)}return!1}function nu(r,e,t){let n=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[r,e])if(i&&(i.toLowerCase().includes(n)||o.test(i)))return!0;return!1}function ou(r){let e=r.trim();if(Li(e))return tc(e);let t=new Set;for(let n of tv(r)){Rr(t,n);let o=tu(n);o&&Rr(t,o)}for(let n of rv(r))Rr(t,n);for(let n of r.matchAll(PT))t.add(n[0]);for(let n of r.matchAll(AT))t.add(n[0]);for(let n of r.matchAll(CT))n[0].length>=4&&t.add(n[0]);return Ni([...t])}function ov(r){let e=r.trim();if(Li(e))return tc(e);let t=new Set,n=rc(e);n&&Rr(t,n.camelCase);for(let o of ou(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Ni([...t])}function iv(r){return Li(r)}var oe={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function sv(r){return oe.pureApiSymbol.test(r.trim())}function Oi(r){let e=r.trim();return oe.stageModelExact.test(e)||oe.stageModelEnglishExact.test(e)}function av(r){let e=[];return Oi(r.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),oe.declarePermissionTokens.test(r)&&e.push("\u58F0\u660E\u6743\u9650"),oe.stageModelEntryPage.test(r)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(r)&&/生命周期/.test(r)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function cv(r){return Oi(r)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var FT=[{matches:r=>oe.uiAbilityLifecycleBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:r=>Oi(r),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:r=>!Oi(r)&&oe.stageModel.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:r=>oe.entryAbilityPage.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:r=>oe.declarePermissionBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:r=>oe.stateDecoratorBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:r=>oe.stateManagement.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:r=>oe.routerRoute.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:r=>oe.dialogPopupBoost.test(r),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function jT(r,e){for(let{catalog:t,multiplier:n}of e){let o=Ir[t];r.set(o,(r.get(o)??1)*n)}}function lv(r,e){for(let t of FT)t.matches(r)&&jT(e,t.weights)}function dv(r,e){if(e!==void 0)return!1;let t=r.trim();return xi(t)||oe.pureApiSymbol.test(t)||nv(t)}function uv(r){let e=r.trim();if(xi(e)||oe.pureApiSymbol.test(e))return"harmonyos-references";if(Oi(e)||oe.uiAbilityLifecycleCatalog.test(e)||oe.stateDecoratorCatalog.test(e)||oe.stateManagement.test(e)||oe.declarePermissionCatalog.test(e)||oe.stageModelEntryPage.test(e)||oe.routerRoute.test(e)||oe.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as $T}from"module";var HT=$T(import.meta.url),nc=null,iu=null,su=null;function UT(){if(nc)return nc;let r=lo("harmonyos-stopwords.txt");return nc=new Set(r.split(`
|
|
1324
|
+
`).map(e=>e.trim()).filter(Boolean)),nc}function BT(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t]?.trim();if(!n)continue;let o=r[t+1]?.trim();if(n==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(n)}return e}function pv(r){let e=UT(),t=[];for(let n of BT(r)){let o=n.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function WT(){let{cut:r,cut_for_search:e,with_dict:t}=HT("jieba-wasm"),n=lo("harmonyos-terms.txt");return t(n),m("doc-index: using jieba-wasm backend"),{cut:(o,i)=>r(o,i),cutForSearch:(o,i)=>e(o,i)}}async function Mi(){return iu||(su||(su=WT().then(r=>(iu=r,r))),su)}async function VT(r){let e=await Mi();return pv(e.cutForSearch(r,!0))}async function mv(r){let e=await Mi();return pv(e.cut(r,!0))}async function oc(r,e){let t=r.trim();if(!t||e<=0)return"";let n=(await VT(t)).join(" ");return n.length<=e?n:n.slice(0,e)}async function GT(r,e){let t=[];for(let o of r){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let n=[...new Set(t)].join(" ");return n.length<=e?n:n.slice(0,e)}async function fv(r){let e=!!r.sectionTitle.trim(),t=r.titleTokens.trim(),n=e?Ey:yy,o=e?Py:wy,i=e?await GT(r.apiSymbols,o):await oc(r.apiSymbols.join(" "),o),a=(await Promise.all([oc(t,e?Cy:vy),Promise.resolve(i),oc(r.headingsText,e?Ay:Sy),oc(r.bodySample,e?Iy:by)])).filter(Boolean).join(" ");return a.length<=n?a:a.slice(0,n)}function zT(r){return r.join(" ").replace(/\s+/g," ").trim().slice(0,so)}function au(r,e){let t=new Set,n=[];for(let o of[...r,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),n.push(o),n.length>=fy))break}return n}function qT(r){return r.length>=2&&r.length<=hy}function JT(r,e){let t=qd(r,Md),n=t.split(/\s+/).filter(Boolean),o=[e.first,...n.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=au(o,i);return{rawQuery:r,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Qy(o,i)}}function YT(r,e){let t=au(tc(e),[]);return{rawQuery:r,expandedQuery:r,tokens:t,preferAnd:!1,ftsMatch:Ti(t)}}async function hv(r){let e=zT(r),t=e.trim(),n=cv(t);if(n)return{rawQuery:e,expandedQuery:n.expandedQuery,tokens:n.tokens,preferAnd:!1};let o=rc(t);if(o)return JT(e,o);if(Li(t))return YT(e,t);let i=av(e),s=[...ou(e),...i],c=iv(t)?e:qd(e,Md),l=await mv(c),d=au(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&qT(d)}}var gv=["harmonyos-releases","harmonyos-roadmap"],KT=new Set(gv.map(r=>Ir[r])),XT=gv.map(r=>`${Ar[r]}/`);function ZT(r){return KT.has(r)}function QT(r){return XT.some(e=>r.startsWith(e))}function yv(r){let e=[],t=[];for(let n of r)ZT(n.catalog_id)?t.push(n):e.push(n);return[...e,...t]}function vv(r){let e=[],t=[];for(let n of r)QT(n.documentId)?t.push(n):e.push(n);return[...e,...t]}var eR=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function _i(r,e,t){let n=Ir[e];r.set(n,(r.get(n)??1)*t)}function tR(r,e){let t=r.trim(),n=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(n&&(o||i)){_i(e,"harmonyos-guides",1.45),_i(e,"harmonyos-references",1.35);return}(o||i)&&_i(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&_i(e,"harmonyos-references",1.75)}function wv(r){let e=new Map,t=r.trim();if(!t)return e;let n=sv(t);tR(t,e),lv(t,e);for(let o of eR)o.pattern.test(t)&&(o.skipForPureApiSymbol&&n||_i(e,o.catalog,o.multiplier));return e}function Sv(r){return uv(r)}import{readFile as ER,stat as CR,writeFile as PR}from"fs/promises";var rR=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function nR(r,e){let t=-1;for(let n of rR){let o=r.lastIndexOf(n);o>t&&(t=o)}return t>=e?t:-1}function bv(r,e,t={}){let{maxLen:n=ky,contextChars:o=Dy,excerptTruncated:i=!1}=t,s=r.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=n)return i?`${s}...`:s;let a=e.split(/\s+/).map(me=>me.trim()).filter(Boolean),c=0;for(let me of a){let Te=s.toLowerCase().indexOf(me.toLowerCase());if(Te>=0){c=Te;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+n),g=s.slice(l,d),v=nR(g,n-25);v>=0&&(d=l+v);let b=s.slice(l,d).trim(),N=l>0?"...":"",$=d<s.length||i?"...":"";return`${N}${b}${$}`}var oR=`
|
|
1314
1325
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1315
1326
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1316
1327
|
FROM segments_fts
|
|
@@ -1319,7 +1330,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1319
1330
|
WHERE segments_fts MATCH ?
|
|
1320
1331
|
ORDER BY bm25(segments_fts)
|
|
1321
1332
|
LIMIT ?
|
|
1322
|
-
`,
|
|
1333
|
+
`,iR=`
|
|
1323
1334
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1324
1335
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1325
1336
|
FROM segments_fts
|
|
@@ -1328,7 +1339,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1328
1339
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1329
1340
|
ORDER BY bm25(segments_fts)
|
|
1330
1341
|
LIMIT ?
|
|
1331
|
-
`,
|
|
1342
|
+
`,sR=3.5,aR=1.4,cR=4,lR=1.8,dR=1.35,uR=3.5,pR=1.8,mR=120,Ev=6;function lu(r){return r.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function fR(r){return r.split(/[^\p{L}\p{N}@.]+/u).map(lu).filter(e=>e.length>=2)}function hR(r,e){return e.length>1&&e.every(t=>r.includes(t))}function gR(r){return/^[a-z0-9]{1,4}$/.test(r.trim().toLowerCase())}function yR(r,e){return r===e?uR:r.startsWith(e)||r.includes(`@ohos.${e}`)?pR:1}function vR(r,e){let t=lu(e);if(t.length<2)return 1;let n=lu(r.doc_title);if(gR(e))return yR(n,t);if(n.includes(t))return cR;if(t.length>=Ev&&n.includes(t.slice(0,Ev)))return lR;let o=fR(e);return hR(n,o)?dR:1}function wR(r,e){return e<=1?r:r<0?r*e:r/e}function ic(r,e,t,n){let o=r.bm25/(e.get(r.catalog_id)??1);return o=wR(o,vR(r,t)),n&&nu(r.doc_title,r.section_title,n)&&(o/=sR,r.catalog_id===Ir["harmonyos-references"]&&(o/=aR)),o}function cu(r,e,t,n){return r.reduce((o,i)=>ic(i,e,t,n)<ic(o,e,t,n)?i:o)}function SR(r,e){return e.some(t=>r.section_title.includes(t)||r.doc_title.includes(t))}function bR(r,e,t,n,o){if(o){let i=r.filter(s=>nu(s.doc_title,s.section_title,o));if(i.length>0)return cu(i,t,n,o)}if(e.length>0){let i=r.filter(s=>SR(s,e));if(i.length>0)return cu(i,t,n,o)}return cu(r,t,n,o)}function Cv(r,e,t,n,o){let i=wv(e),s=ov(e),c=ru(e)?.camelCase,l=new Map;for(let b of r){let N=l.get(b.document_id)??[];N.push(b),l.set(b.document_id,N)}let d=[];for(let b of l.values())d.push(bR(b,s,i,t,c));let g=d.sort((b,N)=>ic(b,i,t,c)-ic(N,i,t,c));return(o?yv(g):g).slice(0,n)}function Pv(r,e,t,n,o,i){let s=e?Ir[e]:void 0,a=Math.max(t,t*gy,mR),c=s===void 0?r.all(oR,n,a):r.all(iR,n,s,a);return(s===void 0?Cv(c,i,o,t,!0):Cv(c,i,o,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:bv(d.lead_text,o,{excerptTruncated:!!d.excerpt_truncated})}))}var Av=`
|
|
1332
1343
|
CREATE TABLE documents (
|
|
1333
1344
|
id INTEGER PRIMARY KEY,
|
|
1334
1345
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1366,45 +1377,48 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1366
1377
|
END;
|
|
1367
1378
|
|
|
1368
1379
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1369
|
-
`;var Ud=null,An=null,Ay=Promise.resolve();async function Bd(){return Ud||(Ud=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Ud}function nT(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function rT(n){let e=await eT(n);if(An&&An.dbPath===n&&An.mtimeMs===e.mtimeMs)return An.db;An?.db.close();let t=await Bd(),r=t.capi,o=t.wasm,i=new Uint8Array(await Qk(n)),s=o.allocFromTypedArray(i),a,c=!1;try{a=new t.oo1.DB(":memory:");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE,d=r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,l);if(d!==r.SQLITE_OK)throw new Error(`Failed to open readonly database: sqlite3_deserialize returned code ${d} for: ${n}`);return An={dbPath:n,mtimeMs:e.mtimeMs,db:a},c=!0,a}finally{c||(a?.close(),o.dealloc(s))}}async function oT(n){let e,t=Ay;Ay=new Promise(r=>{e=r}),await t;try{return await rT(n)}finally{e()}}function Dy(){An?.db.close(),An=null}async function iT(n,e,t,r){n.exec("BEGIN");for(let o of r){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function sT(n,e,t){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function aT(n,e,t){await Ii();let r=await Bd(),o=new r.oo1.DB(":memory:","c");o.exec(Iy);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=sT(o,i,s),l=e.length;for(let g=0;g<l;g+=md){let w=e.slice(g,g+md),C=await Promise.all(w.map(async z=>({source:z,searchText:await fy(z)})));await iT(o,a,c,C),await t?.(Math.min(g+w.length,l),l)}o.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(o);await tT(n,d),o.close(),Dy()}async function cT(n,e,t,r,o,i){let s=await oT(n);return Py(nT(s),e,t,r,o,i)}async function ky(){return await Bd(),{resetCache:Dy,buildSearchIndex:aT,searchIndex:(n,e,t,r,o,i,s)=>cT(r,e,t,o,i,s)}}var Ba=null,Wd=null;async function Vd(){return Ba||(Ba=ky().then(n=>(Wd=n,n))),Ba}function Gd(){Wd?.resetCache(),Ba=null,Wd=null}async function lT(n,e,t,r,o,i,s){let a=await Vd(),c=s??En();return a.searchIndex(n,e,t,c,r,o,i)}function oo(){Gd()}function Ry(n,e,t){let r=new Set,o=[];for(let i of[...n,...e])if(!r.has(i.documentId)&&(r.add(i.documentId),o.push(i),o.length>=t))break;return o}function Wa(n,e,t,r,o,i){return lT(n,e,t,o,r.expandedQuery,r.rawQuery,i)}async function dT(n,e,t,r,o){let i=await Wa(n,e,t,r,Si(r.tokens,"AND"),o);if(i.length>=t)return i;let s=await Wa(n,e,t,r,Si(r.tokens,"OR"),o);return Ry(i,s,t)}async function qd(n,e,t,r,o){return r.ftsMatch?Wa(n,e,t,r,r.ftsMatch,o):r.preferAnd?dT(n,e,t,r,o):Wa(n,e,t,r,Si(r.tokens,"OR"),o)}async function uT(n,e,t,r){let o=await qd(n,"harmonyos-references",e,t,r);if(o.length>=e)return o;let i=await qd(n,void 0,e,t,r);return Ry(o,i,e)}function Ty(n,e){return e!==void 0?n:wy(n)}async function zd(n,e,t=10,r){let o=await hy(n);if(dy(o.rawQuery,e)){let a=await uT(n,t,o,r);return Ty(a,e)}let i=e??Sy(o.rawQuery),s=await qd(n,i,t,o,r);return Ty(s,e)}var Va=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function mT(n){return new Promise(e=>setTimeout(e,n))}async function xy(n,e,t){e?.start(t),await yi({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Ug(n),oo(),e&&(e.text="Documentation index installed.")}async function fT(n,e){try{return await xy(n,e,"Installing documentation index\u2026"),await Ly(e),!0}catch(t){if(no(t))throw t}try{return await Bg(),oo(),await xy(n,e,"Retrying documentation index install\u2026"),await Ly(e),!0}catch(t){if(no(t))throw t;return!1}}async function Ly(n){await yi({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function hT(n){let e=await Td(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await yi({state:"done",message:t,error:null})}async function gT(n,e){let t=n instanceof Error?n.message:String(n);throw await yi({state:"error",error:t}),e?.fail(t),n}async function yT(){let n=Ie();await Di.promises.mkdir(n,{recursive:!0});let e=xa();return Di.existsSync(e)||await Di.promises.writeFile(e,"","utf-8"),e}async function wT(){let n=await yT();return pT.lock(n,{stale:1800*1e3})}async function vT(){let n=Cn(),e=(n?await hi(n):null)??await kd();if(!e)throw new Error("docs.zip not found");return e}async function ST(n,e){let t=await vT(),r=n.force||await Rd(n.force),o=await _a(n.force);if(!r&&!o&&wi()){await hT(e);return}if(!(Hg(t)&&await fT(t,e)))throw new Error("Documentation index bundle is unavailable or corrupted. Reinstall the package with: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>")}var io=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:Oy({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await ro({mode:"write"}),i=await wT(),await Dd(zg("Starting documentation setup\u2026")),await ST(e,o)}catch(s){throw i&&await gT(s,o),s}finally{i&&await i()}}};async function bT(n){for(;;){let e=await Ma();if(e.state==="done"&&wi())return;if(e.state==="error")throw new Va("build-failed",e.error??"Documentation setup failed. Try your docs command again in a moment.");n.text=e.message||"Documentation is being prepared\u2026",await mT(500)}}async function Ny(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await io.run({builtBy:"doc-init",force:e,quiet:!0})}async function ET(){let n=await _a()!==null;if(wi()&&!n)return;let e=Oy({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Jg()){await bT(e),e.succeed("Documentation ready.");return}if(await Rd()){await Ny(e),e.succeed("Documentation ready.");return}await Ny(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function so(){await ro({mode:"read"}),await ET()}function CT(n){let e=n instanceof Error?n.message:String(n);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var Jd=class{async search(e,t,r=10){await so();try{return await zd(e,t,r)}catch(o){if(!CT(o))throw o;return oo(),await io.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),zd(e,t,r)}}async readDocument(e){return await so(),yd(e)}},Ga=new Jd;import J5 from"adm-zip";import{unified as T5}from"unified";import x5 from"remark-parse";import N5 from"remark-gfm";import{toString as M5}from"mdast-util-to-string";async function Kd(n,e){let t=Date.now();try{let r=await e();return await My(n,Date.now()-t,!0,null),r}catch(r){let o=r instanceof Error?r.code??r.name:"UnknownError";throw await My(n,Date.now()-t,!1,o),r}}async function My(n,e,t,r){await D.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function Xd(n){console.error(IT(RT(n))),process.exitCode=1}function _y(...n){return e=>{if(!n.includes(e))throw new Yd(`Allowed values: ${n.join(", ")}`);return e}}function DT(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Yd("Must be a positive integer.");return e}var kT=_y("json","default"),TT=_y("json","default");function RT(n){let e=n instanceof Error?n.message:String(n);return no(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}var qa=new PT("docs").description("Search and read HarmonyOS documentation from local docs directory");qa.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",LT,"all").option("--format <fmt>","Output format (default, json)",kT,"default").option("--limit <n>","Max number of results",DT,10).action(async(n,e)=>{let t=n.map(o=>o.trim()).filter(Boolean),r={event:S.DocOperation,subAction:"search",keywords:t,queryLen:t.join(" ").length,catalog:e.catalog??"all"};try{await Kd(r,async()=>{let o=xT(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,s=await Ga.search(o,i,e.limit);e.format==="json"?console.log(JSON.stringify(s,null,2)):NT(s)})}catch(o){Xd(o)}});qa.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:S.DocOperation,subAction:"read",documentId:e};try{await Kd(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let r=await Ga.readDocument(e);console.log(r)})}catch(r){Xd(r)}});qa.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",TT,"default").action(async n=>{let e={event:S.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Kd(e,async()=>{if(await so(),n.format==="json"){let t=qt.map(r=>({name:r,title:Sn[r]}));console.log(JSON.stringify(t,null,2))}else for(let t of qt)console.log(` ${t.padEnd(20)} ${AT(Sn[t])}`)})}catch(t){Xd(t)}});function xT(n){let e=n.map(r=>r.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>Zr)throw new Error(`Query exceeds ${Zr} characters.`);return e}function LT(n){if(n==="all")return"all";if(!qt.includes(n))throw new Yd(`Invalid catalog "${n}". Allowed: all, ${qt.join(", ")}`);return n}function NT(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 Fy=qa;import{Command as UR}from"commander";import{Command as GT,InvalidArgumentError as qT,Option as Qd}from"commander";import{readFileSync as MT,unlinkSync as _T}from"fs";import{tmpdir as FT}from"os";import{join as jT}from"path";var Jt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=OT(t);return e?.all||(r=r.filter(o=>o.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];f(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await se(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function OT(n){let e=n.split(`
|
|
1370
|
-
`),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]),w=Number(c[3]),C=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:d,type:C})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===i}))}function jy(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function ki(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function $y(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 Hy(n){return n.originalText||void 0}function ao(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let o=r.pop();o.id===e&&t.push(o);for(let i=o.children.length-1;i>=0;i--)r.push(o.children[i])}return t}function Uy(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:o,parent:i,depth:s}=r.pop(),a=i===null,c=!o.id&&!o.text&&!o.clickable&&!o.longClickable&&!o.scrollable&&!o.checkable,l=a||!c,d=i;if(l){let w={...o,children:[]};if(a?t.push(w):i.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";f(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let w=o.children.length-1;w>=0;w--)r.push({current:o.children[w],parent:d,depth:g})}return t}function $T(n){let e=MT(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function HT(n){return n.attributes??{}}function za(n,e,t){let r=HT(n),o={id:r.id||void 0,type:r.type||void 0,text:Hy(r),bounds:$y(r.bounds),clickable:ki(r.clickable)||void 0,longClickable:ki(r.longClickable)||void 0,scrollable:ki(r.scrollable)||void 0,checkable:ki(r.checkable)||void 0,hitTestBehavior:jy(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>za(i,e,t+1))),o}function UT(n,e){if(e){let r=n.find(o=>String(o.id)===e);if(!r){let o=n.map(i=>`${i.id} (${i.name})`).join(", ");throw new v(`Window '${e}' not found. Available windows: ${o||"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 ar=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 o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];r!==void 0&&i.push("-d",String(r)),t&&i.push("-w",t),f(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await se(this.hdcPath,i);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,o)}async recvAndParseDump(e,t){let r=jT(FT(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),$T(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];f(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await se(this.hdcPath,o);if(i.exitCode!==0)throw new Error(`Failed to recv dump file: ${(i.stderr||i.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{f(`Removing local dump file: ${t}`),_T(t)}catch(i){f(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];f(`Executing: ${this.hdcPath} ${o.join(" ")}`),await se(this.hdcPath,o).catch(i=>{f(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new Jt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=UT(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).map(s=>za(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let o=[];for(let i of r){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:za(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>Uy(za(s,0,0),t))}};var Ja={left:"0",right:"1",up:"2",down:"3"};function Ne(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Zd(n,e){n!==void 0&&Ne(n,e)}function By(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ya(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Ti(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 Wy(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Vy(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 co(n,e,t,r,o=!0){By(n,e),Ya(t,"--id"),Zd(n,"x"),Zd(e,"y"),Wy(r),Vy(n!==void 0,!!t,!!r,o)}async function Rt(n){let e=await k.new(),t=await mt(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function lo(n,e,t,r,o,i){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Jt(n,e).listWindows({all:!0}),c=new ar(n);return BT(c,e,a,o,i)}async function BT(n,e,t,r,o){if(o!==void 0){let i=t.find(a=>String(a.id)===o);if(i&&i.displayId!==0)throw new v(`Window "${o}" is on display ${i.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,o,!1);return VT(s,r)}return WT(n,e,t,r)}async function WT(n,e,t,r){let o=[...new Set(t.map(a=>a.displayId))],i=await n.dumpFullTreeByDisplays(e,0,o),s=[];for(let{displayId:a,tree:c}of i)for(let l of ao([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new v(`Node "${r}" not found.`,"Node not found.");if(s.length>1)throw new v(`Multiple nodes found with id "${r}".`,"Multiple nodes found");if(s[0].displayId!==0)throw new v(`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 Gy(s[0].node,r)}function VT(n,e){let t=ao(n,e);if(t.length===0)throw new v(`Node "${e}" not found.`,"Node not found.");if(t.length>1)throw new v(`Multiple nodes found with id "${e}".`,"Multiple nodes found");return Gy(t[0],e)}function Gy(n,e){let t=n.bounds;if(!t)throw new v(`Node "${e}" has no bounds.`,"Node has no bounds.");let[r,o,i,s]=t;return{x:Math.ceil((r+i)/2),y:Math.ceil((o+s)/2)}}async function st(n,e,t){let r=["-t",e,"shell",...t];f(`Executing: ${n} ${r.join(" ")}`);let o=await se(n,r);if(o.exitCode!==0)throw new Error(o.stderr||o.stdout||`uitest exited with code ${o.exitCode}`);let i=o.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>i.includes(a))&&!i.includes("no error"))throw new Error(o.stdout.trim()||"uitest command failed")}import zT from"ora";function JT(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 YT(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 qy(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${YT(o)}`),o.children.length>0&&t.push(...qy(o.children,e+1).split(`
|
|
1380
|
+
`;var du=null,xr=null,Iv=Promise.resolve();async function uu(){return du||(du=(async()=>{let r=(await import("@sqlite.org/sqlite-wasm")).default;return r()})()),du}function AR(r){return{all(e,...t){let n=r.prepare(e);t.length>0&&n.bind(t);let o=[];for(;n.step();)o.push(n.get({}));return n.finalize(),o}}}async function IR(r){let e=await CR(r);if(xr&&xr.dbPath===r&&xr.mtimeMs===e.mtimeMs)return xr.db;xr?.db.close();let t=await uu(),n=t.capi,o=t.wasm,i=new Uint8Array(await ER(r)),s=o.allocFromTypedArray(i),a,c=!1;try{a=new t.oo1.DB(":memory:");let l=n.SQLITE_DESERIALIZE_READONLY|n.SQLITE_DESERIALIZE_RESIZEABLE|n.SQLITE_DESERIALIZE_FREEONCLOSE,d=n.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,l);if(d!==n.SQLITE_OK)throw new Error(`Failed to open readonly database: sqlite3_deserialize returned code ${d} for: ${r}`);return xr={dbPath:r,mtimeMs:e.mtimeMs,db:a},c=!0,a}finally{c||(a?.close(),o.dealloc(s))}}async function kR(r){let e,t=Iv;Iv=new Promise(n=>{e=n}),await t;try{return await IR(r)}finally{e()}}function kv(){xr?.db.close(),xr=null}async function DR(r,e,t,n){r.exec("BEGIN");for(let o of n){let i=t(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}r.exec("COMMIT")}function TR(r,e,t){return n=>{let o=e.get(n.documentId);if(o!==void 0)return o;let i=r.selectValue("SELECT id FROM documents WHERE document_id = ?",[n.documentId]);if(i!=null){let a=Number(i);return e.set(n.documentId,a),a}t.bind([n.documentId,n.catalogId,n.docTitle]),t.step(),t.reset();let s=Number(r.selectValue("SELECT last_insert_rowid()"));return e.set(n.documentId,s),s}}async function RR(r,e,t){await Mi();let n=await uu(),o=new n.oo1.DB(":memory:","c");o.exec(Av);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=TR(o,i,s),l=e.length;for(let g=0;g<l;g+=_d){let v=e.slice(g,g+_d),b=await Promise.all(v.map(async N=>({source:N,searchText:await fv(N)})));await DR(o,a,c,b),await t?.(Math.min(g+v.length,l),l)}o.exec("ANALYZE");let d=n.capi.sqlite3_js_db_export(o);await PR(r,d),o.close(),kv()}async function xR(r,e,t,n,o,i){let s=await kR(r);return Pv(AR(s),e,t,n,o,i)}async function Dv(){return await uu(),{resetCache:kv,buildSearchIndex:RR,searchIndex:(r,e,t,n,o,i,s)=>xR(n,e,t,o,i,s)}}var sc=null,pu=null;async function mu(){return sc||(sc=Dv().then(r=>(pu=r,r))),sc}function fu(){pu?.resetCache(),sc=null,pu=null}async function LR(r,e,t,n,o,i,s){let a=await mu(),c=s??kr();return a.searchIndex(r,e,t,c,n,o,i)}function mo(){fu()}function Rv(r,e,t){let n=new Set,o=[];for(let i of[...r,...e])if(!n.has(i.documentId)&&(n.add(i.documentId),o.push(i),o.length>=t))break;return o}function ac(r,e,t,n,o,i){return LR(r,e,t,o,n.expandedQuery,n.rawQuery,i)}async function NR(r,e,t,n,o){let i=await ac(r,e,t,n,Ri(n.tokens,"AND"),o);if(i.length>=t)return i;let s=await ac(r,e,t,n,Ri(n.tokens,"OR"),o);return Rv(i,s,t)}async function hu(r,e,t,n,o){return n.ftsMatch?ac(r,e,t,n,n.ftsMatch,o):n.preferAnd?NR(r,e,t,n,o):ac(r,e,t,n,Ri(n.tokens,"OR"),o)}async function OR(r,e,t,n){let o=await hu(r,"harmonyos-references",e,t,n);if(o.length>=e)return o;let i=await hu(r,void 0,e,t,n);return Rv(o,i,e)}function Tv(r,e){return e!==void 0?r:vv(r)}async function gu(r,e,t=10,n){let o=await hv(r);if(dv(o.rawQuery,e)){let a=await OR(r,t,o,n);return Tv(a,e)}let i=e??Sv(o.rawQuery),s=await hu(r,i,t,o,n);return Tv(s,e)}var cc=class extends Error{constructor(t,n){super(n);this.code=t;this.name="DocNotReadyError"}code};function _R(r){return new Promise(e=>setTimeout(e,r))}async function xv(r,e,t){e?.start(t),await ki({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Uy(r),mo(),e&&(e.text="Documentation index installed.")}async function FR(r,e){try{return await xv(r,e,"Installing documentation index\u2026"),await Lv(e),!0}catch(t){if(uo(t))throw t}try{return await By(),mo(),await xv(r,e,"Retrying documentation index install\u2026"),await Lv(e),!0}catch(t){if(uo(t))throw t;return!1}}async function Lv(r){await ki({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),r?.succeed("Documentation ready.")}async function jR(r){let e=await Zd(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";r?.succeed(t),await ki({state:"done",message:t,error:null})}async function $R(r,e){let t=r instanceof Error?r.message:String(r);throw await ki({state:"error",error:t}),e?.fail(t),r}async function HR(){let r=ke();await Fi.promises.mkdir(r,{recursive:!0});let e=Ya();return Fi.existsSync(e)||await Fi.promises.writeFile(e,"","utf-8"),e}async function UR(){let r=await HR();return MR.lock(r,{stale:1800*1e3})}async function BR(){let r=Dr(),e=(r?await Ai(r):null)??await Xd();if(!e)throw new Error("docs.zip not found");return e}async function WR(r,e){let t=await BR(),n=r.force||await Qd(r.force),o=await ec(r.force);if(!n&&!o&&Di()){await jR(e);return}if(!(Hy(t)&&await FR(t,e)))throw new Error("Documentation index bundle is unavailable or corrupted. Reinstall the package with: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>")}var fo=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:Ov({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await po({mode:"write"}),i=await UR(),await Kd(qy("Starting documentation setup\u2026")),await WR(e,o)}catch(s){throw i&&await $R(s,o),s}finally{i&&await i()}}};async function VR(r){for(;;){let e=await Qa();if(e.state==="done"&&Di())return;if(e.state==="error")throw new cc("build-failed",e.error??"Documentation setup failed. Try your docs command again in a moment.");r.text=e.message||"Documentation is being prepared\u2026",await _R(500)}}async function Nv(r,e=!1){r.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await fo.run({builtBy:"doc-init",force:e,quiet:!0})}async function GR(){let r=await ec()!==null;if(Di()&&!r)return;let e=Ov({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await Jy()){await VR(e),e.succeed("Documentation ready.");return}if(await Qd()){await Nv(e),e.succeed("Documentation ready.");return}await Nv(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function ho(){await po({mode:"read"}),await GR()}function zR(r){let e=r instanceof Error?r.message:String(r);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var yu=class{async search(e,t,n=10){await ho();try{return await gu(e,t,n)}catch(o){if(!zR(o))throw o;return mo(),await fo.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),gu(e,t,n)}}async readDocument(e){return await ho(),Hd(e)}},lc=new yu;import W4 from"adm-zip";import{unified as P4}from"unified";import I4 from"remark-parse";import D4 from"remark-gfm";import{toString as R4}from"mdast-util-to-string";async function wu(r,e){let t=Date.now();try{let n=await e();return await Mv(r,Date.now()-t,!0,null),n}catch(n){let o=n instanceof Error?n.code??n.name:"UnknownError";throw await Mv(r,Date.now()-t,!1,o),n}}async function Mv(r,e,t,n){await I.track(r,{duration_ms:e,success:t,error_code:n}).catch(()=>{})}function Su(r){console.error(JR(QR(r))),process.exitCode=1}function _v(...r){return e=>{if(!r.includes(e))throw new vu(`Allowed values: ${r.join(", ")}`);return e}}function KR(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new vu("Must be a positive integer.");return e}var XR=_v("json","default"),ZR=_v("json","default");function QR(r){let e=r instanceof Error?r.message:String(r);return uo(r)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}var dc=new qR("docs").description("Search and read HarmonyOS documentation from local docs directory");dc.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",tx,"all").option("--format <fmt>","Output format (default, json)",XR,"default").option("--limit <n>","Max number of results",KR,10).action(async(r,e)=>{let t=r.map(o=>o.trim()).filter(Boolean),n={event:S.DocOperation,subAction:"search",keywords:t,queryLen:t.join(" ").length,catalog:e.catalog??"all"};try{await wu(n,async()=>{let o=ex(r),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,s=await lc.search(o,i,e.limit);e.format==="json"?console.log(JSON.stringify(s,null,2)):rx(s)})}catch(o){Su(o)}});dc.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{let e=r.trim(),t={event:S.DocOperation,subAction:"read",documentId:e};try{await wu(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let n=await lc.readDocument(e);console.log(n)})}catch(n){Su(n)}});dc.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",ZR,"default").action(async r=>{let e={event:S.DocOperation,subAction:"catalog",fmt:r.format??"default"};try{await wu(e,async()=>{if(await ho(),r.format==="json"){let t=Xt.map(n=>({name:n,title:Ar[n]}));console.log(JSON.stringify(t,null,2))}else for(let t of Xt)console.log(` ${t.padEnd(20)} ${YR(Ar[t])}`)})}catch(t){Su(t)}});function ex(r){let e=r.map(n=>n.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>so)throw new Error(`Query exceeds ${so} characters.`);return e}function tx(r){if(r==="all")return"all";if(!Xt.includes(r))throw new vu(`Invalid catalog "${r}". Allowed: all, ${Xt.join(", ")}`);return r}function rx(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 Fv=dc;import{Command as Fx}from"commander";import{Command as nx,InvalidArgumentError as ox,Option as bu}from"commander";import ix from"ora";function sx(r){let e=parseInt(r,10);if(!Number.isInteger(e)||e<0||String(e)!==r.trim())throw new ox("depth must be a non-negative integer");return e}function ax(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 jv(r,e=0){let t=[],n=" ".repeat(e);for(let o of r)t.push(`${n}${ax(o)}`),o.children.length>0&&t.push(...jv(o.children,e+1).split(`
|
|
1371
1381
|
`));return t.join(`
|
|
1372
|
-
`)}function KT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function XT(n,e){let t=ao(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(o=>({...o,children:[]}));return JSON.stringify(r,null,2)}function ZT(n,e){return e.id?XT(n,e.id):e.format==="json"?JSON.stringify(n,null,2):qy(n)}async function QT(n){KT(n);let e=zT({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let o=await k.new(),i=await mt(o,n.device),s=new ar(o.hdcPath);t=n.mode==="full"?await s.dumpFullTree(i,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(i,n.depth,n.window,n.allWindows)}catch(o){throw e.stop(),new Error(`Failed to dump layout: ${o.message}`,{cause:o})}e.stop();let r=ZT(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function eR(n){return{event:S.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function tR(n){let e=eR(n),t=Date.now(),r=!0,o=null;try{e.outputSize=await QT(n)}catch(i){throw r=!1,o=W(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await D.track(e,i)}}var zy=new GT("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 Qd("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(JT).default(0)).addOption(new Qd("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Qd("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await tR(n)});import{Command as nR,Option as rR}from"commander";import{yellow as oR}from"colorette";import iR from"ora";var sR=["Id","Name","Pid","DisplayId","Focused"];function aR(n,e){if(e==="json"){let r=n.map(o=>({id:o.id,name:o.name,pid:o.pid,displayId:o.displayId,focused:o.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(_t(sR,t))}async function cR(n){let e=iR({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await k.new(),o=await mt(r,n.device);t=await new Jt(r.hdcPath,o).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(oR(" No windows found."));return}aR(t,n.format)}function lR(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:S.CommandExecuted,args:["ui","window","list",...e]}}async function dR(n){let e=lR(n),t=Date.now(),r=!0,o=null;try{await cR(n)}catch(i){throw r=!1,o=W(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await D.track(e,i)}}var eu=new nR("window").description("Manage device windows");eu.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new rR("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await dR(n)});import{Command as uR}from"commander";import Ue from"fs";import at from"path";import{randomUUID as pR}from"crypto";import{green as mR}from"colorette";function fR(n){return{event:S.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function hR(){return String(Date.now())}function Jy(n){let e;try{e=Ue.statSync(n)}catch(t){let r=t.code;throw r==="ENOENT"?new Error(`Screenshot directory does not exist: ${n}`,{cause:t}):r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${n}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${n}`);try{Ue.accessSync(n,Ue.constants.W_OK|Ue.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Yy(n,e){try{throw Ue.lstatSync(n),new Error(`Screenshot file already exists: ${n}`)}catch(t){let r=t.code;if(r==="ENOENT")return;throw r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!r?t:new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}}function gR(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=at.resolve(e);try{if(Ue.statSync(t).isDirectory()){Jy(t);let o=at.join(t,`screenshot-${hR()}.png`);return Yy(o,t),o}}catch(o){if(o.code!=="ENOENT")throw o}if(at.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=at.dirname(t);return Jy(r),Yy(t,r),t}function Ky(n){if(!Ue.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Ue.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Ue.readFileSync(n).subarray(0,8),r=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(r))throw new Error(`Screenshot file is not a valid PNG: ${n}`)}function yR(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 wR(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function vR(n,e){try{Ue.copyFileSync(n,e,Ue.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Ky(e)}function SR(n){let e=n.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),r=Number(t[4]);return Number.isFinite(r)?r:void 0}async function bR(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];f(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await se(n.hdcPath,e);return t.exitCode===0?SR(t.stdout):void 0}function ER(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1373
|
-
`).trim()}function CR(n){return n.replace(/(Tips:\s*supported\s+displayIds)\s*:?[ \t]*(?:\r?\n[ \t]*)?(\d+(?:(?:[ \t]*,[ \t]*|[ \t]+|\r?\n[ \t]*)\d+)*)/gi,(e,t,r)=>`${t}: ${r.match(/\d+/g)?.join(", ")??r}`)}function PR(n){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(n)||new RegExp(String.raw`(?:${e}).*display(?:\s*id)?`,"is").test(n)}async function IR(n,e){let t=yR(n,e);f(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await se(n.hdcPath,t),o=await bR(n);return{created:o!==void 0&&o>0,output:CR(ER(r))}}async function AR(n){let e="";for(let t of[void 0,"png"]){let r=await IR(n,t);if(r.created)return;if(n.display!==void 0&&PR(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
|
|
1374
|
-
snapshot_display output:
|
|
1375
|
-
${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
|
|
1376
|
-
snapshot_display output:
|
|
1377
|
-
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Xy(n){try{return Ky(n),!0}catch{return!1}}function Zy(n){let e=[];for(let t of Ue.readdirSync(n,{withFileTypes:!0})){let r=at.join(n,t.name);if(t.isDirectory()){e.push(...Zy(r));continue}t.isFile()&&Xy(r)&&e.push(r)}return e}function DR(n,e){let t=at.join(n,at.basename(e));if(Xy(t))return t;let r=Zy(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function tu(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];f(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await se(n.hdcPath,r);return o.exitCode!==0&&f(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),DR(e,n.remotePath)}async function kR(n){let e=Ue.mkdtempSync(at.join(at.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await tu(n,e,at.join(e,at.basename(n.remotePath)))??await tu(n,e,e)??await tu(n,e,at.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);vR(t,n.localPath)}finally{Ue.rmSync(e,{recursive:!0,force:!0})}}async function TR(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];f(`Executing: ${n.hdcPath} ${e.join(" ")}`),await se(n.hdcPath,e)}async function RR(n){try{await AR(n),await kR(n)}finally{await TR(n)}}async function xR(n){let e=fR(n),t=Date.now(),r=!0,o=null;try{let i=gR(n.path),s=n.display!==void 0?wR(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let a=await k.new(),c=await mt(a,n.device),l=`/data/local/tmp/devecocli-${pR()}.png`;await RR({hdcPath:a.hdcPath,serial:c,localPath:i,remotePath:l,display:s}),console.log(mR(`Screenshot saved to ${i}`))}catch(i){throw r=!1,o=W(i),i}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await D.track(e,i)}}var Qy=new uR("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(xR);import{Command as Dn}from"commander";function kn(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:S.CommandExecuted,args:["ui",n,...t]}}function LR(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return f(`escapeShellText: ${n} -> ${t}`),t}async function Tn(n,e,t,r){let o=new ft;o.start(n);let i=Date.now(),s=!0,a=null;try{await r(o)}catch(c){throw o.stop(),s=!1,a=W(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-i,success:s,error_code:a};await D.track(t,c)}}async function NR(n,e,t){let r=kn("click",t);await Tn("Executing click...","click failed",r,async o=>{co(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Rt(t.device),{x:a,y:c}=await lo(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await st(i,s,["uitest","uiInput","click",String(a),String(c)]),o.succeed(`click at (${a}, ${c})`)})}async function OR(n,e,t){let r=kn("doubleclick",t);await Tn("Executing doubleclick...","doubleclick failed",r,async o=>{co(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Rt(t.device),{x:a,y:c}=await lo(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await st(i,s,["uitest","uiInput","doubleClick",String(a),String(c)]),o.succeed(`doubleclick at (${a}, ${c})`)})}async function MR(n,e,t){let r=kn("longclick",t);await Tn("Executing longclick...","longclick failed",r,async o=>{co(n,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Rt(t.device),{x:a,y:c}=await lo(i,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await st(i,s,["uitest","uiInput","longClick",String(a),String(c)]),o.succeed(`longclick at (${a}, ${c})`)})}async function _R(n,e,t,r,o){let i=kn("swipe",o);await Tn("Executing swipe...","swipe failed",i,async s=>{Ne(n,"x1"),Ne(e,"y1"),Ne(t,"x2"),Ne(r,"y2");let a=Ti(o.speed),{hdcPath:c,deviceId:l}=await Rt(o.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await st(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function FR(n,e,t,r,o){let i=kn("fling",o);await Tn("Executing fling...","fling failed",i,async s=>{Ne(n,"x1"),Ne(e,"y1"),Ne(t,"x2"),Ne(r,"y2");let a=Ti(o.speed),{hdcPath:c,deviceId:l}=await Rt(o.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await st(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function jR(n,e,t,r,o){let i=kn("drag",o);await Tn("Executing drag...","drag failed",i,async s=>{Ne(n,"x1"),Ne(e,"y1"),Ne(t,"x2"),Ne(r,"y2");let a=Ti(o.speed),{hdcPath:c,deviceId:l}=await Rt(o.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await st(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function $R(n,e){let t=kn("dircfling",e);await Tn("Executing dircfling...","dircfling failed",t,async r=>{let o=Ja[n];if(o===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Ja).join(", ")}`);let{hdcPath:i,deviceId:s}=await Rt(e.device);await st(i,s,["uitest","uiInput","dircFling",o]),r.succeed(`dircfling ${n}`)})}async function HR(n,e,t,r){let o=kn("text",r);await Tn("Executing text input...","input failed",o,async i=>{co(e,t,r.id,r.window,!1),Ya(n,"text");let{hdcPath:s,deviceId:a}=await Rt(r.device),c=LR(n);if(e!==void 0)await st(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),i.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await lo(s,a,void 0,void 0,r.id,r.window);await st(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),i.succeed(`input ${n} at (${l}, ${d})`)}else await st(s,a,[`uitest uiInput text ${c}`]),i.succeed(`input ${n}`)})}var ew=new Dn("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(NR),tw=new Dn("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(OR),nw=new Dn("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(MR),rw=new Dn("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(_R),ow=new Dn("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(FR),iw=new Dn("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(jR),sw=new Dn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action($R),aw=new Dn("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(HR);var ct=new UR("ui").description("Inspect and interact with UI on a connected device");ct.addCommand(zy);ct.addCommand(eu);ct.addCommand(Qy);ct.addCommand(ew);ct.addCommand(tw);ct.addCommand(nw);ct.addCommand(rw);ct.addCommand(ow);ct.addCommand(iw);ct.addCommand(sw);ct.addCommand(aw);var cw=ct;import{Command as Hw,InvalidArgumentError as kL}from"commander";import{execa as ux}from"execa";import xt from"fs";import*as su from"os";import*as O from"path";var BR=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),WR=/\r/g,VR=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,GR=/^<+\s*/,qR=/\s*>+$/,zR=[/^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\.$/],JR=new Set([1]);function ru(n){if(!n)return"";let e=n.replace(BR,"").replace(WR,`
|
|
1382
|
+
`)}function cx(r){if(r.allWindows&&r.window)throw new Error("--all-windows and --window are mutually exclusive.")}function lx(r,e){let t=kn(r,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let n=t.map(o=>({...o,children:[]}));return JSON.stringify(n,null,2)}function dx(r,e){return e.id?lx(r,e.id):e.format==="json"?JSON.stringify(r,null,2):jv(r)}async function ux(r){cx(r);let e=ix({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let o=await k.new(),i=await gt(o,r.device),s=new en(o.hdcPath);t=r.mode==="full"?await s.dumpFullTree(i,r.depth,r.window,r.allWindows):await s.dumpCollapsedTree(i,r.depth,r.window,r.allWindows)}catch(o){throw e.stop(),new Error(`Failed to dump layout: ${o.message}`,{cause:o})}e.stop();let n=dx(t,r);return console.log(n),Buffer.byteLength(n,"utf8")}function px(r){return{event:S.CommandExecuted,args:["ui","layout",...r.device?["--device"]:[]],mode:r.mode,outputSize:0}}async function mx(r){let e=px(r),t=Date.now(),n=!0,o=null;try{e.outputSize=await ux(r)}catch(i){throw n=!1,o=q(i),i}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}}var $v=new nx("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 bu("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(sx).default(0)).addOption(new bu("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new bu("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async r=>{await mx(r)});import{Command as fx,Option as hx}from"commander";import{yellow as gx}from"colorette";import yx from"ora";var vx=["Id","Name","Pid","DisplayId","Focused"];function wx(r,e){if(e==="json"){let n=r.map(o=>({id:o.id,name:o.name,pid:o.pid,displayId:o.displayId,focused:o.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(Ut(vx,t))}async function Sx(r){let e=yx({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let n=await k.new(),o=await gt(n,r.device);t=await new jt(n.hdcPath,o).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(gx(" No windows found."));return}wx(t,r.format)}function bx(r){let e=[];return r.device&&e.push("--device"),r.format!=="default"&&e.push("--format"),r.all&&e.push("--all"),{event:S.CommandExecuted,args:["ui","window","list",...e]}}async function Ex(r){let e=bx(r),t=Date.now(),n=!0,o=null;try{await Sx(r)}catch(i){throw n=!1,o=q(i),i}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}}var Eu=new fx("window").description("Manage device windows");Eu.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new hx("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async r=>{await Ex(r)});import{Command as Cx}from"commander";import{green as Px}from"colorette";function Ax(r){return{event:S.CommandExecuted,args:["ui","screenshot",...r.device?["--device"]:[]]}}function Ix(r){let e=r.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}async function kx(r){let e=Ax(r),t=Date.now(),n=!0,o=null;try{if(r.device!==void 0&&!r.device.trim())throw new Error("--device must not be empty.");let i=r.display!==void 0?Ix(r.display):void 0,s=await k.new(),a=new tn(s),c=a.resolveDestinationPath(r.path),l=await gt(s,r.device);await a.captureToPath(l,c,i),console.log(Px(`Screenshot saved to ${c}`))}catch(i){throw n=!1,o=q(i),i}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}}var Hv=new Cx("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(kx);import{Command as Lr}from"commander";function Nr(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:S.CommandExecuted,args:["ui",r,...t]}}function Dx(r){let t=`"$(printf '%s' '${Buffer.from(r,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${r} -> ${t}`),t}async function Or(r,e,t,n){let o=new Qe;o.start(r);let i=Date.now(),s=!0,a=null;try{await n(o)}catch(c){throw o.stop(),s=!1,a=q(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-i,success:s,error_code:a};await I.track(t,c)}}async function Tx(r,e,t){let n=Nr("click",t);await Or("Executing click...","click failed",n,async o=>{Dn(r,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Rt(t.device),{x:a,y:c}=await Tn(i,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ct(i,s,["uitest","uiInput","click",String(a),String(c)]),o.succeed(`click at (${a}, ${c})`)})}async function Rx(r,e,t){let n=Nr("doubleclick",t);await Or("Executing doubleclick...","doubleclick failed",n,async o=>{Dn(r,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Rt(t.device),{x:a,y:c}=await Tn(i,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ct(i,s,["uitest","uiInput","doubleClick",String(a),String(c)]),o.succeed(`doubleclick at (${a}, ${c})`)})}async function xx(r,e,t){let n=Nr("longclick",t);await Or("Executing longclick...","longclick failed",n,async o=>{Dn(r,e,t.id,t.window);let{hdcPath:i,deviceId:s}=await Rt(t.device),{x:a,y:c}=await Tn(i,s,r!==void 0?Number(r):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ct(i,s,["uitest","uiInput","longClick",String(a),String(c)]),o.succeed(`longclick at (${a}, ${c})`)})}async function Lx(r,e,t,n,o){let i=Nr("swipe",o);await Or("Executing swipe...","swipe failed",i,async s=>{Le(r,"x1"),Le(e,"y1"),Le(t,"x2"),Le(n,"y2");let a=Fo(o.speed),{hdcPath:c,deviceId:l}=await Rt(o.device),d=["uitest","uiInput","swipe",r,e,t,n];a&&d.push(a),await ct(c,l,d),s.succeed(`swipe from (${r}, ${e}) to (${t}, ${n})`)})}async function Nx(r,e,t,n,o){let i=Nr("fling",o);await Or("Executing fling...","fling failed",i,async s=>{Le(r,"x1"),Le(e,"y1"),Le(t,"x2"),Le(n,"y2");let a=Fo(o.speed),{hdcPath:c,deviceId:l}=await Rt(o.device),d=["uitest","uiInput","fling",r,e,t,n];a&&d.push(a),await ct(c,l,d),s.succeed(`fling from (${r}, ${e}) to (${t}, ${n})`)})}async function Ox(r,e,t,n,o){let i=Nr("drag",o);await Or("Executing drag...","drag failed",i,async s=>{Le(r,"x1"),Le(e,"y1"),Le(t,"x2"),Le(n,"y2");let a=Fo(o.speed),{hdcPath:c,deviceId:l}=await Rt(o.device),d=["uitest","uiInput","drag",r,e,t,n];a&&d.push(a),await ct(c,l,d),s.succeed(`drag from (${r}, ${e}) to (${t}, ${n})`)})}async function Mx(r,e){let t=Nr("dircfling",e);await Or("Executing dircfling...","dircfling failed",t,async n=>{let o=Ns[r];if(o===void 0)throw new Error(`Invalid direction "${r}". Valid values: ${Object.keys(Ns).join(", ")}`);let{hdcPath:i,deviceId:s}=await Rt(e.device);await ct(i,s,["uitest","uiInput","dircFling",o]),n.succeed(`dircfling ${r}`)})}async function _x(r,e,t,n){let o=Nr("text",n);await Or("Executing text input...","input failed",o,async i=>{Dn(e,t,n.id,n.window,!1),Os(r,"text");let{hdcPath:s,deviceId:a}=await Rt(n.device),c=Dx(r);if(e!==void 0)await ct(s,a,[`uitest uiInput inputText ${e} ${t} ${c}`]),i.succeed(`input ${r} at (${e}, ${t})`);else if(n.id){let{x:l,y:d}=await Tn(s,a,void 0,void 0,n.id,n.window);await ct(s,a,[`uitest uiInput inputText ${l} ${d} ${c}`]),i.succeed(`input ${r} at (${l}, ${d})`)}else await ct(s,a,[`uitest uiInput text ${c}`]),i.succeed(`input ${r}`)})}var Uv=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(Tx),Bv=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(Rx),Wv=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(xx),Vv=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(Lx),Gv=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(Nx),zv=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(Ox),qv=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(Mx),Jv=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(_x);var pt=new Fx("ui").description("Inspect and interact with UI on a connected device");pt.addCommand($v);pt.addCommand(Eu);pt.addCommand(Hv);pt.addCommand(Uv);pt.addCommand(Bv);pt.addCommand(Wv);pt.addCommand(Vv);pt.addCommand(Gv);pt.addCommand(zv);pt.addCommand(qv);pt.addCommand(Jv);var Yv=pt;import{Command as Rw,InvalidArgumentError as NN}from"commander";import{execa as aL}from"execa";import Ot from"fs";import*as ku from"os";import*as M from"path";var jx=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),$x=/\r/g,Hx=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,Ux=/^<+\s*/,Bx=/\s*>+$/,Wx=[/^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\.$/],Vx=new Set([1]);function Pu(r){if(!r)return"";let e=r.replace(jx,"").replace($x,`
|
|
1378
1383
|
`).split(`
|
|
1379
|
-
`).map(
|
|
1384
|
+
`).map(Gx).map(t=>t.trimEnd()).filter(t=>qx(t));return e.length>0?`${e.join(`
|
|
1380
1385
|
`)}
|
|
1381
|
-
`:""}function
|
|
1382
|
-
[output truncated: exceeded ${
|
|
1383
|
-
`};if(
|
|
1384
|
-
`);if(t.length>1&&t.every(
|
|
1385
|
-
`};let o=[e.slice(0,
|
|
1386
|
-
`);return{jsonText:e.slice(
|
|
1387
|
-
`:""}}function
|
|
1388
|
-
${
|
|
1389
|
-
`;let t=e===void 0?
|
|
1386
|
+
`:""}function Gx(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:Vx.has(t.messageType)?"":t.content}catch{return r}}var Kv=50*1024*1024;function ew(r){let e=Pu(r).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(e.length>Kv)return{jsonText:void 0,diagnostics:`${e.slice(0,1024)}
|
|
1387
|
+
[output truncated: exceeded ${Kv} bytes]
|
|
1388
|
+
`};if(Cu(e))return{jsonText:e,diagnostics:""};let t=e.split(`
|
|
1389
|
+
`);if(t.length>1&&t.every(Cu))return{jsonText:JSON.stringify(t.map(i=>JSON.parse(i))),diagnostics:""};let n=Jx(e);if(!n)return{jsonText:void 0,diagnostics:`${e}
|
|
1390
|
+
`};let o=[e.slice(0,n.start).trim(),e.slice(n.end).trim()].filter(Boolean).join(`
|
|
1391
|
+
`);return{jsonText:e.slice(n.start,n.end),diagnostics:o?`${o}
|
|
1392
|
+
`:""}}function zx(r){return Hx.test(r.trim())}function qx(r){let e=r.trim();return!!e&&!zx(e)&&!Wx.some(t=>t.test(e))}function Cu(r){try{return JSON.parse(r),!0}catch{return!1}}function Jx(r){for(let e=0;e<r.length;e++){let t=r[e];if(t!=="["&&t!=="{")continue;let o=Yx(r,e,t,t==="["?"]":"}");if(o!==-1&&Cu(r.slice(e,o+1)))return{start:e,end:o+1}}}function Yx(r,e,t,n){let o=0,i=!1,s=!1;for(let a=e;a<r.length;a++){let c=r[a];if(s){s=!1;continue}if(c==="\\"&&i){s=!0;continue}if(c==='"'){i=!i;continue}if(!i){if(c===t)o++;else if(c===n&&(o--,o===0))return a}}return-1}var Xv=["Error","Warning","Suggestion","Info","Off","Unknown"];function tw(r){let e=Au(r);return{issues:Qx(e),summary:Kx(r,e)}}function Kx(r,e){let t=tL(e);return{filesChecked:rL(r).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Au(r,e=""){if(Array.isArray(r))return r.flatMap(i=>Au(i,e));if(!rw(r))return[];let t=ji(r,["filePath","file","path"])??e,n=Xx(r,t);if(n.length>0)return n;let o=Zx(r,t);return o?[o]:[]}function Xx(r,e){let t=["messages","defects","issues","results","files"];for(let n of t){let o=r[n];if(Array.isArray(o)){let i=o.flatMap(s=>Au(s,e));if(i.length>0)return i}}return[]}function Zx(r,e){let t=ji(r,["message","description","desc","detail"])??"",n=sL(ji(r,["rule","ruleId","ruleName"])),o=oL(r,["severity","level"]),i=ji(r,["filePath","file","path"])??e;if(!(!t&&!n&&o==="Unknown"))return{file:i,line:Qv(r,["line","reportLine"]),column:Qv(r,["column","reportColumn"]),severity:o,rule:n,message:t}}function Qx(r){return[...r].sort((e,t)=>{let n=Zv(e.severity)-Zv(t.severity);return n===0?eL(e,t):n})}function eL(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 tL(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 rL(r){let e=new Set;return Iu(e,r,""),e}function Iu(r,e,t){if(Array.isArray(e)){for(let o of e)Iu(r,o,t);return}if(!rw(e))return;let n=ji(e,["filePath","file","path"])??t;n&&r.add(n),nL(r,e,n)}function nL(r,e,t){let n=["messages","defects","issues","results","files"];for(let o of n){let i=e[o];if(Array.isArray(i))for(let s of i)Iu(r,s,t)}}function oL(r,e){for(let t of e){let n=r[t];if(typeof n=="string"||typeof n=="number")return iL(n)}return"Unknown"}function iL(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 sL(r){let e=r?.normalize("NFKC").trim();if(e)return e.replace(Ux,"").replace(Bx,"").toLowerCase()}function Zv(r){let e=Xv.indexOf(r);return e===-1?Xv.length:e}function ji(r,e){for(let t of e){let n=r[t];if(typeof n=="string")return n}}function Qv(r,e){for(let t of e){let n=r[t];if(typeof n=="number")return n}}function rw(r){return typeof r=="object"&&r!==null}var Mr=class extends Error{code;constructor(e,t,n){super(t,n),this.name="ValidationError",this.code=e}},nw="deveco-codelinter-",ow=[".ets",".ts",".js"],$i=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 V.discover(e).rootDir}catch{return e}}async check(e){let t=Ot.mkdtempSync(M.join(ku.tmpdir(),nw)),n=M.join(t,"report.json");try{let o=r.resolveProjectRoot(this.cwd),i=this.resolveLintTarget(e.lintPath,o),s=this.resolveConfigPath(e.configPath,i),a=this.buildNativeArgs(e,i.path,s,n,t,i.projectRoot??o),c=await this.run(a),l=ew(c.stdout),d=l.diagnostics+Pu(c.stderr);try{let g=this.readJsonReport(n,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:tw(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let n=e?M.resolve(this.cwd,e):t,o=this.resolveRealPath(n,"Lint path"),i=Ot.statSync(o);if(!i.isFile()&&!i.isDirectory())throw new Mr("errorCode",`Lint path must be a file or directory: ${n}`);if(i.isFile()){let a=M.extname(o).toLowerCase();if(!ow.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${ow.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.isDirectory());if(e!==void 0&&s===void 0)throw new Mr("errorCode",`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${o}`);return{path:o,projectRoot:s}}resolveConfigPath(e,t){let n=e?M.resolve(this.cwd,e):M.join(t.projectRoot??this.cwd,"code-linter.json5"),o=this.resolveRealPath(n,"`--config-path`");if(!Ot.statSync(o).isFile())throw new Mr("errorCode",`--config-path must point to a file: ${n}`);if(t.projectRoot){let i=this.discoverProjectRoot(o,!1);if(i===void 0||M.relative(t.projectRoot,i)!=="")throw new Mr("errorCode",`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${i??"not found"}.`)}return o}discoverProjectRoot(e,t){let n=t?e:M.dirname(e);try{return Ot.realpathSync(V.discover(n).rootDir)}catch{return}}resolveRealPath(e,t){try{return Ot.realpathSync(e)}catch(n){throw new Mr("errorCode",`${t} does not exist or cannot be resolved: ${e}`,{cause:n})}}buildNativeArgs(e,t,n,o,i,s){if(this.resolution.isLegacyStudioArgs)return this.buildLegacyNativeArgs(e,t,n,i,s);let a=["--config",n];return e.fix&&a.push("--fix"),e.incremental&&a.push("--incremental"),a.push("--product",e.product,"--format","json","--output",o,t),a}buildLegacyNativeArgs(e,t,n,o,i){let s=String(this.toolProvider.getMaxApiLevel()),a=this.toolProvider.getSdkPlatformVersion(),c=M.join(o,"check-paths.json");Ot.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",i,"--logPath",M.join(o,"codelinter.log"),"--workdir",M.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(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${n}`);let o=await aL(this.resolution.command,t,{cwd:n,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Ot.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let o=(Ot.existsSync(e)?Ot.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!o)throw new Mr("errorCode","Native JSON report was not generated.");return JSON.parse(o)}removeTempDir(e){let t=M.resolve(e),n=M.resolve(ku.tmpdir());!(t.startsWith(`${n}${M.sep}`)||t===n)||!M.basename(t).startsWith(nw)||Ot.rmSync(t,{recursive:!0,force:!0})}static isModernStudioEntry(e){let t=["plugins","codelinter","run","index.js"],n=M.normalize(e).split(M.sep).slice(-t.length);return t.every((o,i)=>n[i]?.toLowerCase()===o)}static resolveWithToolProvider(e){let t=r.getSource(e),n=e.toolchainRoot,o=e.codelinterPath,i=e.sdkPath,s=r.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c=t==="ide"&&!r.isModernStudioEntry(o),l={command:e.nodePath,argsPrefix:[o,i],env:{...process.env,PATH:[...s,process.env.PATH||""].join(M.delimiter),DEVECO_SDK_HOME:i},isLegacyStudioArgs:c};return t==="command-line-tools"&&(l.workingDirectory=n,l.runtimeDirectories=[r.getResultDirectory(o)]),m(`[CodelinterAdapter] Selected ${a} entry: ${o}`),l}static getPathEntries(e,t){let n=[M.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&n.unshift(M.dirname(e.javaPath)),n}static getResultDirectory(e){return M.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as pc,yellow as pw}from"colorette";import{Argument as vL,Command as wL,InvalidArgumentError as Fr}from"commander";import Ui from"fs";import*as ze from"path";import*as Hi from"path";var iw="n/a",sw=/\\/g,cL=/\|/g,lL=/\r?\n/g;function aw(r,e){if(r.issues.length===0)return`No defects found.
|
|
1393
|
+
${Du(r.summary)}
|
|
1394
|
+
`;let t=e===void 0?r.issues:r.issues.slice(0,e),n=[uL(t),Du(r.summary)];return e!==void 0&&t.length<r.issues.length&&n.push(dL(r.issues.length,t.length)),`${n.join(`
|
|
1390
1395
|
`)}
|
|
1391
|
-
`}function
|
|
1392
|
-
`)}function
|
|
1393
|
-
`)}function
|
|
1394
|
-
`}function
|
|
1395
|
-
`)}function
|
|
1396
|
-
|
|
1397
|
-
|
|
1396
|
+
`}function cw(r,e){return[Du(r.summary),`Full report: ${Tu(e)}`,""].join(`
|
|
1397
|
+
`)}function lw(r){let e=["# CodeLinter report",""];return r.issues.length===0?e.push("No defects found.",""):e.push(...pL(r.issues),""),e.push("## Summary","",...fL(r.summary),""),e.join(`
|
|
1398
|
+
`)}function dw(r){return`${JSON.stringify(r,null,2)}
|
|
1399
|
+
`}function Du(r){return`Summary: Issues: ${mt(r.issues)} | Errors: ${mt(r.errors)} | Warnings: ${mt(r.warnings)} | Suggestions: ${mt(r.suggestions)} | Files checked: ${mt(r.filesChecked)}`}function dL(r,e){return`Showing ${mt(e)} of ${mt(r)} issues. Use --output-path <path> to write all results.`}function uL(r){let e=["No","File","Line","Column","Severity","Rule","Message"],t=r.map((n,o)=>({cells:gL(n,o+1)}));return["CodeLinter report","",Ut(e,t)].join(`
|
|
1400
|
+
`)}function pL(r){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,n]of r.entries())e.push(mL(n,t+1));return e}function mL(r,e){return`| ${[String(e),Tu(_r(r.file)),uc(r.line),uc(r.column),_r(r.severity),_r(r.rule),_r(r.message)].map(hL).join(" | ")} |`}function fL(r){return[`- Issues: ${mt(r.issues)}`,`- Errors: ${mt(r.errors)}`,`- Warnings: ${mt(r.warnings)}`,`- Suggestions: ${mt(r.suggestions)}`,`- Files checked: ${mt(r.filesChecked)}`]}function hL(r){return r.replace(sw,"\\\\").replace(cL,"\\|").replace(lL,"<br>")}function gL(r,e){return[String(e),Tu(_r(yL(r.file))),uc(r.line),uc(r.column),_r(r.severity),_r(r.rule),_r(r.message)]}function yL(r){if(!Hi.isAbsolute(r))return r;let e=Hi.relative(process.cwd(),r);return!e||e.startsWith("..")||Hi.isAbsolute(e)?r:e}function Tu(r){return r.replace(sw,"/")}function _r(r){let e=r?.trim();return e||iw}function uc(r){return r===void 0?iw:String(r)}function mt(r){return r.toLocaleString("en-US")}var Ru=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function SL(r){let e=r;return r instanceof Ru?r.code:e.code??e.name??"UnknownError"}async function uw(r,e,t,n){let o=await $e(process.pid),i=o!==null?de(Number(o)*1024):"unknown",s={event:S.CheckCommand,args:n,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var bL=/^-?\d+$/;function xu(){return new wL("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("-h, --help","display help for command").addArgument(new vL("[path]","File or directory to lint").argParser(IL)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",CL).option("--product <product>","Product name defined in build-profile.json5",PL,"default").option("--format <format>","Report format (choices: default, json)",EL,"default").option("--output-path <path>","Complete report file or directory",AL).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",kL).action(DL)}function EL(r){if(r==="default"||r==="json")return r;throw new Fr("Invalid --format. Expected one of: default, json.")}function CL(r){Lu(r,"--config-path");let e=ze.extname(r).toLowerCase();if(e!==".json"&&e!==".json5")throw new Fr("`--config-path` must point to a .json or .json5 file.");return r}function PL(r){return mw(r,"product"),r}function AL(r){return Lu(r,"--output-path"),r}function IL(r){return Lu(r,"path"),r}function kL(r){if(mw(r,"limit"),!bL.test(r))throw new Fr("`--limit` must be a positive integer.");let e=Number.parseInt(r,10);if(e<=0||!Number.isSafeInteger(e))throw new Fr("`--limit` must be an integer greater than 0.");return e}function mw(r,e){if(r.trim().length===0||gw(r))throw new Fr(`Invalid --${e} value.`)}function Lu(r,e){let t=`\`${e}\``;if(r.length===0||gw(r))throw new Fr(`${t} must be a non-empty path without control characters.`)}async function DL(r,e,t){let n=Date.now(),o=["check","lint"];try{let i=process.cwd(),s=await k.new(),a=new $i(s,i),c=xL(s,a,t,e),l=ML(c.outputPath,c.format,i);e.fix&&console.warn(pw("Running codelinter with --fix. Ensure your project source is trusted."));let d=await TL(a,r,e);HL(d.diagnostics),process.exitCode=NL(d,l,c.format,e.limit,i),await uw(n,!0,null,o)}catch(i){let s=SL(i);throw await uw(n,!1,s,o),i}}async function TL(r,e,t){return LL(r,{lintPath:e,configPath:t.configPath,product:t.product,fix:t.fix,incremental:t.incremental})}function RL(r){return[["format","--format"],["outputPath","--output-path"]].filter(([e])=>r.getOptionValueSource(e)==="cli").map(([,e])=>e)}function xL(r,e,t,n){let o=RL(t);if(o.length===0||e.supportsReportOptions)return n;let i=nr(r.toolchainRoot),s=o.length===1?"option":"options";return console.warn(pw(`Warning: The detected DevEco Studio version is: ${i??"unknown"}. The bundled legacy Code Linter does not support ${s}: ${o.join(", ")}. Action: ignore the unsupported ${s} and continue the lint check with default terminal output.`)),{format:o.includes("--format")?"default":n.format,outputPath:o.includes("--output-path")?void 0:n.outputPath}}async function LL(r,e){let t=new Qe;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 NL(r,e,t,n,o){if(!r.report)return console.error(pc("Failed to generate Code Linter report.")),console.error(pc(r.reportError?.message??"Native JSON report was not generated.")),r.exitCode===0?1:r.exitCode;try{if(e){OL(e,t,r.report);let i=hw(e,o);process.stdout.write(cw(r.report,i))}else process.stdout.write(aw(r.report,n));return r.exitCode}catch(i){return console.error(pc("Failed to generate Code Linter report.")),console.error(pc(i.message)),r.exitCode===0?1:r.exitCode}}function OL(r,e,t){Ui.mkdirSync(ze.dirname(r),{recursive:!0});let n=e==="json"?dw(t):lw(t);try{Ui.writeFileSync(r,n,{encoding:"utf-8",flag:"wx"})}catch(o){throw o.code==="EEXIST"?new Error(`Output file already exists: ${r}`,{cause:o}):o}}function ML(r,e,t){if(!r)return;let n=jL(r,t),o=FL(r,n),i=o?ze.join(n,$L(e)):n;if(o||_L(r,e),Ui.existsSync(i))throw new Fr(`Output file already exists: ${hw(i,t)}`);return i}function _L(r,e){let t=fw(e);if(ze.extname(r).toLowerCase()!==t)throw new Fr(`--output-path must use the ${t} extension for --format ${e}.`)}function FL(r,e){return Ui.existsSync(e)?Ui.statSync(e).isDirectory():r.endsWith("/")||r.endsWith("\\")||ze.extname(r)===""}function jL(r,e){return ze.resolve(e,r)}function $L(r){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((i,s)=>String(i).padStart(s===0?4:2,"0")).join(""),n=[e.getHours(),e.getMinutes(),e.getSeconds()].map(i=>String(i).padStart(2,"0")).join(""),o=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${o}${fw(r)}`}function fw(r){return r==="json"?".json":".md"}function hw(r,e){let t=ze.relative(e,r);return t&&!t.startsWith("..")&&!ze.isAbsolute(t)?t:r}function HL(r){r&&process.stderr.write(r)}function gw(r){for(let e of r){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{execa as UL}from"execa";import Qt from"fs";import BL from"os";import*as z from"path";import{fileURLToPath as WL}from"url";var yw=z.join("resources","arkts-check.cjs"),Bi=class{toolProvider;cwd;constructor(e,t){this.toolProvider=e,this.cwd=t}async check(e){let t=this.resolveProjectRoot(e.projectRoot,e.files),n=this.resolveFiles(t,e.files),o=this.resolveScriptPath(),i=this.buildArgs(o,t,n,e.fix),s=this.buildEnv();m(`Executing: ${this.toolProvider.nodePath} ${i.join(" ")}`);let a=await UL(this.toolProvider.nodePath,i,{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 o=z.resolve(this.cwd,e);if(!Qt.existsSync(o))throw new Error(`Project path not found: ${o}`);if(Qt.statSync(o).isFile()){let s=this.discoverRootFrom(z.dirname(o));if(s)return s;throw new Error(`--project path is a file, not a project root: ${o}
|
|
1401
|
+
Could not find a project-level build-profile.json5 above it. Pass the project root directory instead.`)}if(this.discoverRootFrom(o)!==o)throw new Error(`Not a valid Harmony project root: ${o}
|
|
1402
|
+
(project-level build-profile.json5 not found).`);return o}if(t&&t.length>0)for(let o of t){let i=z.isAbsolute(o)?o:z.resolve(this.cwd,o),s=this.discoverRootFrom(z.dirname(i));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 V.discover(e).rootDir}catch{return}}resolveFiles(e,t){if(t.length===0)return[];let n=t.map(a=>{if(z.isAbsolute(a))return a;let c=z.resolve(this.cwd,a);return Qt.existsSync(c)?c:z.resolve(e,a)}),o=n.filter(a=>!Qt.existsSync(a));if(o.length>0)throw new Error(`File(s) not found:
|
|
1403
|
+
`+o.map(a=>` ${a}`).join(`
|
|
1404
|
+
`));let i=n.filter(a=>{let c=z.relative(e,a);return c.startsWith("..")||z.isAbsolute(c)});if(i.length>0)throw new Error(`File(s) outside the project root ${e}:
|
|
1405
|
+
`+i.map(a=>` ${a}`).join(`
|
|
1406
|
+
`));let s=n.filter(a=>Qt.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):
|
|
1407
|
+
`+n.map(a=>` ${a}`).join(`
|
|
1408
|
+
`));return s}buildArgs(e,t,n,o){let i=[e,"--project",t];return i.push(o?"--fix":"--no-fix"),n.length>0&&i.push("--files",...n),i}buildEnv(){return{...process.env,DEVECO_HOME:this.resolveDevecoHome()}}resolveDevecoHome(){let e=this.toolProvider.toolchainRoot;if(BL.platform()==="darwin"&&!Qt.existsSync(z.join(e,"sdk"))){let t=z.join(e,"Contents");if(Qt.existsSync(z.join(t,"sdk")))return t}return e}parseResult(e,t,n){let o=e.trim();if(!o){let i=t.trim();throw new Error(`arkts-check exited with code ${n} but produced no output`+(i?`: ${i}`:""))}try{let i=JSON.parse(o);return{success:i.success??!1,error:i.error,errors:i.errors??[],fixed:i.fixed??[],alsoModified:i.alsoModified??[],summary:{errorCount:i.summary?.errorCount??0,warnCount:i.summary?.warnCount??0,fixedCount:i.summary?.fixedCount??0,checkerDiagCount:i.summary?.checkerDiagCount,fileCount:i.summary?.fileCount??0}}}catch(i){throw new Error(`Failed to parse arkts-check output: ${o.slice(0,500)}`,{cause:i})}}resolveScriptPath(){let e=WL(import.meta.url),t=z.dirname(e);if(e.includes("dist")){let s=z.dirname(t),a=z.join(s,"src",yw);if(Qt.existsSync(a))return a}let n=z.dirname(t),o=z.dirname(n),i=z.join(o,"src",yw);if(Qt.existsSync(i))return i;throw new Error("arkts-check.cjs not found in deveco-cli package resources. Reinstall deveco-cli.")}};import{red as Ou,yellow as Mu,green as vw}from"colorette";import{Command as VL}from"commander";function GL(r){let e=r;return e.code??e.name??"UnknownError"}async function Nu(r,e,t,n){let o=await $e(process.pid),i=o!==null?de(Number(o)*1024):"unknown",s={event:S.CheckCommand,args:n,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(s,a).catch(()=>{})}function _u(){return new VL("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 zL(r,e)})}async function zL(r,e){let t=Date.now(),n=["check","arkts"];try{let o=await k.new(),i=new Bi(o,process.cwd()),s=new Qe;process.stderr.isTTY&&s.start("Checking ArkTS...");let a;try{a=await i.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(Ou(a.error)),process.exitCode=1,await Nu(t,!1,"CheckFailed",n);return}s.stop(),qL(a),await Nu(t,!0,null,n)}catch(o){throw await Nu(t,!1,GL(o),n),o}}function qL(r){let{errorCount:e,warnCount:t,fixedCount:n,fileCount:o}=r.summary;if(JL(r.fixed,n,r.alsoModified),e===0){console.log(vw(`No errors found in ${o} file(s).`)),ww(r.errors);return}YL(r.errors,e,t),process.exitCode=1}function JL(r,e,t){if(r.length!==0){console.log(vw(`\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(Mu(`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 YL(r,e,t){let n=r.filter(o=>o.severity==="error");console.error(Ou(`ArkTS check found ${e} error(s):`));for(let o of n){let i=o.rule?` (${o.rule})`:"";console.error(Ou(`${o.file}:${o.line}:${o.column} - ${o.severity}: ${o.message}${i}`))}ww(r,t)}function ww(r,e){let t=r.filter(o=>o.severity!=="error");if(t.length===0)return;let n=e??t.length;console.warn(Mu(`
|
|
1409
|
+
Warnings (${n}):`));for(let o of t){let i=o.rule?` (${o.rule})`:"";console.warn(Mu(`${o.file}:${o.line}:${o.column} - ${o.severity}: ${o.message}${i}`))}}import{InvalidArgumentError as KL}from"commander";import*as K from"path";import*as Fu from"os";import{readdirSync as XL,existsSync as mc,readFileSync as ZL,unlinkSync as QL,copyFileSync as Cw,writeFileSync as Pw}from"fs";import{execa as eN}from"execa";import{cyan as Se,yellow as Aw}from"colorette";import tN from"ora";var ie=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function ju(r){let e=r;return r instanceof ie?r.code:e.code??e.name??"UnknownError"}async function go(r,e,t,n){let o=await $e(process.pid),i=o!==null?de(Number(o)*1024):"unknown",s={event:S.CheckCommand,args:n,mcpMemory:i,lspMemory:"unknown"},a={duration_ms:Date.now()-r,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var rN=["default","csv","json"],Sw=["default","json"];function nN(r){return[...r].sort((e,t)=>{let n=bw(e),o=bw(t);return n.apiVersion-o.apiVersion||n.suffix.localeCompare(o.suffix)})}function bw(r){let e=r.match(/\((\d+)\)/),t=e?Number(e[1]):0,n=r.lastIndexOf("_"),o=n>=0?r.slice(n+1):r;return{apiVersion:t,suffix:o}}function Iw(r){let t=XL(r,{withFileTypes:!0}).filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".json")).map(n=>n.name.slice(0,-5));return nN(t)}async function kw(r){if(r=r===void 0?"default":r,!Sw.includes(r))throw new Error(`--format must be ${Sw.join(" or ")}. got "${r}"`);let e=Date.now(),t=["check","compat","versions"];try{let n=await k.new(),{apiChangeDir:o}=n.getApiscanPaths();m(Se(`[compat:versions] apiChangeDir: "${o}"`));let i=Iw(o);if(r==="json")console.log(JSON.stringify({versions:i,count:i.length},null,2));else{if(i.length===0){console.log("No SDK versions available."),await go(e,!0,null,t);return}console.log(i.join(`
|
|
1410
|
+
`))}await go(e,!0,null,t)}catch(n){let o=ju(n);throw await go(e,!1,o,t),n}}var Ew=new Set([".ets",".c",".cpp"]);function oN(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 o=r.profile.modules.map(s=>s.name).join(", "),i=n.length>1?"are":"is";throw new ie("errorCode",`Module ${n.map(s=>`"${s}"`).join(", ")} ${i} not defined in build-profile.json5. Available modules: ${o}.`)}function iN(r){for(let e of r){let t=K.resolve(e);if(!mc(t))throw new ie("errorCode",`File "${e}" does not exist.`);let n=K.extname(t).toLowerCase();if(!Ew.has(n)){let o=Array.from(Ew).join(", ");throw new ie("errorCode",`Unsupported file extension "${n}" for "${e}". Supported: ${o}.`)}}}function sN(r){let e=[],t=[];for(let n of r)K.extname(n).toLowerCase()===".ets"?e.push(n):t.push(n);return{arkTs:e,cpp:t}}function aN(r){let e=[],t=[],n="",o=!1,i=0;for(;i<r.length;){let s=r[i];o?{field:n,inQuotes:o,i}=cN(r,i,s,n,o):s==='"'?(o=!0,i+=1):s===","?(t.push(n),n="",i+=1):s===`
|
|
1411
|
+
`?(t.push(n),e.push(t),t=[],n="",i+=1):(s==="\r"||(n+=s),i+=1)}return(n.length>0||t.length>0)&&(t.push(n),e.push(t)),e}function cN(r,e,t,n,o){return t!=='"'?{field:n+t,inQuotes:o,i:e+1}:r[e+1]==='"'?{field:n+'"',inQuotes:o,i:e+2}:{field:n,inQuotes:!1,i:e+1}}function lN(r,e){return e.map(t=>{let n=o=>{let i=r.indexOf(o);return i>=0&&i<t.length?t[i]:""};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 dN(r){let e=ZL(r,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,n=aN(t);if(n.length<2)return[];let[o,...i]=n;return lN(o,i)}function uN(r,e){let t=r.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let n=t[1].trim();if(K.isAbsolute(n))return n;let o=K.join(e,n);return E.ensurePathWithinRoot(e,o)}function pN(r,e){let t=new Map;for(let i of r){let s=i.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let n=Array.from(t.entries()).sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0])),o=Math.max(5,...n.map(([i])=>i.length));console.log(Se("API change scan summary:")),console.log(` ${"Total".padEnd(o)} ${r.length}`);for(let[i,s]of n)console.log(` ${i.padEnd(o)} ${s}`);e&&console.log(` ${"Report".padEnd(o)} ${e}`)}function mN(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(Se(`Details (showing ${t.length}${n>0?` of ${r.length}`:""}):`));let o=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],i=Math.max(...o.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 o)console.log(` ${c.padEnd(i)} ${s(a[l])}`)}n>0&&console.log(Aw(` ... and ${n} more. you can re-run with --output-path <dir> to save the full report.`))}function fN(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(Aw(`... and ${n} more. you can re-run with --output-path <dir> to save the full report.`))}function hN(r,e){let t=[];for(let n of e){let o=r.profile.modules.find(i=>i.name===n);if(!o)throw new ie("errorCode",`Module "${n}" not found in build-profile.json5.`);t.push(K.resolve(r.rootDir,o.srcPath))}return t}function gN(r,e,t,n){if(!n.sourceVersion||!n.targetVersion)throw new ie("errorCode","source-version and target-version are required.");let o=[r,"--startVersion",n.sourceVersion,"--endVersion",n.targetVersion];if(e.length>0){let{arkTs:i,cpp:s}=sN(e),a=d=>K.resolve(process.cwd(),d),c=i.map(a),l=s.map(a);c.length>0&&o.push("--arkTsFiles",c.join(",")),l.length>0&&o.push("--cppFiles",l.join(","))}else if(n.modules&&n.modules.length>0){let i=hN(t,n.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",Fu.tmpdir()),o}async function yN(r,e){let t=K.dirname(e[0]);try{let o=(await eN(r.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(Se("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
|
|
1398
1412
|
`)||process.stdout.write(`
|
|
1399
|
-
`),console.log(
|
|
1413
|
+
`),console.log(Se("[compat:check] === end stdout ==="))),o}catch(n){let o=n;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(Se("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
|
|
1400
1414
|
`)||process.stdout.write(`
|
|
1401
|
-
`),console.log(
|
|
1402
|
-
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function
|
|
1403
|
-
Run \`devecocli compat versions\` to see all available versions.`)}if(
|
|
1404
|
-
`}function EL(n,e,t,r){r===".csv"?Nw(n,t):Ow(t,jw(e),"utf8"),f(we(`[compat:check] saved report: "${t}"`))}function CL(n,e,t,r){if(r==="json"){let i=q.basename(n,".csv"),s=q.join(t,`${i}.json`);return Ow(s,jw(e),"utf8"),f(we(`[compat:check] saved report: "${s}"`)),s}let o=q.join(t,q.basename(n));return Nw(n,o),f(we(`[compat:check] saved report: "${o}"`)),o}async function PL(n,e){let t=new qe(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(o){throw new ne("errorCode",`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function IL(n,e){mL(n,e);let t=X.discover(process.cwd());e.modules&&e.modules.length>0&&Qx(t,e.modules),n.length>0&&eL(n);let r=await k.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();f(we(`[compat:check] script: "${i}"`));let s=_w(o);fL(e,s),e.outputPath&&f(we(`[compat:check] outputPath: "${e.outputPath}"`));let a=SL(e.outputPath,e.format);return f(we(`[compat:check] outputTarget: ${a.kind}`)),bL(a),{project:t,scriptPath:i,target:a,toolProvider:r}}function AL(n,e,t,r){if(t.kind==="file")return EL(n,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return CL(n,e,t.dirPath,r);if(t.kind==="none")return null;throw new ne("errorCode",`Unexpected output target kind: ${t.kind}`)}async function DL(n,e,t,r,o){let i=Kx({text:"Running compatibility check...",color:"cyan"}).start();try{await PL(n.toolProvider,t);let s=uL(n.scriptPath,e,n.project,t);gL(n.scriptPath,s);let a=await pL(n.toolProvider,s),c=sL(a,pu.tmpdir());if(!c)throw new ne("errorCode","Scanner output format unexpected: missing report path.");f(we(`[compat:check] tmp csv: "${c}"`));let l=iL(c),d=AL(c,l,n.target,t.format);yL(c),i.stop(),hL(l,d,t.format,t.limit,n.target.kind),await uo(r,!0,null,o)}catch(s){i.fail("Compatibility check failed");let a=mu(s);throw await uo(r,!1,a,o),s}}async function $w(n,e){let t=Date.now(),r=["check","compat"];try{let o=await IL(n,e);await DL(o,n,e,t,r)}catch(o){let i=mu(o);throw await uo(t,!1,i,r),o}}function TL(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new kL(`--limit must be a positive integer (got "${n}")`);return e}var fu=new Hw("compat").description("Compatibility checking utilities.");fu.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)",TL,100).action(async(n,e)=>{await $w(n,e)});fu.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 Fw(t)});var RL=new Hw("check").description("Run DevEco project checks").addCommand(fu).addCommand(du()),Uw=RL;import{Command as wO}from"commander";import{green as Fu,red as vO}from"colorette";import ju from"fs";import Iv from"path";import Av from"json5";import{readFileSync as iN}from"fs";import{join as xL}from"path";var ie={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"},We={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:xL(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ve={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"},yt={FORBIDDEN:403,UNAUTHORIZED:401},E={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."},ce={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 Qa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function hu(n){let e=n.replace(We.TEAM_ID_INVALID_CHARS,"");return`${We.CERT_NAME_PREFIX}${e}.cer`}function po(n,e,t){if(n===yt.FORBIDDEN)return e===ve.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===yt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(ve.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(ve.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=LL(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function LL(n){let e=Bw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Bw(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Bw(n){try{return JSON.parse(n)}catch{return null}}function gu(n){return JSON.parse(n)}async function Ww(n){let e=`${ie.BASE_URL}${ie.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:Qa(n)});if(t.statusCode!==200)throw po(t.statusCode,t.statusText,t.data);return gu(t.data)?.certList??[]}async function ec(n,e){return(await Ww(n)).find(r=>r.certName===e)??null}async function yu(n,e){let t=`${ie.BASE_URL}${ie.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:Qa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw po(r.statusCode,r.statusText,r.data);return gu(r.data)?.ret?.code===0}async function wu(n,e,t){let r=`${ie.BASE_URL}${ie.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:We.CERT_TYPE_DEBUG},i=await L.postAllowFailure(r,{headers:Qa(n),params:o});if(i.statusCode!==200)throw po(i.statusCode,i.statusText,i.data);if(!i.data.includes(ve.SUCCESS_MARKER))throw po(void 0,i.statusText,i.data)}async function vu(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:Qa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw po(r.statusCode,r.statusText,r.data);return gu(r.data)?.urlsInfo?.[0]??null}import{mkdirSync as NL,writeFileSync as OL,existsSync as ML}from"fs";import{dirname as _L}from"path";import{createHash as FL}from"crypto";function jL(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 Oi(n,e,t){jL(n);let{statusCode:r,statusText:o,buffer:i}=await L.getBinaryAllowFailure(n,{timeout:We.DOWNLOAD_CONNECT_TIMEOUT_MS});if(r!==200)throw r===yt.FORBIDDEN&&o===ve.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);if(t){let a=FL("sha256").update(i).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=_L(e);ML(s)||NL(s,{recursive:!0}),OL(e,i)}import nN from"fs/promises";import{readFileSync as rN}from"fs";import tc from"path";import qw from"crypto";import $L from"os";import Mi from"fs/promises";var zw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Vw=["ECC","RSA"],Gw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],HL={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},UL=8,Su=64,BL=/[\\/:*?"<>|=-]/g,wt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function WL(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>Su)throw new Error(`The length of keyAlias cannot exceed ${Su}`);if(!Vw.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Vw.join(" / ")}`);let e=HL[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function VL(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(!Gw.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Gw.join(" / ")}`)}function GL(n){return qw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function qL(n){let e=n?.trim()??"";return e&&e.replace(BL,"_").replace(/\.+/g,"_").slice(0,Su)||wt.productName}async function Jw(){let n=await k.new(),e=n.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;m.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=tc.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Mi.access(r)}catch(o){throw new Error(`Sign tool jar not found: ${r}`,{cause:o})}return{javaPath:e,jarPath:r}}async function zL(n){let{javaPath:e,jarPath:t}=await Jw(),r=["-jar",t,zw.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return m.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function JL(n){let{javaPath:e,jarPath:t}=await Jw(),r=["-jar",t,zw.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 o=r.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(r[s-1])?"******":i);return m.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...r]}async function YL(n){m.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),WL(n);let e=await zL(n),t=await ko(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 m.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function KL(n){m.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),VL(n);let e=await JL(n),t=await ko(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 m.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function XL(n=UL){return qw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function ZL(){let n=$L.homedir();try{await Mi.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=tc.join(n,".ohos","config");try{await Mi.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 Ae(n,e,t){let r=qL(n),o=tc.basename(e),i=GL(e),s=`${r}_${o}_${i}=.${t}`,a=await ZL();return tc.join(a,s)}function QL(n){let e;try{e=X.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function eN(n){try{await Mi.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function tN(n){try{await Mi.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(),o=QL(r);await eN(o),m.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=XL(),s=await Ae(n??"",o,"p12"),a=await Ae(n??"",o,"csr");return console.log("Start generating p12"),await YL({keyAlias:e?.keyAlias??wt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??wt.keyAlg,keySize:e?.keySize??wt.keySize,keystoreFile:s,keystorePwd:i}),await tN(s),console.log("Start generating csr"),await KL({subject:t?.subject??wt.csrSubject,outFile:a,keyAlias:t?.keyAlias??wt.keyAlias,keyPwd:i,signAlg:t?.signAlg??wt.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??wt.keyAlias}}var oN=["p12","cer","csr","p7b"];async function Eu(n,e){for(let t of oN){let r=await Ae(n,e,t);await nN.rm(r,{force:!0})}}function Cu(n){let e;try{e=rN(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!We.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Yw(n,e){return{certPath:await Ae(n,e,"cer"),csrPath:await Ae(n,e,"csr"),p12Path:await Ae(n,e,"p12"),profilePath:await Ae(n,e,"p7b")}}async function Pu(n,e){let t=e??"",r=X.discover(process.cwd()).rootDir;await Eu(t,r);let o=hu(n.teamId),i=await ec(n,o);if(i&&!await yu(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await bu(e),a;try{a=iN(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await wu(n,a,o);let c=await ec(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await vu(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Ae(t,r,"cer");await Oi(l.newUrl,d,l.sha256),Cu(d);let g=await Ae(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 uc from"crypto";import _n from"fs";import*as dv from"path";import DN from"json5";import{execa as av}from"execa";import cv from"node-forge";import{createCipheriv as sN,createDecipheriv as aN,pbkdf2Sync as cN,randomBytes as ku}from"crypto";import{promises as lr}from"fs";import{dirname as lN,join as vt}from"path";var nc=3,_i=16,dN=1e4,Kw="material",uN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),ev="aes-128-gcm",cr=12,rc=16,Nn=4;function Iu(n){return new Uint8Array(ku(n))}function pN(n){return ku(n).toString("hex")}function mN(...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 o=0;for(let i of n)o^=i[r];t[r]=o}return t}function Xw(n,e,t=dN,r=_i){let o=[...n,uN],i=mN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=cN(a,e,t,r,"sha256");return new Uint8Array(c)}function Zw(n,e){let t=ku(cr),r=sN(ev,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(Nn+cr+s.length);return c.writeUInt32BE(a,0),t.copy(c,Nn),s.copy(c,Nn+cr),c}function Qw(n,e){if(e.length<Nn+cr+rc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Nn,Nn+cr),o=e.subarray(Nn+cr,Nn+cr+t);if(o.length<rc)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-rc),s=o.subarray(o.length-rc),a=aN(ev,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function fN(n){try{await lr.rm(n,{recursive:!0,force:!0})}catch{}}async function Au(n){let e=await lr.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 lr.readFile(vt(n,t[0]))}async function Du(n,e){let t=pN(_i),r=vt(n,t);return await lr.writeFile(r,e,{mode:384}),t}var On=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=vt(e,Kw);await fN(t);let r=vt(t,"ac"),o=vt(t,"ce");await lr.mkdir(r,{recursive:!0,mode:448}),await lr.mkdir(o,{recursive:!0,mode:448});for(let d=0;d<nc;d++)await lr.mkdir(vt(t,"fd",String(d)),{recursive:!0,mode:448});let i=Iu(_i),s=[];for(let d=0;d<nc;d++)s.push(Iu(_i));let a=Iu(_i),c=Xw(s,i),l=Zw(c,a);await Du(r,i),await Du(o,l);for(let d=0;d<nc;d++){let g=vt(t,"fd",String(d));await Du(g,s[d])}return a}static async readMaterial(e){let t=vt(e,Kw),r=vt(t,"ac"),o=new Uint8Array(await Au(r)),i=[];for(let d=0;d<nc;d++){let g=vt(t,"fd",String(d)),w=await Au(g);i.push(new Uint8Array(w))}let s=vt(t,"ce"),a=await Au(s),c=Xw(i,o),l=Qw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,r=this.keyChain;this.keyChain=new Promise(o=>{t=o}),await r;try{let o=lN(e);try{return await this.readMaterial(o)}catch{return await this.generateMaterial(o)}}finally{t()}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return Zw(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Qw(r,o).toString("utf8")}};import iv from"fs";import lc from"path";import SN from"json5";import*as oc from"fs";import*as tv from"path";function ic(n){let e=tv.resolve(n);if(!oc.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=oc.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 o=r?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as fo from"fs";import*as Ve from"path";import{debuglog as mo}from"util";var nv={"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 hN(n){return Object.prototype.hasOwnProperty.call(nv,n)}function sc(n){if(hN(n))return nv[n]}var rv={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as gN}from"url";var cc=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 ac(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function ov(n){return n==null||n.length===0}function yN(n){return!ov(n)}function Tu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function wN(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 vN(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 Mn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Ve.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=Ve.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,o=this.getOrCreateSet(this.aclPermissionNamesMap,r),i=this.getOrCreateSet(this.aclPermissionInfoMap,r);o.clear(),i.clear();let s=Ve.join(t.sdkPath,"default","sdk-pkg.json"),a=ic(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}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=Ve.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(fo.existsSync(e))return fo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=gN(e);if(t.includes("dist")){let s=Ve.dirname(t),a=Ve.dirname(s);return Ve.join(a,"src","resources")}let r=Ve.dirname(t),o=Ve.dirname(r),i=Ve.dirname(o);return Ve.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{mo("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:ac(o)?Object.values(o):[]).filter(ac).map(a=>new cc(a));s.forEach(a=>{let c=a.permissionInsteadName;yN(c)&&(a.permissionInsteadName=sc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){mo(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!ac(i))return;let s=i,a=Tu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(ov(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Tu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Tu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:wN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new cc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=vN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=Ve.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!fo.existsSync(t))return;let r;try{r=fo.readFileSync(t,"utf-8")}catch(s){mo(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!ac(s)){mo("json object is null");return}o=s}catch(s){mo(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){mo("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=sc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=sc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function dc(n,e){let t=new Set,r=new Set;Mn.handleSpecificAclPermissions(),Mn.initAclPermission(n,e);for(let o of n.profile.modules){let i=sv(o,n,e,r,lc.join("src","main"));for(let a of i)t.add(a);let s=sv(o,n,e,r,lc.join("src","ohosTest"));for(let a of s)t.add(a)}return bN(r),t}function bN(n){if(n.size>0)throw new Error(rv.DUPLICATE_PERMISSION)}function sv(n,e,t,r,o){let i=CN(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let w of i){if(typeof w!="object"||w===null)continue;let C=EN(w,"name");C&&s.push(C)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=lc.join(t.sdkPath,"default","sdk-pkg.json"),l=ic(c),d=Mn.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(w=>{let C=Number(w.minSupportApiLevel);return Number.isFinite(C)&&C<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function EN(n,e){let t=n[e];return typeof t=="string"?t:""}function CN(n,e,t){let r=lc.join(n,e.srcPath,t,"module.json5"),o=PN(r);if(o==null)return null;let i=IN(o,"module");return i==null?null:AN(i,"requestPermissions")}function PN(n){try{if(!iv.existsSync(n))return null;let e=iv.readFileSync(n,"utf-8");return SN.parse(e)}catch{return null}}function IN(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 AN(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var xu=class{verifyStorePassword(e,t){try{let r=_n.readFileSync(e),o=cv.asn1.fromDer(r.toString("binary"));return cv.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=_n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new uc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new uc.X509Certificate(_n.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=_n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new uc.X509Certificate(i);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 kN(n){let e=_n.readFileSync(n,"utf-8"),t=TN(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Ru(o["bundle-name"]),expiryDate:RN(r?.validity?.["not-after"]),cerFingerprintInProfile:xN(Ru(o["development-certificate"])),deviceUdidsInProfile:LN(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:NN(r?.acls?.["allowed-acls"]),teamIdInProfile:Ru(o["developer-id"])}}function TN(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,o=!1,i=!1;for(let s=e;s<n.length;s++){let a=n[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function RN(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function xN(n){if(!n)return null;try{let t=new uc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function LN(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 NN(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 Ru(n){return typeof n=="string"?n:null}var Fi=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#o(r)??n.#i(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,o=e.teamId,i=e.productName??"default",s=X.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([ON(i,a),_N(t.hdcPath)]),d=null;if(lv(c).allExist)try{d=kN(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(i),deviceUdids:l,storePassword:await MN(a,i,c.storeFile),localAclPermissions:[...dc(s,t)].sort(),hapSignTool:new xu,profileInfo:d}}static#t(e){return e.force?(f("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ye({force:!0})}):null}static#n(e){let t=lv(e.materialPaths);return t.allExist?null:(f(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ye({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(f("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Ye({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(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:Ye({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(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:Ye({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:Ye({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=jN(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:Ye({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return $N(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(f("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ye({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:(f("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Ye({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:(f(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Ye({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:Ye({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:Ye({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:Ye({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function ON(n,e){let[t,r,o,i]=await Promise.all([Ae(n,e,"p12"),Ae(n,e,"csr"),Ae(n,e,"cer"),Ae(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function MN(n,e,t){let r=dv.join(n,"build-profile.json5");if(!_n.existsSync(r))return;let o;try{o=DN.parse(_n.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await On.decryptPassword(a,t)}catch{return}}async function _N(n){f(`Executing: ${n} list targets`);let{stdout:e}=await av(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1405
|
-
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let
|
|
1406
|
-
`);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let
|
|
1407
|
-
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let
|
|
1408
|
-
`);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=r.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function VN(n,e){let{stdout:t}=await Nu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return GN(t)}function GN(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 dr from"fs";import{createHash as qN}from"crypto";import{debuglog as Yt}from"util";import{Buffer as wv}from"buffer";import{createPublicKey as zN,X509Certificate as Ou}from"crypto";import{readFileSync as JN}from"fs";import ur from"node-forge";async function vv(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${ie.BASE_URL}${ie.PROVISION_ADD_TEST_PATH}`,g=YN(t,r),w=await XN(n,d,a||[],r,s,g,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Yt("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let C=w.profileInfo,de=(await tO(n,C.provisionFileUrl)).urlList,Se=w.profileInfo.id;if(de&&de.length>0){let St=await Yw(t,o),Kt=St.profilePath;if(!await nO(de,Kt))throw await yv(n,Se),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await yv(n,Se),dr.existsSync(St.certPath)&&dr.existsSync(Kt)&&dr.existsSync(St.p12Path)){let Tv=dr.readFileSync(St.certPath,"utf8"),Rv=dr.readFileSync(Kt,"utf8");return rO(Rv,Tv,St.p12Path,c,l)||eO(Kt),Kt}}throw new Error(E.ADD_PROFILE_FAIL)}function YN(n,e){let t=n?`${n}_`:"";return`${KN(`${t}${e}_${e}`)}`}function KN(n){return qN("sha256").update(n).digest("hex").substring(0,16)}async function XN(n,e,t,r,o,i,s){ZN(r);let a=_u(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw Yt("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Mu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Yt(`add provision fail: ${l.data}`),QN(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:g}}}function Mu(n,e,t){return n===yt.FORBIDDEN?e===ve.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===yt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ve.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function ZN(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!We.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function QN(n,e){if(n.includes(ve.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ve.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function yv(n,e){if(!e||e.trim().length===0)return;let t=`${ie.BASE_URL}${ie.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:_u(n)});if(r.statusCode!==200)throw Mu(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&Yt(`delete provision failed: ${r.data}`)}function eO(...n){for(let e of n)try{dr.existsSync(e)&&dr.unlinkSync(e)}catch(t){Yt(`delete local sign file error: ${t.message}`)}}async function tO(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=_u(n),o={sourceUrls:e},i=await L.postAllowFailure(t,{headers:r,params:o});if(!i)throw Yt("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw Mu(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Yt("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function nO(n,e){if(!n||n.length===0)return!1;let t=n[0];return await Oi(t.newUrl,e,t.sha256),!0}function rO(n,e,t,r,o){return oO(n,e),r=r||We.TARGET_FRIENDLY_NAME,o=o||"",iO(e,t,r,o),!0}function oO(n,e){if(e.lastIndexOf(We.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(We.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function iO(n,e,t,r){let o=n.matchAll(We.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=sO(l),g=new Date(d.validFrom),w=new Date(d.validTo);if(s<g||s>w){let C=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${C}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!cO(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function sO(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Ou(t);let r=wv.from(t,"base64");return new Ou(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function aO(n){if(n.cert){let e=ur.pki.publicKeyToPem(n.cert.publicKey);return zN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=ur.asn1.toDer(n.asn1).getBytes(),t=wv.from(e,"binary");return new Ou(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Yt(`Failed to parse cert from asn1: ${e}`),null}return null}function cO(n,e,t,r){try{let o=JN(n),i=ur.asn1.fromDer(ur.util.createBuffer(o)),c=ur.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:ur.pki.oids.certBag})[ur.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=aO(l);if(!g)continue;if(r.some(C=>{let z=C.publicKey.export({type:"spki",format:"der"});return g.equals(z)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return Yt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function _u(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var bv="https://developer.huawei.com",lO={"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"},dO="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function uO(n){let e=lO[n];return e?`${bv}${e}`:void 0}function pO(){return`${bv}${dO}`}var mO={"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 Sv(n,e){return(mO[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function fO(n){return Array.from(n).join(", ")}function Ev(n,e){if(n.size===0)return;let t=Mn.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=uO(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let o=new Set;for(let g of r)o.add(g.permissionDisplayName);let i=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;i.add(`${w} (${g.permissionHelpUrlKey})`)}let s=pO(),a=Sv("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=Sv("acl.permissions.warn",[fO(o),l,c]);console.log(d)}var mc=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=X.discover(process.cwd()),{passed:!0,message:""}}catch(t){return f(`[EnvCheck] Project.discover() failed: ${t.message}`),e(ce.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return f(`[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 f(`[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:ce.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import hO from"fs";import Cv from"path";var fc=class{constructor(e){this.toolProvider=e}toolProvider;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,r=Cv.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!hO.existsSync(r)){let o=Cv.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var hc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await xe.getUserInfo()}catch(e){return f(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await xe.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(ce.LOGIN_REQUIRED)}catch(t){return f(`[EnvCheck] Login check failed: ${t.message}`),e(ce.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(ce.TEAM_INFO_FAILED);try{if((await dn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return f(`[EnvCheck] Team API error: ${r.message}`),e(ce.TEAM_INFO_FAILED)}return f("[EnvCheck] No teams found for current user"),e(ce.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(ce.REALNAME_REQUIRED):t.isRealName!==!0?(f("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(ce.REALNAME_REQUIRED)):{passed:!0,message:""}:e(ce.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await dn();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return f(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return f(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(ce.REGION_CHINA_ONLY):{passed:!0,message:""}:(f("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(ce.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function gO(n){try{let{teamList:e}=await dn();if(e.length>0)return e[0].id}catch(e){f(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function yO(n){let e=await xe.getUserInfo(),t=await xe.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await gO(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await pc(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var gc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await yO(t);if(r.length>0)return f(`[EnvCheck] Scenario 4 Device check: ${r.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 i=await ae.from(this.toolProvider).listDevices();return i.length===0?(f("[EnvCheck] Scenario 4 Device check: no local devices found"),e(ce.DEVICE_MISSING)):i.some(a=>It(a.serial))?{passed:!0,message:""}:(f("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(ce.DEVICE_MISSING))}catch(r){return f(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(ce.DEVICE_DETECT_FAILED)}}};var yc=class{projectChecker=new mc;toolchainChecker=null;authChecker=new hc;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await k.new();return this.toolchainChecker=new fc(e),this.deviceChecker=new gc(e),!0}catch(e){throw f(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(ce.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw f(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var Pv=5*1024*1024;function SO(n){try{let e=ju.statSync(n);if(e.size>Pv)throw new Error(`Profile file too large: ${e.size} bytes (max ${Pv} bytes): ${n}`);let t=ju.readFileSync(n,"utf-8");return Av.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${n}`,{cause:e})}}function bO(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function EO(n){if(n.keyPwd===n.storePassword){let r=await On.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await On.encryptedPassword(n.keyPwd,n.p12FilePath),t=await On.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function CO(n,e,t){let r=Iv.join(n,"build-profile.json5"),o=SO(r);bO(o);let i=t??"default",{keyPassword:s,storePassword:a}=await EO(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:wt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(g=>g.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(g=>g.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),ju.writeFileSync(r,Av.stringify(o,null,2),"utf-8")}async function PO(n){let e=await xe.getUserInfo(),t=await xe.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 IO(n){let e=n.product||"default";await new yc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await PO(n),o=await k.new(),{shouldRegenerate:i}=await Fi.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(Fu("Signature generation completed successfully."));return}await AO(n,r,o),console.log(Fu("Signature generation completed successfully."))}async function AO(n,e,t){let r=await Pu(e,n.product),o=DO(n,e,r,t);o.allDeviceIds=await pv(e,t.hdcPath),await vv(e,o);let i=X.discover(process.cwd()).rootDir;await CO(i,r,n.product??"default"),console.log(Fu(`Signing config written to ${Iv.join(i,"build-profile.json5")}`))}function DO(n,e,t,r){let o=process.cwd(),i=X.discover(o),s=dc(i,r);return Ev(s,i),{productName:n.product||"default",bundleName:i.getBundleName(n.product||"default"),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var Dv=new wO("signature").description("Generate application signature.");Dv.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:S.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[]]},t=Date.now(),r=!0,o=null;try{await IO(n)}catch(i){r=!1,o=W(i),console.error(vO(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:r,error_code:o};await D.track(e,i)}});var kv=Dv;if(!Zt())try{D.init(wc.join(rt(),"TraceLogData")),D.startScheduler()}catch(n){h.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Zt())try{let n=await k.new();D.setSourceType(n.sourceType);let e=await k.getCltVersion();e&&D.setCltVersion(e);let t=await k.getStudioVersion();t&&D.setStudioVersion(t)}catch(n){h.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();le.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1415
|
+
`),console.log(Se("[compat:check] === end stdout ===")));let i=new ie("errorCode",`Compatibility scan failed: ${o.message}`+(o.stderr?`
|
|
1416
|
+
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function vN(r,e){if(!rN.includes(e.format))throw new KL(`--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 ie("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 ie("errorCode","--source-version is required.");if(!e.targetVersion)throw new ie("errorCode","--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new ie("errorCode","--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function wN(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 ie("errorCode",`${t.join(" and ")} ${n} not in the available SDK version list.
|
|
1417
|
+
Run \`devecocli compat versions\` to see all available versions.`)}if(r.sourceVersion&&r.targetVersion){let n=e.indexOf(r.sourceVersion),o=e.indexOf(r.targetVersion);if(n>=o)throw new ie("errorCode",`--target-version "${r.targetVersion}" must be later than --source-version "${r.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function SN(r,e,t,n,o){o==="none"&&(t==="json"?fN(r,n):mN(r,n)),pN(r,e)}function bN(r,e){let t=K.dirname(r),n=K.basename(r),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");m(Se(`[compat:check] command: cd "${t}" && node "${n}" ${o}`))}function EN(r){try{QL(r),m(Se(`[compat:check] cleaned up tmp report: "${r}"`))}catch(e){m(Se(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var CN=[".csv",".json"];function PN(r){return CN.includes(r.toLowerCase())}function AN(r,e){if(!r)return{kind:"none"};let t=K.extname(r).toLowerCase();if(!PN(t))return{kind:"dir",dirPath:K.resolve(r)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new ie("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:K.resolve(r),ext:t}}function IN(r){if(r.kind==="file"){if(mc(r.filePath))throw new ie("errorCode",`Target file "${r.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=K.dirname(r.filePath);if(!mc(e))throw new ie("errorCode",`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(r.kind==="dir"&&!mc(r.dirPath))throw new ie("errorCode",`Target directory "${r.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function Dw(r){return JSON.stringify({records:r,count:r.length},null,2)+`
|
|
1418
|
+
`}function kN(r,e,t,n){n===".csv"?Cw(r,t):Pw(t,Dw(e),"utf8"),m(Se(`[compat:check] saved report: "${t}"`))}function DN(r,e,t,n){if(n==="json"){let i=K.basename(r,".csv"),s=K.join(t,`${i}.json`);return Pw(s,Dw(e),"utf8"),m(Se(`[compat:check] saved report: "${s}"`)),s}let o=K.join(t,K.basename(r));return Cw(r,o),m(Se(`[compat:check] saved report: "${o}"`)),o}async function TN(r,e){let t=new Ke(r,process.cwd(),!0),n=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",n)}catch(o){throw new ie("errorCode",`hvigorw compileNative failed (module=${n??"<project>"}): `+o.message,{cause:o})}}async function RN(r,e){vN(r,e);let t=V.discover(process.cwd());e.modules&&e.modules.length>0&&oN(t,e.modules),r.length>0&&iN(r);let n=await k.new(),{apiChangeDir:o,scriptPath:i}=n.getApiscanPaths();m(Se(`[compat:check] script: "${i}"`));let s=Iw(o);wN(e,s),e.outputPath&&m(Se(`[compat:check] outputPath: "${e.outputPath}"`));let a=AN(e.outputPath,e.format);return m(Se(`[compat:check] outputTarget: ${a.kind}`)),IN(a),{project:t,scriptPath:i,target:a,toolProvider:n}}function xN(r,e,t,n){if(t.kind==="file")return kN(r,e,t.filePath,t.ext),t.filePath;if(t.kind==="dir")return DN(r,e,t.dirPath,n);if(t.kind==="none")return null;throw new ie("errorCode",`Unexpected output target kind: ${t.kind}`)}async function LN(r,e,t,n,o){let i=tN({text:"Running compatibility check...",color:"cyan"}).start();try{await TN(r.toolProvider,t);let s=gN(r.scriptPath,e,r.project,t);bN(r.scriptPath,s);let a=await yN(r.toolProvider,s),c=uN(a,Fu.tmpdir());if(!c)throw new ie("errorCode","Scanner output format unexpected: missing report path.");m(Se(`[compat:check] tmp csv: "${c}"`));let l=dN(c),d=xN(c,l,r.target,t.format);EN(c),i.stop(),SN(l,d,t.format,t.limit,r.target.kind),await go(n,!0,null,o)}catch(s){i.fail("Compatibility check failed");let a=ju(s);throw await go(n,!1,a,o),s}}async function Tw(r,e){let t=Date.now(),n=["check","compat"];try{let o=await RN(r,e);await LN(o,r,e,t,n)}catch(o){let i=ju(o);throw await go(t,!1,i,n),o}}function ON(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new NN(`--limit must be a positive integer (got "${r}")`);return e}var $u=new Rw("compat").description("Compatibility checking utilities.");$u.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)",ON,100).action(async(r,e)=>{await Tw(r,e)});$u.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 kw(t)});var MN=new Rw("check").description("Run DevEco project checks").addCommand($u).addCommand(xu()).addCommand(_u()),xw=MN;import{Command as CM}from"commander";import{green as cp,red as PM}from"colorette";import lp from"fs";import hS from"path";import gS from"json5";import{readFileSync as dO}from"fs";import{join as _N}from"path";var ce={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"},qe={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:_N(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},be={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"},St={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."},pe={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 fc(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}function Hu(r){let e=r.replace(qe.TEAM_ID_INVALID_CHARS,"");return`${qe.CERT_NAME_PREFIX}${e}.cer`}function yo(r,e,t){if(r===St.FORBIDDEN)return e===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN);if(r===St.UNAUTHORIZED)return new Error(C.ERR_UNAUTHORIZED);if(t.includes(be.USER_NOT_HARMONY_CODE))return new Error(C.ERR_USER_NOT_HARMONY);if(t.includes(be.CERT_LIMIT_CODE))return new Error(C.ERR_CERT_LIMIT_REACHED);let n=FN(t);return new Error(n??C.ERR_DOWNLOAD_CER)}function FN(r){let e=Lw(r);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let n=typeof t=="string"?Lw(t):t;if(n&&typeof n=="object"){let o=n.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Lw(r){try{return JSON.parse(r)}catch{return null}}function Uu(r){return JSON.parse(r)}async function Nw(r){let e=`${ce.BASE_URL}${ce.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:fc(r)});if(t.statusCode!==200)throw yo(t.statusCode,t.statusText,t.data);return Uu(t.data)?.certList??[]}async function hc(r,e){return(await Nw(r)).find(n=>n.certName===e)??null}async function Bu(r,e){let t=`${ce.BASE_URL}${ce.CERT_DELETE_PATH}`,n=await L.deleteAllowFailure(t,{headers:fc(r),params:{certIds:[e]}});if(n.statusCode!==200)throw yo(n.statusCode,n.statusText,n.data);return Uu(n.data)?.ret?.code===0}async function Wu(r,e,t){let n=`${ce.BASE_URL}${ce.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:qe.CERT_TYPE_DEBUG},i=await L.postAllowFailure(n,{headers:fc(r),params:o});if(i.statusCode!==200)throw yo(i.statusCode,i.statusText,i.data);if(!i.data.includes(be.SUCCESS_MARKER))throw yo(void 0,i.statusText,i.data)}async function Vu(r,e){let t=`${ce.BASE_URL}${ce.CERT_DOWNLOAD_URL_PATH}`,n=await L.postAllowFailure(t,{headers:fc(r),params:{sourceUrls:e}});if(n.statusCode!==200)throw yo(n.statusCode,n.statusText,n.data);return Uu(n.data)?.urlsInfo?.[0]??null}import{mkdirSync as jN,writeFileSync as $N,existsSync as HN}from"fs";import{dirname as UN}from"path";import{createHash as BN}from"crypto";function WN(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 Wi(r,e,t){WN(r);let{statusCode:n,statusText:o,buffer:i}=await L.getBinaryAllowFailure(r,{timeout:qe.DOWNLOAD_CONNECT_TIMEOUT_MS});if(n!==200)throw n===St.FORBIDDEN&&o===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_DOWNLOAD_CER);if(t){let a=BN("sha256").update(i).digest("hex");if(a!==t.toLowerCase())throw new Error(`SHA-256 mismatch for ${e}: expected ${t.toLowerCase()}, got ${a}`)}let s=UN(e);HN(s)||jN(s,{recursive:!0}),$N(e,i)}import aO from"fs/promises";import{readFileSync as cO}from"fs";import gc from"path";import _w from"crypto";import VN from"os";import Vi from"fs/promises";var Fw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Ow=["ECC","RSA"],Mw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],GN={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},zN=8,Gu=64,qN=/[\\/:*?"<>|=-]/g,bt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function JN(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>Gu)throw new Error(`The length of keyAlias cannot exceed ${Gu}`);if(!Ow.includes(r.keyAlg))throw new Error(`Invalid key algorithm ${r.keyAlg}, available: ${Ow.join(" / ")}`);let e=GN[r.keyAlg];if(!e.includes(r.keySize))throw new Error(`Key algorithm ${r.keyAlg} does not support size ${r.keySize}, available: ${e.join(", ")}`)}function YN(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(!Mw.includes(r.signAlg))throw new Error(`Invalid sign algorithm ${r.signAlg}, available: ${Mw.join(" / ")}`)}function KN(r){return _w.createHash("sha256").update(r,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function XN(r){let e=r?.trim()??"";return e&&e.replace(qN,"_").replace(/\.+/g,"_").slice(0,Gu)||bt.productName}async function jw(){let r=await k.new(),e=r.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=r.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let n=gc.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await Vi.access(n)}catch(o){throw new Error(`Sign tool jar not found: ${n}`,{cause:o})}return{javaPath:e,jarPath:n}}async function ZN(r){let{javaPath:e,jarPath:t}=await jw(),n=["-jar",t,Fw.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 o=n.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(n[s-1])?"******":i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...n]}async function QN(r){let{javaPath:e,jarPath:t}=await jw(),n=["-jar",t,Fw.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 o=n.map((i,s)=>s>0&&["-keyPwd","-keystorePwd"].includes(n[s-1])?"******":i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),[e,...n]}async function eO(r){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),JN(r);let e=await ZN(r),t=await No(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 f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function tO(r){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),YN(r);let e=await QN(r),t=await No(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 f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function rO(r=zN){return _w.randomBytes(r).toString("base64url").replaceAll(/[-_=]/g,"")}async function nO(){let r=VN.homedir();try{await Vi.access(r)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=gc.join(r,".ohos","config");try{await Vi.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function De(r,e,t){let n=XN(r),o=gc.basename(e),i=KN(e),s=`${n}_${o}_${i}=.${t}`,a=await nO();return gc.join(a,s)}function oO(r){let e;try{e=V.discover(r).rootDir}catch(t){throw new Error(`Current directory ${r} is not a valid project root`,{cause:t})}return e}async function iO(r){try{await Vi.access(r)}catch(e){throw new Error(`Project directory ${r} is not accessible, missing read/write permissions`,{cause:e})}}async function sO(r){try{await Vi.access(r)}catch(e){throw new Error(`P12 file ${r} does not exist, terminating CSR generation.`,{cause:e})}}async function zu(r,e,t){let n=process.cwd(),o=oO(n);await iO(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=rO(),s=await De(r??"",o,"p12"),a=await De(r??"",o,"csr");return console.log("Start generating p12"),await eO({keyAlias:e?.keyAlias??bt.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??bt.keyAlg,keySize:e?.keySize??bt.keySize,keystoreFile:s,keystorePwd:i}),await sO(s),console.log("Start generating csr"),await tO({subject:t?.subject??bt.csrSubject,outFile:a,keyAlias:t?.keyAlias??bt.keyAlias,keyPwd:i,signAlg:t?.signAlg??bt.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??bt.keyAlias}}var lO=["p12","cer","csr","p7b"];async function qu(r,e){for(let t of lO){let n=await De(r,e,t);await aO.rm(n,{force:!0})}}function Ju(r){let e;try{e=cO(r,"utf-8")}catch{throw new Error(C.ERR_CERT_INVALIDATE)}if(!qe.CERT_PATTERN.test(e))throw new Error(C.ERR_CERT_INVALIDATE)}async function $w(r,e){return{certPath:await De(r,e,"cer"),csrPath:await De(r,e,"csr"),p12Path:await De(r,e,"p12"),profilePath:await De(r,e,"p7b")}}async function Yu(r,e){let t=e??"",n=V.discover(process.cwd()).rootDir;await qu(t,n);let o=Hu(r.teamId),i=await hc(r,o);if(i&&!await Bu(r,i.id))throw new Error(C.ERR_DOWNLOAD_CER);let s=await zu(e),a;try{a=dO(s.csrFilePath,"utf-8")}catch{throw new Error(C.ERR_READ_CSR)}console.log("Start generating certificate"),await Wu(r,a,o);let c=await hc(r,o);if(!c)throw new Error(C.ERR_DOWNLOAD_CER);let l=await Vu(r,c.certObjectId);if(!l)throw new Error(C.ERR_DOWNLOAD_CER);let d=await De(t,n,"cer");await Wi(l.newUrl,d,l.sha256),Ju(d);let g=await De(t,n,"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 Ic from"crypto";import Ur from"fs";import*as eS from"path";import LO from"json5";import{execa as Xw}from"execa";import Zw from"node-forge";import{createCipheriv as uO,createDecipheriv as pO,pbkdf2Sync as mO,randomBytes as Qu}from"crypto";import{promises as gn}from"fs";import{dirname as fO,join as Et}from"path";var yc=3,Gi=16,hO=1e4,Hw="material",gO=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Vw="aes-128-gcm",hn=12,vc=16,jr=4;function Ku(r){return new Uint8Array(Qu(r))}function yO(r){return Qu(r).toString("hex")}function vO(...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 o=0;for(let i of r)o^=i[n];t[n]=o}return t}function Uw(r,e,t=hO,n=Gi){let o=[...r,gO],i=vO(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=mO(a,e,t,n,"sha256");return new Uint8Array(c)}function Bw(r,e){let t=Qu(hn),n=uO(Vw,r,t),o=Buffer.concat([n.update(e),n.final()]),i=n.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(jr+hn+s.length);return c.writeUInt32BE(a,0),t.copy(c,jr),s.copy(c,jr+hn),c}function Ww(r,e){if(e.length<jr+hn+vc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),n=e.subarray(jr,jr+hn),o=e.subarray(jr+hn,jr+hn+t);if(o.length<vc)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-vc),s=o.subarray(o.length-vc),a=pO(Vw,r,n);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function wO(r){try{await gn.rm(r,{recursive:!0,force:!0})}catch{}}async function Xu(r){let e=await gn.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 gn.readFile(Et(r,t[0]))}async function Zu(r,e){let t=yO(Gi),n=Et(r,t);return await gn.writeFile(n,e,{mode:384}),t}var $r=class{static keyChain=Promise.resolve();static async generateMaterial(e){let t=Et(e,Hw);await wO(t);let n=Et(t,"ac"),o=Et(t,"ce");await gn.mkdir(n,{recursive:!0,mode:448}),await gn.mkdir(o,{recursive:!0,mode:448});for(let d=0;d<yc;d++)await gn.mkdir(Et(t,"fd",String(d)),{recursive:!0,mode:448});let i=Ku(Gi),s=[];for(let d=0;d<yc;d++)s.push(Ku(Gi));let a=Ku(Gi),c=Uw(s,i),l=Bw(c,a);await Zu(n,i),await Zu(o,l);for(let d=0;d<yc;d++){let g=Et(t,"fd",String(d));await Zu(g,s[d])}return a}static async readMaterial(e){let t=Et(e,Hw),n=Et(t,"ac"),o=new Uint8Array(await Xu(n)),i=[];for(let d=0;d<yc;d++){let g=Et(t,"fd",String(d)),v=await Xu(g);i.push(new Uint8Array(v))}let s=Et(t,"ce"),a=await Xu(s),c=Uw(i,o),l=Ww(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t,n=this.keyChain;this.keyChain=new Promise(o=>{t=o}),await n;try{let o=fO(e);try{return await this.readMaterial(o)}catch{return await this.generateMaterial(o)}}finally{t()}}static async encryptedPassword(e,t){let n=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return Bw(n,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let n=await this.getStoreKey(t),o=Buffer.from(e,"hex");return Ww(n,o).toString("utf8")}};import Yw from"fs";import Pc from"path";import AO from"json5";import*as wc from"fs";import*as Gw from"path";function Sc(r){let e=Gw.resolve(r);if(!wc.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=wc.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 o=n?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as wo from"fs";import*as Je from"path";import{debuglog as vo}from"util";var zw={"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 SO(r){return Object.prototype.hasOwnProperty.call(zw,r)}function bc(r){if(SO(r))return zw[r]}var qw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as bO}from"url";var Cc=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 Ec(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Jw(r){return r==null||r.length===0}function EO(r){return!Jw(r)}function ep(r,e){let t=r[e];return typeof t=="string"?t:t==null?"":String(t)}function CO(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 PO(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 Hr=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Je.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=Je.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,o=this.getOrCreateSet(this.aclPermissionNamesMap,n),i=this.getOrCreateSet(this.aclPermissionInfoMap,n);o.clear(),i.clear();let s=Je.join(t.sdkPath,"default","sdk-pkg.json"),a=Sc(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}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=Je.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(wo.existsSync(e))return wo.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=bO(e);if(t.includes("dist")){let s=Je.dirname(t),a=Je.dirname(s);return Je.join(a,"src","resources")}let n=Je.dirname(t),o=Je.dirname(n),i=Je.dirname(o);return Je.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let n;try{n=this.readBuiltInConfigText()}catch{vo("read builtin acl permission failed.");return}if(n!==void 0)try{let o=JSON.parse(n),s=(Array.isArray(o)?o:Ec(o)?Object.values(o):[]).filter(Ec).map(a=>new Cc(a));s.forEach(a=>{let c=a.permissionInsteadName;EO(c)&&(a.permissionInsteadName=bc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){vo(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,n){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!Ec(i))return;let s=i,a=ep(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Jw(a)||(this.generateAclInfos(n,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||ep(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||ep(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:CO(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,n){let o=new Cc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=PO(n,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=Je.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!wo.existsSync(t))return;let n;try{n=wo.readFileSync(t,"utf-8")}catch(s){vo(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(n);if(!Ec(s)){vo("json object is null");return}o=s}catch(s){vo(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){vo("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=bc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=bc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Ac(r,e){let t=new Set,n=new Set;Hr.handleSpecificAclPermissions(),Hr.initAclPermission(r,e);for(let o of r.profile.modules){let i=Kw(o,r,e,n,Pc.join("src","main"));for(let a of i)t.add(a);let s=Kw(o,r,e,n,Pc.join("src","ohosTest"));for(let a of s)t.add(a)}return IO(n),t}function IO(r){if(r.size>0)throw new Error(qw.DUPLICATE_PERMISSION)}function Kw(r,e,t,n,o){let i=DO(e.rootDir,r,o);if(i==null)return new Set;let s=[];for(let v of i){if(typeof v!="object"||v===null)continue;let b=kO(v,"name");b&&s.push(b)}let a=new Set(s);a.size!==s.length&&n.add(r.name);let c=Pc.join(t.sdkPath,"default","sdk-pkg.json"),l=Sc(c),d=Hr.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(v=>{let b=Number(v.minSupportApiLevel);return Number.isFinite(b)&&b<=l}).map(v=>v.permissionName));for(let v of Array.from(a))g.has(v)||a.delete(v);return a}function kO(r,e){let t=r[e];return typeof t=="string"?t:""}function DO(r,e,t){let n=Pc.join(r,e.srcPath,t,"module.json5"),o=TO(n);if(o==null)return null;let i=RO(o,"module");return i==null?null:xO(i,"requestPermissions")}function TO(r){try{if(!Yw.existsSync(r))return null;let e=Yw.readFileSync(r,"utf-8");return AO.parse(e)}catch{return null}}function RO(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 xO(r,e){if(r==null||typeof r!="object")return null;let t=r[e];return Array.isArray(t)?t:null}var rp=class{verifyStorePassword(e,t){try{let n=Ur.readFileSync(e),o=Zw.asn1.fromDer(n.toString("binary"));return Zw.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let n=Ur.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(n&&n.length>0)return n.map(o=>this.formatFp(new Ic.X509Certificate(o).fingerprint256));try{return[this.formatFp(new Ic.X509Certificate(Ur.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=Ur.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new Ic.X509Certificate(i);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 NO(r){let e=Ur.readFileSync(r,"utf-8"),t=OO(e),n=null;if(t)try{n=JSON.parse(t)}catch{n=null}let o=n?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:tp(o["bundle-name"]),expiryDate:MO(n?.validity?.["not-after"]),cerFingerprintInProfile:_O(tp(o["development-certificate"])),deviceUdidsInProfile:FO(n?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:jO(n?.acls?.["allowed-acls"]),teamIdInProfile:tp(o["developer-id"])}}function OO(r){let e=r.indexOf("{");if(e<0)return null;let t=0,n=-1,o=!1,i=!1;for(let s=e;s<r.length;s++){let a=r[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){n=s;break}}return n<0?null:r.slice(e,n+1)}function MO(r){if(typeof r!="number"||!Number.isFinite(r))return null;let e=new Date(r*1e3);return isNaN(e.getTime())?null:e}function _O(r){if(!r)return null;try{let t=new Ic.X509Certificate(r).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function FO(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 jO(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 tp(r){return typeof r=="string"?r:null}var zi=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.#o(n)??r.#i(n)??r.#s(n)??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,o=e.teamId,i=e.productName??"default",s=V.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([$O(i,a),UO(t.hdcPath)]),d=null;if(Qw(c).allExist)try{d=NO(c.profileFile)}catch{}return{force:n,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(i),deviceUdids:l,storePassword:await HO(a,i,c.storeFile),localAclPermissions:[...Ac(s,t)].sort(),hapSignTool:new rp,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:tt({force:!0})}):null}static#r(e){let t=Qw(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:tt({allFilesExist:!1,missingFiles:t.missing})})}static#n(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=WO(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return VO(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:tt({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:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:tt({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:(m(`[reGenerateSign] local certificate expired at ${n.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${n.toISOString()}`,checkDetails:tt({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:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:tt({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function $O(r,e){let[t,n,o,i]=await Promise.all([De(r,e,"p12"),De(r,e,"csr"),De(r,e,"cer"),De(r,e,"p7b")]);return{storeFile:t,csrFile:n,cerFile:o,profileFile:i}}async function HO(r,e,t){let n=eS.join(r,"build-profile.json5");if(!Ur.existsSync(n))return;let o;try{o=LO.parse(Ur.readFileSync(n,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await $r.decryptPassword(a,t)}catch{return}}async function UO(r){m(`Executing: ${r} list targets`);let{stdout:e}=await Xw(r,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1419
|
+
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let n=[];for(let o of t)try{m(`Executing: ${r} -t ${o} shell bm get -u`);let{stdout:i}=await Xw(r,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=BO(i);s&&n.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return n}function BO(r){let e=r.trim();if(!e)return null;let t=e.split(`
|
|
1420
|
+
`);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+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 Qw(r){let e=[r.storeFile,r.csrFile,r.cerFile,r.profileFile],t=[];for(let n of e)Ur.existsSync(n)||t.push(n);return{allExist:t.length===0,missing:t}}function WO(r,e){let t=[];for(let n of e)r.includes(n)||t.push(n);return{allPresent:t.length===0,missing:t}}function VO(r,e){let t=[...r].sort(),n=[...e].sort();return t.length!==n.length?!1:t.every((o,i)=>o===n[i])}function tt(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 np}from"util";import{execa as op}from"execa";async function rS(r,e){let t=await kc(r);if(!t)throw new Error(C.DEVICE_LIST_EMPTY);let n=await qO(e);if(t.length===0)for(let s of n)await GO(r,s.udid,s.deviceName);else for(let s of n)await zO(r,t,s.udid,s.deviceName);let i=(await kc(r)).map(s=>s.id);if(i.length===0)throw new Error(C.DEVICE_LIST_EMPTY);return i}async function GO(r,e,t){await iS(r,e,nS(t))}async function zO(r,e,t,n){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await iS(r,t,nS(n));return}}}function nS(r){switch(r){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function tS(r,e=1,t=100){let n=`${ce.BASE_URL}${ce.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=sS(r),i=await L.get(n,{headers:o});if(!i)throw np("query devices failed: response is null"),new Error(C.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw oS(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw np("query devices failed: response list is null"),new Error(s.ret?.msg||C.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function oS(r,e,t){return r===St.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN):r===St.UNAUTHORIZED?new Error(C.ERR_UNAUTHORIZED):t.includes(be.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(C.DEVICE_LIMIT_REACHED):new Error(C.ERROR_WHILE_ADD_DEVICE)}async function kc(r){let t=await tS(r,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let n=[...t.deviceList],o=t.total,i=Math.floor(o/100)+(o%100===0?0:1);for(let s=2;s<=i;s++){let a=await tS(r,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;n.push(...a.deviceList)}return n}async function iS(r,e,t){let n=`${ce.BASE_URL}${ce.DEVICE_ADD_PATH}`,o=sS(r),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await L.postAllowFailure(n,{headers:o,params:s});if(!a)throw np("add device failed: response is null"),new Error(C.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw oS(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(be.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(C.DEVICE_LIMIT_REACHED):c.includes(be.DEVICE_NAME_REPEAT_CODE)?new Error(C.DEVICE_NAME_REPEAT):new Error(C.ERROR_WHILE_ADD_DEVICE)}function sS(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}async function qO(r){let{stdout:e}=await op(r,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1421
|
+
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let n=[];for(let o of t)try{let i=await JO(o,r),s=await YO(o,r);i.length>0&&n.push({id:"",udid:i,deviceName:s})}catch{m(`Failed to get device info for ${o}, skipping`)}return n}async function JO(r,e){let{stdout:t}=await op(e,["-t",r,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),n=t.trim();if(!n)return"";let o=n.split(`
|
|
1422
|
+
`);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=n.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function YO(r,e){let{stdout:t}=await op(e,["-c","-t",r,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return KO(t)}function KO(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 yn from"fs";import{createHash as XO}from"crypto";import{debuglog as er}from"util";import{Buffer as cS}from"buffer";import{createPublicKey as ZO,X509Certificate as ip}from"crypto";import{readFileSync as QO}from"fs";import vn from"node-forge";async function lS(r,e){console.log("Start generating profile");let{productName:t,bundleName:n,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(C.DEVICE_LIST_EMPTY);let d=`${ce.BASE_URL}${ce.PROVISION_ADD_TEST_PATH}`,g=eM(t,n),v=await rM(r,d,a||[],n,s,g,i||[]);if(!v||!v.profileInfo||!v.profileInfo.provisionFileUrl)throw er("add provision failed, the provision file url is null"),new Error(C.ADD_PROFILE_FAIL);let b=v.profileInfo,$=(await sM(r,b.provisionFileUrl)).urlList,me=v.profileInfo.id;if($&&$.length>0){let Te=await $w(t,o),Ct=Te.profilePath;if(!await aM($,Ct))throw await aS(r,me),new Error(C.ERROR_WHILE_DOWNLOAD_PROFILE);if(await aS(r,me),yn.existsSync(Te.certPath)&&yn.existsSync(Ct)&&yn.existsSync(Te.p12Path)){let Oc=yn.readFileSync(Te.certPath,"utf8"),Mc=yn.readFileSync(Ct,"utf8");return cM(Mc,Oc,Te.p12Path,c,l)||iM(Ct),Ct}}throw new Error(C.ADD_PROFILE_FAIL)}function eM(r,e){let t=r?`${r}_`:"";return`${tM(`${t}${e}_${e}`)}`}function tM(r){return XO("sha256").update(r).digest("hex").substring(0,16)}async function rM(r,e,t,n,o,i,s){nM(n);let a=ap(r),c={certList:t,packageName:n,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw er("add provision failed: response is null"),new Error(C.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw sp(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw er(`add provision fail: ${l.data}`),oM(l.data,i),new Error(d.ret?.msg||C.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:g}}}function sp(r,e,t){return r===St.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(C.ERR_CERT_NETWORK_ERROR):new Error(C.ERR_FORBIDDEN):r===St.UNAUTHORIZED?new Error(C.ERR_UNAUTHORIZED):t.includes(be.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(C.TEST_PROVISION_EXCEEDS_LIMIT):new Error(C.ADD_PROFILE_FAIL)}function nM(r){if(!r||r.trim().length===0)throw new Error(C.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!qe.BUNDLE_NAME_REGEX.test(r))throw new Error(C.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function oM(r,e){if(r.includes(be.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(C.TEST_PROVISION_EXCEEDS_LIMIT);if(r.includes(be.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(C.PROFILE_NAME_REPEAT)}async function aS(r,e){if(!e||e.trim().length===0)return;let t=`${ce.BASE_URL}${ce.PROVISION_DELETE_PATH}?id=${e}`,n=await L.deleteAllowFailure(t,{headers:ap(r)});if(n.statusCode!==200)throw sp(n.statusCode,n.statusText,n.data);let o=JSON.parse(n.data);(!o||!o.ret||o.ret.code!==0)&&er(`delete provision failed: ${n.data}`)}function iM(...r){for(let e of r)try{yn.existsSync(e)&&yn.unlinkSync(e)}catch(t){er(`delete local sign file error: ${t.message}`)}}async function sM(r,e){let t=`${ce.BASE_URL}${ce.CERT_DOWNLOAD_URL_PATH}`,n=ap(r),o={sourceUrls:e},i=await L.postAllowFailure(t,{headers:n,params:o});if(!i)throw er("get download list failed: response is null"),new Error(C.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw sp(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw er("download: The application does not exist"),new Error(s.ret?.msg||C.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function aM(r,e){if(!r||r.length===0)return!1;let t=r[0];return await Wi(t.newUrl,e,t.sha256),!0}function cM(r,e,t,n,o){return lM(r,e),n=n||qe.TARGET_FRIENDLY_NAME,o=o||"",dM(e,t,n,o),!0}function lM(r,e){if(e.lastIndexOf(qe.CERT_BEGIN_HEADER)<0)throw new Error(C.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(qe.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!r.includes(t))throw new Error(C.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function dM(r,e,t,n){let o=r.matchAll(qe.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=uM(l),g=new Date(d.validFrom),v=new Date(d.validTo);if(s<g||s>v){let b=`Certificate is not valid, Valid from ${g} to ${v}`;throw console.warn(`checkCertificateInValidityPeriod: ${b}`),new Error(C.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(C.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(C.CERTIFICATE_HAS_EXPIRED);if(!mM(e,t,n,i))throw new Error(C.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function uM(r){let e="-----BEGIN CERTIFICATE-----",t=r.trim();try{if(t.startsWith(e))return new ip(t);let n=cS.from(t,"base64");return new ip(n)}catch(n){throw new Error("decodeBase64ToX509Certificate",{cause:n})}}function pM(r){if(r.cert){let e=vn.pki.publicKeyToPem(r.cert.publicKey);return ZO(e).export({type:"spki",format:"der"})}if(r.asn1)try{let e=vn.asn1.toDer(r.asn1).getBytes(),t=cS.from(e,"binary");return new ip(t).publicKey.export({type:"spki",format:"der"})}catch(e){return er(`Failed to parse cert from asn1: ${e}`),null}return null}function mM(r,e,t,n){try{let o=QO(r),i=vn.asn1.fromDer(vn.util.createBuffer(o)),c=vn.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:vn.pki.oids.certBag})[vn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=pM(l);if(!g)continue;if(n.some(b=>{let N=b.publicKey.export({type:"spki",format:"der"});return g.equals(N)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return er(`Failed to process P12 file: ${r}, error: ${i}`),!1}}function ap(r){return{uid:r.uid,teamId:r.teamId,oauth2Token:r.accessToken}}var uS="https://developer.huawei.com",fM={"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"},hM="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function gM(r){let e=fM[r];return e?`${uS}${e}`:void 0}function yM(){return`${uS}${hM}`}var vM={"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 dS(r,e){return(vM[r]??r).replace(/\{(\d+)\}/g,(n,o)=>String(e[Number(o)]??""))}function wM(r){return Array.from(r).join(", ")}function pS(r,e){if(r.size===0)return;let t=Hr.getAclPermissionInfos(e),n=new Set;for(let g of t)r.has(g.permissionName)&&n.add(g);for(let g of n){let v=gM(g.permissionName);v!=null&&(g.permissionHelpUrlKey=v)}let o=new Set;for(let g of n)o.add(g.permissionDisplayName);let i=new Set;for(let g of n)if(g.permissionHelpUrlKey!=null){let v=g.permissionInsteadName??g.permissionDisplayName;i.add(`${v} (${g.permissionHelpUrlKey})`)}let s=yM(),a=dS("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=dS("acl.permissions.warn",[wM(o),l,c]);console.log(d)}var Dc=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=V.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(pe.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(n){return m(`[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 m(`[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:pe.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import SM from"fs";import mS from"path";var Tc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,n=mS.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!SM.existsSync(n)){let o=mS.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var Rc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Me.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Me.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(pe.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(pe.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(pe.TEAM_INFO_FAILED);try{if((await hr()).teamList.length>0)return{passed:!0,message:""}}catch(n){return m(`[EnvCheck] Team API error: ${n.message}`),e(pe.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(pe.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(pe.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(pe.REALNAME_REQUIRED)):{passed:!0,message:""}:e(pe.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let n=e??"";try{let o=await hr();if(n=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.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 m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(o){return m(`[EnvCheck] Team ID check failed: ${o.message}`),{passed:!1,message:`team-id for ${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(pe.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(pe.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function bM(r){try{let{teamList:e}=await hr();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return r??""}async function EM(r){let e=await Me.getUserInfo(),t=await Me.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let n=r||await bM(e.userId);if(!n)throw new Error("No team found");let o={uid:e.userId??"",teamId:n,accessToken:t.accessToken};return(await kc(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var xc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let n=await EM(t);if(n.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${n.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let i=await ue.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(pe.DEVICE_MISSING)):i.some(a=>Dt(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(pe.DEVICE_MISSING))}catch(n){return m(`[EnvCheck] Scenario 4 Device check failed: ${n.message}`),e(pe.DEVICE_DETECT_FAILED)}}};var Lc=class{projectChecker=new Dc;toolchainChecker=null;authChecker=new Rc;deviceChecker=null;constructor(){}async preflight(e){let t=n=>this.blockingFail(n);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 n=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let i of o)if(!n(await i()))return!1;return!(e.teamId&&!n(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await k.new();return this.toolchainChecker=new Tc(e),this.deviceChecker=new xc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(pe.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let n=i=>i.passed?!0:(this.fail(i),!1);if(!n(this.projectChecker.checkProjectDir(t))||!n(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!n(i()))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 m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};var fS=5*1024*1024;function AM(r){try{let e=lp.statSync(r);if(e.size>fS)throw new Error(`Profile file too large: ${e.size} bytes (max ${fS} bytes): ${r}`);let t=lp.readFileSync(r,"utf-8");return gS.parse(t)}catch(e){if(e.code==="ENOENT")return{app:{signingConfigs:[],products:[]}};throw new Error(`Failed to read profile: ${r}`,{cause:e})}}function IM(r){r.app||(r.app={signingConfigs:[],products:[]}),r.app.signingConfigs||(r.app.signingConfigs=[]),r.app.products||(r.app.products=[])}async function kM(r){if(r.keyPwd===r.storePassword){let n=await $r.encryptedPassword(r.keyPwd,r.p12FilePath);return{keyPassword:n,storePassword:n}}let e=await $r.encryptedPassword(r.keyPwd,r.p12FilePath),t=await $r.encryptedPassword(r.storePassword,r.p12FilePath);return{keyPassword:e,storePassword:t}}async function DM(r,e,t){let n=hS.join(r,"build-profile.json5"),o=AM(n);IM(o);let i=t??"default",{keyPassword:s,storePassword:a}=await kM(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:bt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(g=>g.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(g=>g.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),lp.writeFileSync(n,gS.stringify(o,null,2),"utf-8")}async function TM(r){let e=await Me.getUserInfo(),t=await Me.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??""}}async function RM(r){let e=r.product||"default";await new Lc().preflight({productName:e,teamId:r.teamId}),console.log("Executing signature generate command");let n=await TM(r),o=await k.new(),{shouldRegenerate:i}=await zi.shouldRegenerate({force:r.force??!1,teamId:n.teamId,productName:r.product},o);if(!i){console.log(cp("Signature generation completed successfully."));return}await xM(r,n,o),console.log(cp("Signature generation completed successfully."))}async function xM(r,e,t){let n=await Yu(e,r.product),o=LM(r,e,n,t);o.allDeviceIds=await rS(e,t.hdcPath),await lS(e,o);let i=V.discover(process.cwd()).rootDir;await DM(i,n,r.product??"default"),console.log(cp(`Signing config written to ${hS.join(i,"build-profile.json5")}`))}function LM(r,e,t,n){let o=process.cwd(),i=V.discover(o),s=Ac(i,n);return pS(s,i),{productName:r.product||"default",bundleName:i.getBundleName(r.product||"default"),projectPath:i.rootDir,teamId:e.teamId,force:r.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var yS=new CM("signature").description("Generate application signature.");yS.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 r=>{let e={event:S.CommandExecuted,args:["signature","generate",...r.force?["--force"]:[],...r.teamId?["--team-id"]:[],...r.product?["--product"]:[]]},t=Date.now(),n=!0,o=null;try{await RM(r)}catch(i){n=!1,o=q(i),console.error(PM(i.message)),process.exitCode=1}finally{let i={duration_ms:Date.now()-t,success:n,error_code:o};await I.track(e,i)}});var vS=yS;if(!rr())try{I.init(Nc.join(lt(),"TraceLogData")),I.startScheduler()}catch(r){h.error(`[telemetry] init failed: ${r instanceof Error?r.message:String(r)}`)}(async()=>{if(!rr())try{let r=await k.new();I.setSourceType(r.sourceType);let e=await k.getCltVersion();e&&I.setCltVersion(e);let t=await k.getStudioVersion();t&&I.setStudioVersion(t)}catch(r){h.error(`[telemetry] toolchain info failed: ${r instanceof Error?r.message:String(r)}`)}})();le.name("devecocli").description(`HarmonyOS application development command line tool
|
|
1409
1423
|
|
|
1410
|
-
Privacy: ${
|
|
1424
|
+
Privacy: ${bo.PRIVACY_URL}`).version("1.3.3-Test.2");var wS=le.options.find(r=>r.long==="--version");wS&&(wS.flags="-V, -v, --version");le.addCommand(Sm);le.addCommand(Sf);le.addCommand(Tf);le.addCommand(Yf);le.addCommand(Eh);le.addCommand(Gh);le.addCommand(vg);le.addCommand(bg);le.addCommand(Lg);le.addCommand(Ug);le.addCommand(my);le.addCommand(Fv);le.addCommand(Yv);le.addCommand(xw);le.addCommand(vS);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 dp=process.argv.slice(2);dp.length>=2&&dp[dp.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function OM(r){let e=r;for(;e.parent&&e.parent!==le;)e=e.parent;return e}var MM=new Set(["update","auth","serve"]);le.hook("preAction",async(r,e)=>{let t=OM(e),n=xn();if(t.name()==="update")return;let o=new pr(Nc.join(lt(),"update")),i=ur();if(n==="off"&&o.getBlockedVersions().includes(i))throw new Error(`devecocli ${i} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||MM.has(t.name())||await k.checkVersion()});le.hook("postAction",async(r,e)=>{if(process.exitCode||xn()!=="off")return;await new zo(e).checkAndNotify()});le.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{Yc(Nc.join(lt(),"TraceLogData"))}catch(r){h.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(NM(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});
|