@deveco-test/deveco-cli-openharmony-arm64 1.3.12-Test.1 → 1.3.13-23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,90 +1,90 @@
1
1
  #!/usr/bin/env node
2
- var KS=Object.defineProperty;var XS=(n,e)=>{for(var t in e)KS(n,t,{get:e[t],enumerable:!0})};import*as Dp from"path";import{program as de}from"commander";import{red as gF}from"colorette";var bi={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Qo={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"},J={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"},Hn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Ei={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"},Pi={baseUrl:J.LOGIN_URL,authUrl:J.AUTH_APPLY_PATH,tempTokenCheckUrl:J.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:J.JWT_TOKEN_CHECK_PATH,successRedirectUrl:J.LOGIN_SUCCESS_PATH,failedRedirectUrl:J.LOGIN_FAILED_PATH,logoutUrl:J.LOGOUT_PATH,agcTeamListUrl:J.AGC_TEAM_LIST_URL,appId:Ee.APP_ID,timeout:bi.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as xE}from"commander";import{green as kl,red as Nm,yellow as xl}from"colorette";import ne from"fs";import*as V from"path";import Mt from"json5";import*as Zc from"fs";import*as Pe from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&process.stderr.write(`[DEBUG] ${n}
2
+ var gb=Object.defineProperty;var hb=(n,e)=>{for(var t in e)gb(n,t,{get:e[t],enumerable:!0})};import*as Wp from"path";import{program as de}from"commander";import{red as jF}from"colorette";var Ci={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},rs={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"},J={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"},Gn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Ii={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"},Di={baseUrl:J.LOGIN_URL,authUrl:J.AUTH_APPLY_PATH,tempTokenCheckUrl:J.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:J.JWT_TOKEN_CHECK_PATH,successRedirectUrl:J.LOGIN_SUCCESS_PATH,failedRedirectUrl:J.LOGIN_FAILED_PATH,logoutUrl:J.LOGOUT_PATH,agcTeamListUrl:J.AGC_TEAM_LIST_URL,appId:Ee.APP_ID,timeout:Ci.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{Command as KE}from"commander";import{green as Fl,red as Jm,yellow as jl}from"colorette";import ne from"fs";import*as V from"path";import jt from"json5";import*as ol from"fs";import*as Pe from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&process.stderr.write(`[DEBUG] ${n}
3
3
  `)}var x=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
4
- `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let h=n.extractTimestampFromLogLine(d,i);h&&(l=n.isWithinBounds(h,o,s)),l&&c.push(d)}return c.join(`
5
- `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,h);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-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 i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Pe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Pe.resolve(Pe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Pe.normalize(e),i=Pe.relative(r,t);if(i.split(Pe.sep)[0]===".."||Pe.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Pe.isAbsolute(e)}static isPathContained(e,t){let r=Pe.resolve(t,e),i=Pe.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=Zc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=Pe.resolve(i,e),s;try{s=Zc.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import tm from"crypto";import Z from"fs";import ds from"os";import Ve from"path";import QS from"https";var Tp={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var es=class n{static ENDPOINT=Tp.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,i){let o=new URL(e);return new Promise((s,a)=>{let c=QS.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",h=>d.push(h)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var Rp={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()},Qc=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(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??Rp.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=r[o]??t(o);i[a]=this.transform(s)}return i}},kp=new Qc({namingStrategy:Rp.snakeCase,fieldNames:{}});import Ci from"crypto";import ts from"fs";import eb from"path";var ns="aes-256-gcm",tb=12,nb="deveco-cli-trace-file",rb="trace-file-secret",Np=32;function xp(n){try{let e=ts.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Np?e:null}catch{return null}}function Lp(n){let e=eb.join(n,rb),t=xp(e);if(t)return el(t);let r=Ci.randomBytes(Np).toString("base64");try{ts.mkdirSync(n,{recursive:!0});try{ts.writeFileSync(e,r,{flag:"wx"})}catch{let i=xp(e);if(i)return el(i);ts.writeFileSync(e,r)}}catch{}return el(r)}function el(n){return Ci.createHash("sha256").update(nb).update(n).digest()}function Op(n,e){let t=Ci.randomBytes(tb),r=Ci.createCipheriv(ns,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:ns,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function Mp(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!ib(t))return n;try{let r=Ci.createDecipheriv(ns,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 ib(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===ns&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as $ from"fs";import*as as from"path";import X from"fs";import*as yr from"os";import*as j from"path";import ob from"json5";import*as _p from"os";function b(){return tl().toLowerCase().includes("openharmony")}function tl(){return _p.platform()}import*as Fp from"fs";import*as xe from"path";function nl(n,e){let t=xe.relative(e,n);return t===""||!xe.isAbsolute(t)&&!t.startsWith(`..${xe.sep}`)&&t!==".."}function Xe(n){let e=xe.resolve(n),t=[],r=e;for(;;)try{let i=Fp.realpathSync(r);return t.length===0?i:xe.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=xe.dirname(r);if(o===r)return e;t.push(xe.basename(r)),r=o}}function Un(n,e){let t=Xe(e),r=Xe(n);return nl(r,t)?r:null}var jp=3;function rs(n){if(!X.existsSync(n)||!X.statSync(n).isDirectory())return!1;let e=X.existsSync(j.join(n,"build-profile.json5")),t=X.existsSync(j.join(n,"hvigorfile.js"))||X.existsSync(j.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=X.readFileSync(j.join(n,"build-profile.json5"),"utf-8");return ob.parse(r).app!==void 0}catch{return!1}}function rl(n,e,t){if(e>=t)return null;let r=sb(n),i=ab(r);if(i)return i;for(let o of r){let s=rl(o,e+1,t);if(s)return s}return null}function sb(n){try{let e=X.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(j.join(n,r.name));return t}catch{return[]}}function ab(n){for(let e of n)if(rs(e))return e;return null}function Ot(n){if(!n||n.trim()==="")return null;let e=j.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}if(!X.existsSync(t))return null;if(rs(t))return t;let r=t;for(let i=1;i<=3;i++){let o=j.dirname(r);if(o===r)break;if(rs(o))return o;r=o}if(X.statSync(t).isDirectory()){let i=rl(t,0,jp);if(i)return i}return null}function is(n){if(!n||n.trim()==="")return null;let e=j.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}return!X.existsSync(t)||!X.statSync(t).isDirectory()?null:rs(t)?t:rl(t,0,jp)}var il=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function wr(n){return j.join(n,...il)}function $p(n){return new Promise(e=>setTimeout(e,n))}var cb=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Bn(n){let e=j.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&cb.has(e)}function os(n){return j.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function fe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function lb(n){return fe(n)}function Wn(n){let e=lb(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Ii(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??j.join(yr.homedir(),"AppData","Local");return j.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?j.join(yr.homedir(),"Library","Logs","devecocli-mcp-server"):j.join(yr.homedir(),".local","share","devecocli-mcp-server","logs")}function db(){return j.join(yr.tmpdir(),"devecocli-mcp-server")}function ol(){return[Ii(),db()]}function sl(n,e=ol()){for(let t of e)try{return n(t)}catch{}return null}function Hp(n,e=ol()){return sl(t=>{let r=j.join(t,"ArkTSCheck"),i=j.join(r,"mapping-config.properties"),o=ub(n,i),s=`${Date.now()}${process.hrtime.bigint()%1000000n}`,a=j.join(r,"lsp-log",String(o),s),c=j.join(r,"lsp-index",String(o));return X.mkdirSync(a,{recursive:!0}),X.mkdirSync(c,{recursive:!0}),{logPath:fe(a),indexPath:fe(c)}},e)??{logPath:null,indexPath:null}}function ub(n,e){let t=pb(e),r=mb(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=fb(t,n,s);return hb(e,a),i}function pb(n){let e;try{e=X.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function mb(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function fb(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function hb(n,e){try{X.mkdirSync(j.dirname(n),{recursive:!0})}catch{}try{X.writeFileSync(n,e.join(`
4
+ `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=n.extractTimestampFromLogLine(d,i);g&&(l=n.isWithinBounds(g,o,s)),l&&c.push(d)}return c.join(`
5
+ `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-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 i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Pe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Pe.resolve(Pe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Pe.normalize(e),i=Pe.relative(r,t);if(i.split(Pe.sep)[0]===".."||Pe.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Pe.isAbsolute(e)}static isPathContained(e,t){let r=Pe.resolve(t,e),i=Pe.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=ol.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=Pe.resolve(i,e),s;try{s=ol.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import wm from"crypto";import Z from"fs";import fs from"os";import We from"path";import wb from"https";var Gp={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var is=class n{static ENDPOINT=Gp.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,i){let o=new URL(e);return new Promise((s,a)=>{let c=wb.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",g=>d.push(g)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var zp={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()},sl=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(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??zp.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=r[o]??t(o);i[a]=this.transform(s)}return i}},qp=new sl({namingStrategy:zp.snakeCase,fieldNames:{}});import Ai from"crypto";import os from"fs";import vb from"path";var ss="aes-256-gcm",Sb=12,bb="deveco-cli-trace-file",Eb="trace-file-secret",Jp=32;function Yp(n){try{let e=os.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Jp?e:null}catch{return null}}function Kp(n){let e=vb.join(n,Eb),t=Yp(e);if(t)return al(t);let r=Ai.randomBytes(Jp).toString("base64");try{os.mkdirSync(n,{recursive:!0});try{os.writeFileSync(e,r,{flag:"wx"})}catch{let i=Yp(e);if(i)return al(i);os.writeFileSync(e,r)}}catch{}return al(r)}function al(n){return Ai.createHash("sha256").update(bb).update(n).digest()}function Xp(n,e){let t=Ai.randomBytes(Sb),r=Ai.createCipheriv(ss,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:ss,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function Zp(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!Pb(t))return n;try{let r=Ai.createDecipheriv(ss,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 Pb(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===ss&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as $ from"fs";import*as us from"path";import X from"fs";import*as Er from"os";import*as j from"path";import Cb from"json5";import*as Qp from"os";function b(){return cl().toLowerCase().includes("openharmony")}function cl(){return Qp.platform()}import*as em from"fs";import*as ke from"path";function ll(n,e){let t=ke.relative(e,n);return t===""||!ke.isAbsolute(t)&&!t.startsWith(`..${ke.sep}`)&&t!==".."}function Ke(n){let e=ke.resolve(n),t=[],r=e;for(;;)try{let i=em.realpathSync(r);return t.length===0?i:ke.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=ke.dirname(r);if(o===r)return e;t.push(ke.basename(r)),r=o}}function zn(n,e){let t=Ke(e),r=Ke(n);return ll(r,t)?r:null}var tm=3;function as(n){if(!X.existsSync(n)||!X.statSync(n).isDirectory())return!1;let e=X.existsSync(j.join(n,"build-profile.json5")),t=X.existsSync(j.join(n,"hvigorfile.js"))||X.existsSync(j.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=X.readFileSync(j.join(n,"build-profile.json5"),"utf-8");return Cb.parse(r).app!==void 0}catch{return!1}}function dl(n,e,t){if(e>=t)return null;let r=Ib(n),i=Db(r);if(i)return i;for(let o of r){let s=dl(o,e+1,t);if(s)return s}return null}function Ib(n){try{let e=X.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(j.join(n,r.name));return t}catch{return[]}}function Db(n){for(let e of n)if(as(e))return e;return null}function Ft(n){if(!n||n.trim()==="")return null;let e=j.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}if(!X.existsSync(t))return null;if(as(t))return t;let r=t;for(let i=1;i<=3;i++){let o=j.dirname(r);if(o===r)break;if(as(o))return o;r=o}if(X.statSync(t).isDirectory()){let i=dl(t,0,tm);if(i)return i}return null}function cs(n){if(!n||n.trim()==="")return null;let e=j.resolve(n),t;try{t=X.realpathSync(e)}catch{t=e}return!X.existsSync(t)||!X.statSync(t).isDirectory()?null:as(t)?t:dl(t,0,tm)}var ul=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function Pr(n){return j.join(n,...ul)}function nm(n){return new Promise(e=>setTimeout(e,n))}var Ab=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function qn(n){let e=j.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Ab.has(e)}function ls(n){return j.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function fe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Tb(n){return fe(n)}function Yn(n){let e=Tb(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Ti(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??j.join(Er.homedir(),"AppData","Local");return j.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?j.join(Er.homedir(),"Library","Logs","devecocli-mcp-server"):j.join(Er.homedir(),".local","share","devecocli-mcp-server","logs")}function Rb(){return j.join(Er.tmpdir(),"devecocli-mcp-server")}function pl(){return[Ti(),Rb()]}function ml(n,e=pl()){for(let t of e)try{return n(t)}catch{}return null}function rm(n,e=pl()){return ml(t=>{let r=j.join(t,"ArkTSCheck"),i=j.join(r,"mapping-config.properties"),o=kb(n,i),s=`${Date.now()}${process.hrtime.bigint()%1000000n}`,a=j.join(r,"lsp-log",String(o),s),c=j.join(r,"lsp-index",String(o));return X.mkdirSync(a,{recursive:!0}),X.mkdirSync(c,{recursive:!0}),{logPath:fe(a),indexPath:fe(c)}},e)??{logPath:null,indexPath:null}}function kb(n,e){let t=xb(e),r=Nb(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=Lb(t,n,s);return Ob(e,a),i}function xb(n){let e;try{e=X.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Nb(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Lb(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function Ob(n,e){try{X.mkdirSync(j.dirname(n),{recursive:!0})}catch{}try{X.writeFileSync(n,e.join(`
6
6
  `)+`
7
- `,"utf8")}catch{}}var gb=/^\d+$/;function al(n,e,t="[Cleanup]",r=ol()){try{let i=j.dirname(n);if(!X.existsSync(i))return;let o=Xe(i);if(!r.some(a=>Un(o,a)!==null)){console.error(`${t} Skip cleanup: '${n}' resolves outside managed storage roots`);return}let s=Date.now();for(let a of X.readdirSync(o,{withFileTypes:!0})){if(!a.isDirectory()||!gb.test(a.name))continue;let c=j.join(o,a.name);r.some(l=>Un(c,l)!==null)&&yb(c,s,e,t)}}catch{}}function yb(n,e,t,r){try{let{mtimeMs:i}=X.statSync(n);if(e-i<=t)return;X.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}var Up="mcp-server.log",wb="mcp-server",vb={maxSize:10*1024*1024,maxFiles:4},cl=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...vb,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Ii(),this.currentLogFile=as.join(this.logDir,Up),$.existsSync(this.logDir)||$.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return as.join(this.logDir,`${wb}-${e}.log.${t}`)}fileExists(e){try{return $.accessSync(e,$.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=$.readdirSync(this.logDir),t=[];for(let i of e)if(i===Up||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=as.join(this.logDir,i),s=$.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{$.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&$.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&$.renameSync(o,s)}let r=this.getRotatedFileName(e,1);$.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=$.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=$.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{$.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
8
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);$.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{$.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Ze=null;function Vn(n=!1){Ze&&Ze.dispose(),Ze=new cl(n)}function Bp(){Ze&&(Ze.dispose(),Ze=null)}function Wp(){Ze&&Ze.flush()}function Vp(){return Ze?.getLogFilePath()??null}function Gp(){return Ze?.getLogDirectory()??null}function ss(){return Ze||Vn(!1),Ze}var g={debug:(n,...e)=>ss().debug(n,...e),info:(n,...e)=>ss().info(n,...e),warn:(n,...e)=>ss().warn(n,...e),error:(n,...e)=>ss().error(n,...e)};import Di from"fs";import ll from"path";var Ai=300*1e3,Ti=3600*1e3,dl=10080*60*1e3,vr=8*1024*1024,ul=3600*1e3,zp=".pending",Sb=/\.reclaim-\d+-\d+$/;function Qe(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var bb="upload-state.json";function Yp(n){return ll.join(n,bb)}function Eb(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function cs(n){try{let e=Di.readFileSync(Yp(n),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return Eb()}}function pl(n,e){try{Di.writeFileSync(Yp(n),JSON.stringify(e),"utf8")}catch{}}function Jp(n){let e=cs(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),pl(n,e))}function Kp(n){let e=cs(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,pl(n,e)}function Xp(n){let e=cs(n);e.lastRetryAt=Date.now(),pl(n,e)}function ml(n){let e=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function fl(n){if(!n.startsWith("telemetry-"))return null;let e=Sb.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(zp))return null;let r=t.slice(0,-zp.length);return r.endsWith(".txt")?r:null}function hl(n){return fl(n)!==null}function Pb(n,e=Date.now()){try{return e-Di.statSync(n).mtimeMs>=ul}catch{return!1}}function qp(n,e=Date.now()){let t;try{t=Di.readdirSync(n)}catch{return!1}return t.some(r=>hl(r)&&Pb(ll.join(n,r),e))}function Cb(n,e=Date.now()){if(qp(n,e))return!0;let t=ll.join(n,"failed");if(qp(t,e))return!0;let r;try{r=Di.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=ml(i);if(o!==null&&e-o<=dl)return!0}return!1}function Zp(n,e=Date.now()){let t=cs(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Ai||Cb(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Ti))}import Ib from"crypto";import ls from"fs";import Db from"path";var Ab="install-id";function Tb(n){return Db.join(n,Ab)}function Qp(n){try{let e=ls.readFileSync(n,"utf8").trim();return Rb(e)?e:null}catch{return null}}function Rb(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function em(n){let e=Tb(n),t=Qp(e);if(t)return t;let r=Ib.randomUUID();try{ls.mkdirSync(n,{recursive:!0});try{ls.writeFileSync(e,r,{flag:"wx"})}catch{let i=Qp(e);if(i)return i;ls.writeFileSync(e,r)}}catch{}return r}var Ri=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new es;storageDir="";failedDir="";installId="";disabled=Qe();traceFileKey=Buffer.alloc(0);sessionId=tm.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=Ve.join(e,"failed"),this.cliVersion="1.3.12-Test.1",this.nodeVersion=process.version,this.installId=em(e).replace(/-/g,""),this.traceFileKey=Lp(e),Z.mkdirSync(e,{recursive:!0}),Z.mkdirSync(this.failedDir,{recursive:!0}),g.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,g.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,g.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,g.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let r=t,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,r,i){let o=this.buildTraceEvent(e,t,r,i);try{let s=Op(JSON.stringify(o),this.traceFileKey);await Z.promises.appendFile(this.currentFile(),s+`
9
- `,"utf8"),Jp(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=kp.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:tm.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:r,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=ds.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=ds.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 ds.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(ds.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return Ve.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){g.debug("[telemetry] scheduler not started (telemetry disabled)");return}g.debug(`[telemetry] scheduler started (flush every ${Ai/1e3}s, retry failed every ${Ti/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Ai)},Ai),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Ti)},Ti)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),g.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return Kp(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let e=Date.now(),t;try{t=await Z.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>Ve.join(this.failedDir,o)),i=!0;for(let o of r){let s=Ve.basename(o),a=ml(s);if(a!==null){if(e-a>dl){try{await Z.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||g.warn("[telemetry] retry failed"),Xp(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await Z.promises.readdir(t)}catch{continue}for(let i of r)hl(i)&&await this.reclaimOrphan(Ve.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await Z.promises.stat(e);if(t-l.mtimeMs<ul)return;r=l.size}catch{return}let i=Ve.dirname(e),o=fl(Ve.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=Ve.join(i,o),c=vr-await this.fileSize(a);if(r>c){try{await Z.promises.unlink(s)}catch{}g.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){g.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}g.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=Ve.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await Z.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await Z.promises.appendFile(t,await Z.promises.readFile(e))}catch(r){return g.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await Z.promises.unlink(e)}catch(r){g.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(e){try{return(await Z.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await Z.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await Z.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>Ve.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>vr){g.warn(`[telemetry] ${Ve.basename(e)} is ${t} bytes (> ${vr}), dropped without uploading`);try{await Z.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await Z.promises.rename(e,r)}catch{return!1}await this.touch(r);let i;try{i=await Z.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
10
- `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await Z.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(e,t){let r=[],i=16,o=t;for(;o<e.length&&r.length<n.MAX_BATCH;){let s=Mp(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+a>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=a,o++}return{batch:r,next:o}}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(t,r);r=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){g.warn("[telemetry] upload failed");let d=t.slice(i).join(`
7
+ `,"utf8")}catch{}}var Mb=/^\d+$/;function fl(n,e,t="[Cleanup]",r=pl()){try{let i=j.dirname(n);if(!X.existsSync(i))return;let o=Ke(i);if(!r.some(a=>zn(o,a)!==null)){console.error(`${t} Skip cleanup: '${n}' resolves outside managed storage roots`);return}let s=Date.now();for(let a of X.readdirSync(o,{withFileTypes:!0})){if(!a.isDirectory()||!Mb.test(a.name))continue;let c=j.join(o,a.name);r.some(l=>zn(c,l)!==null)&&_b(c,s,e,t)}}catch{}}function _b(n,e,t,r){try{let{mtimeMs:i}=X.statSync(n);if(e-i<=t)return;X.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}var im="mcp-server.log",Fb="mcp-server",jb={maxSize:10*1024*1024,maxFiles:4},gl=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...jb,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Ti(),this.currentLogFile=us.join(this.logDir,im),$.existsSync(this.logDir)||$.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return us.join(this.logDir,`${Fb}-${e}.log.${t}`)}fileExists(e){try{return $.accessSync(e,$.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=$.readdirSync(this.logDir),t=[];for(let i of e)if(i===im||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=us.join(this.logDir,i),s=$.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{$.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&$.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&$.renameSync(o,s)}let r=this.getRotatedFileName(e,1);$.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=$.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=$.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{$.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
8
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);$.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{$.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Xe=null;function Jn(n=!1){Xe&&Xe.dispose(),Xe=new gl(n)}function om(){Xe&&(Xe.dispose(),Xe=null)}function sm(){Xe&&Xe.flush()}function am(){return Xe?.getLogFilePath()??null}function cm(){return Xe?.getLogDirectory()??null}function ds(){return Xe||Jn(!1),Xe}var h={debug:(n,...e)=>ds().debug(n,...e),info:(n,...e)=>ds().info(n,...e),warn:(n,...e)=>ds().warn(n,...e),error:(n,...e)=>ds().error(n,...e)};import Ri from"fs";import hl from"path";var ki=300*1e3,xi=3600*1e3,yl=10080*60*1e3,Cr=8*1024*1024,wl=3600*1e3,lm=".pending",$b=/\.reclaim-\d+-\d+$/;function Ze(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var Hb="upload-state.json";function um(n){return hl.join(n,Hb)}function Ub(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ps(n){try{let e=Ri.readFileSync(um(n),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return Ub()}}function vl(n,e){try{Ri.writeFileSync(um(n),JSON.stringify(e),"utf8")}catch{}}function pm(n){let e=ps(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),vl(n,e))}function mm(n){let e=ps(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,vl(n,e)}function fm(n){let e=ps(n);e.lastRetryAt=Date.now(),vl(n,e)}function Sl(n){let e=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function bl(n){if(!n.startsWith("telemetry-"))return null;let e=$b.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(lm))return null;let r=t.slice(0,-lm.length);return r.endsWith(".txt")?r:null}function El(n){return bl(n)!==null}function Bb(n,e=Date.now()){try{return e-Ri.statSync(n).mtimeMs>=wl}catch{return!1}}function dm(n,e=Date.now()){let t;try{t=Ri.readdirSync(n)}catch{return!1}return t.some(r=>El(r)&&Bb(hl.join(n,r),e))}function Wb(n,e=Date.now()){if(dm(n,e))return!0;let t=hl.join(n,"failed");if(dm(t,e))return!0;let r;try{r=Ri.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=Sl(i);if(o!==null&&e-o<=yl)return!0}return!1}function gm(n,e=Date.now()){let t=ps(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=ki||Wb(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=xi))}import Vb from"crypto";import ms from"fs";import Gb from"path";var zb="install-id";function qb(n){return Gb.join(n,zb)}function hm(n){try{let e=ms.readFileSync(n,"utf8").trim();return Yb(e)?e:null}catch{return null}}function Yb(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function ym(n){let e=qb(n),t=hm(e);if(t)return t;let r=Vb.randomUUID();try{ms.mkdirSync(n,{recursive:!0});try{ms.writeFileSync(e,r,{flag:"wx"})}catch{let i=hm(e);if(i)return i;ms.writeFileSync(e,r)}}catch{}return r}var Ni=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new is;storageDir="";failedDir="";installId="";disabled=Ze();traceFileKey=Buffer.alloc(0);sessionId=wm.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){h.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=We.join(e,"failed"),this.cliVersion="1.3.13-23.1",this.nodeVersion=process.version,this.installId=ym(e).replace(/-/g,""),this.traceFileKey=Kp(e),Z.mkdirSync(e,{recursive:!0}),Z.mkdirSync(this.failedDir,{recursive:!0}),h.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,h.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,h.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,h.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let r=t,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,r,i){let o=this.buildTraceEvent(e,t,r,i);try{let s=Xp(JSON.stringify(o),this.traceFileKey);await Z.promises.appendFile(this.currentFile(),s+`
9
+ `,"utf8"),pm(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=qp.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:wm.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:r,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=fs.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=fs.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 fs.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(fs.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return We.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){h.debug("[telemetry] scheduler not started (telemetry disabled)");return}h.debug(`[telemetry] scheduler started (flush every ${ki/1e3}s, retry failed every ${xi/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},ki)},ki),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},xi)},xi)}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.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return mm(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let e=Date.now(),t;try{t=await Z.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>We.join(this.failedDir,o)),i=!0;for(let o of r){let s=We.basename(o),a=Sl(s);if(a!==null){if(e-a>yl){try{await Z.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||h.warn("[telemetry] retry failed"),fm(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await Z.promises.readdir(t)}catch{continue}for(let i of r)El(i)&&await this.reclaimOrphan(We.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await Z.promises.stat(e);if(t-l.mtimeMs<wl)return;r=l.size}catch{return}let i=We.dirname(e),o=bl(We.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=We.join(i,o),c=Cr-await this.fileSize(a);if(r>c){try{await Z.promises.unlink(s)}catch{}h.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){h.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}h.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=We.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await Z.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await Z.promises.appendFile(t,await Z.promises.readFile(e))}catch(r){return h.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await Z.promises.unlink(e)}catch(r){h.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(e){try{return(await Z.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await Z.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await Z.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>We.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>Cr){h.warn(`[telemetry] ${We.basename(e)} is ${t} bytes (> ${Cr}), dropped without uploading`);try{await Z.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await Z.promises.rename(e,r)}catch{return!1}await this.touch(r);let i;try{i=await Z.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
10
+ `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await Z.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(e,t){let r=[],i=16,o=t;for(;o<e.length&&r.length<n.MAX_BATCH;){let s=Zp(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+a>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=a,o++}return{batch:r,next:o}}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(t,r);r=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){h.warn("[telemetry] upload failed");let d=t.slice(i).join(`
11
11
  `)+`
12
- `;return await this.moveToFailed(e,d),!1}}try{await Z.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let r of e)try{let i=JSON.parse(r);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let r=Ve.basename(e,".pending"),i=Ve.join(this.failedDir,r),o=t.split(`
13
- `).filter(Boolean),s=vr-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&g.warn(`[telemetry] failed file capped at ${vr} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await Z.promises.appendFile(i,a.join(`
12
+ `;return await this.moveToFailed(e,d),!1}}try{await Z.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let r of e)try{let i=JSON.parse(r);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let r=We.basename(e,".pending"),i=We.join(this.failedDir,r),o=t.split(`
13
+ `).filter(Boolean),s=Cr-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&h.warn(`[telemetry] failed file capped at ${Cr} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await Z.promises.appendFile(i,a.join(`
14
14
  `)+`
15
- `,"utf8")}catch{return}try{await Z.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,r.push(e[o])}return r.reverse(),r}};var I=new Ri;import{spawn as kb}from"child_process";import{existsSync as xb}from"fs";import{dirname as Nb,join as Lb}from"path";import{fileURLToPath as Ob}from"url";function Mb(){let n=Nb(Ob(import.meta.url)),e=Lb(n,"internal","telemetry-upload-background.js");return xb(e)?e:null}function gl(n){if(Qe()||!Zp(n))return;let e=Mb();if(!e){g.warn("[telemetry] background upload script not found, skipping spawn");return}try{kb(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){g.warn("[telemetry] failed to spawn background upload:",t)}}var T=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function W(n){if(n instanceof T)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var D={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var K=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=V.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=V.join(e,"build-profile.json5");if(!ne.existsSync(t))return null;try{let r=ne.readFileSync(t,"utf-8"),i=Mt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new T(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"src","main","module.json5");if(!ne.existsSync(i))return"entry";try{let o=ne.readFileSync(i,"utf-8");return Mt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=V.normalize(e);for(let r of this.profile.modules){let i=V.normalize(V.join(this.rootDir,r.srcPath)),o=i+V.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new T(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"build-profile.json5");if(!ne.existsSync(i))throw new T(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");let o=ne.readFileSync(i,"utf-8");return Mt.parse(o)}getBundleName(){let e=V.join(this.rootDir,"AppScope","app.json5");if(ne.existsSync(e))try{let t=ne.readFileSync(e,"utf-8"),r=Mt.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=V.join(this.rootDir,"AppScope","app.json5");if(!ne.existsSync(e))return!1;try{let t=ne.readFileSync(e,"utf-8");return Mt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=x.resolvePathWithinRoot(this.rootDir,r.srcPath),o=V.join(i,"src","main","module.json5");if(!ne.existsSync(o))return"EntryAbility";try{let s=ne.readFileSync(o,"utf-8"),c=Mt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new T(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new T(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"oh-package.json5");if(!ne.existsSync(i))return[];let o=[];try{let s=ne.readFileSync(i,"utf-8"),c=Mt.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=V.join(t.srcPath,d),v=x.resolvePathWithinRoot(this.rootDir,w),k=this.profile.modules.find(ce=>V.resolve(this.rootDir,ce.srcPath)===v);k&&o.push(k.name)}}catch{}return o}getModuleName(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)return e;let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"src","main","module.json5");if(!ne.existsSync(i))return e;try{let o=ne.readFileSync(i,"utf-8");return Mt.parse(o)?.module?.name||e}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),e}}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new T(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!ne.existsSync(a))throw new T(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let v=this.getSignedHapName(c,o.srcPath,i,t);v&&(d=v)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new T(`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(o.srcPath,i,["outputs",t,d]);if(!ne.existsSync(w))throw new T(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=V.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!ne.existsSync(l))throw new T(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return ne.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=x.resolvePathWithinRoot(this.rootDir,e),o=V.resolve(i,"build",t,...r);return x.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r=ne.readFileSync(e,"utf-8"),i=Mt.parse(r),o,s=!1,a=Array.isArray(i)?i:[i];for(let l of a)o||(o=l[t]),s||(s=l.isSigned===!0);if(!o)throw new T(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(o);let c=this.collectRemoteHsps(a);return{packageName:o,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=V.basename(e);if(t!==e)throw new T(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new T(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import ge from"fs";import*as ze from"os";import*as S from"path";import sm from"fs";import*as ms from"os";import*as ps from"path";import jb from"regedit";import{execFileSync as _b}from"child_process";import nm from"fs";import*as rm from"os";import*as yl from"path";function us(n,e){let t=yl.join(n,"Contents","Info.plist");if(!nm.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=_b(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function Fb(n){let e=us(n,"CFBundleShortVersionString");if(!e)return us(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[us(n,"CFBundleVersion"),us(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Sr(n){if(rm.platform()==="darwin")return Fb(n);let e=yl.join(n,"product-info.json");try{let t=JSON.parse(nm.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function ki(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function $b(n){return n.filter(e=>{try{return sm.statSync(e).isDirectory()}catch{return!1}})}function Hb(){let n=[];for(let e of[ps.join(ms.homedir(),"Applications"),"/Applications"])try{n.push(...sm.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>ps.join(e,t)))}catch{}return n}function im(n){return new Promise((e,t)=>jb.list(n,(r,i)=>r?t(r):e(i)))}async function om(n,e,t){let i=((await im([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await im(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function Ub(){let n=[ps.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 om(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 om(e,()=>!0,""))}catch{}return n}async function am(){let n=ms.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"?Hb():await Ub(),t=$b(e).flatMap(r=>{let i=Sr(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,i)=>ki(i.version,r.version)>0?i:r)}function fs(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function hs(n){let e=fs(n);if(!e)throw new Error("Path must not be empty.");return Xe(e)}import{homedir as sn}from"os";import _t from"path";import{xdgConfig as Bb}from"xdg-basedir";var he={"trae-cn":_t.join(sn(),".trae-cn"),opencode:_t.join(Bb,"opencode"),cursor:_t.join(sn(),".cursor"),codebuddy:_t.join(sn(),".codebuddy"),qoder:_t.join(sn(),".qoder"),"claude-code":_t.join(sn(),".claude"),codex:_t.join(sn(),".codex"),bitfun:_t.join(sn(),".bitfun"),opendesk:_t.join(sn(),".opendesk")};import an from"path";var wl="https://matrix.openharmony.cn",dt={TAGS_API_URL:`${wl}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${wl}/api/registry/skill/skills`,SKILL_API_BASE:`${wl}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},cm={"trae-cn":{path:an.join(he["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:an.join(he.opencode,"skills"),displayName:"opencode"},cursor:{path:an.join(he.cursor,"skills"),displayName:"cursor"},codebuddy:{path:an.join(he.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:an.join(he.qoder,"skills"),displayName:"qoder"},"claude-code":{path:an.join(he["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:an.join(he.codex,"skills"),displayName:"codex"}},lm={opencode:{path:an.join(he.opencode,"skills"),displayName:"opencode"}};function Ft(){return b()?lm:cm}import{homedir as xi}from"os";import Ge from"path";var It="deveco-mcp";var cn={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Ge.join(he.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Ge.join(process.platform==="win32"?Ge.join(process.env.APPDATA??Ge.join(xi(),"AppData","Roaming"),"Trae CN","User"):Ge.join(xi(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Ge.join(he.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Ge.join(he.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Ge.join(process.platform==="win32"?Ge.join(process.env.APPDATA??Ge.join(xi(),"AppData","Roaming"),"Qoder","SharedClientCache"):Ge.join(xi(),"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:Ge.join(xi(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Ge.join(he.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function um(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function dm(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function pm(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function gs(n,e){return n.format==="opencode"?um(e):n.format==="claude-code"||n.format==="codex"?dm(e):pm(e)}var ut={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var vl="https://developer.huawei.com/consumer/cn/download/";var Wb=/^#\s*Version:\s*(\S+)/,Vb="26.0.0.810",Gb=["sdk","default","openharmony","native","llvm","bin","clangd"];function zb(n){try{let e=JSON.parse(ge.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function qb(n){let e=S.join(n,"default","openharmony");return[S.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>S.join(e,t,"oh-uni-package.json"))]}var A=class n{constructor(e,t,r,i,o,s,a,c,l,d,h="",w=""){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d;this._clangdPath=h;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;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 javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this._clangdPath&&ge.existsSync(this._clangdPath)?this._clangdPath:""}get lspServerPath(){return this._lspServerPath&&ge.existsSync(this._lspServerPath)?this._lspServerPath:""}assertJava(){if(!b()&&(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 ki(e,t)}static async checkVersion(){if(b())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(b())return n.fromOpenHarmony();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,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static OPENHARMONY_STUDIO_ROOT="/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0";static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH?.trim();if(!e&&!n.isDirectory(n.OPENHARMONY_STUDIO_ROOT))throw new Error("No toolchain found. Set COMMAND_LINE_TOOL_PATH.");return e?(m(`[ToolProvider] Using COMMAND_LINE_TOOL_PATH \u2192 ${e}`),n.buildOpenHarmonyProvider("clt",e)):(m("[ToolProvider] COMMAND_LINE_TOOL_PATH not set, using fallback DevEco Studio toolchain"),n.buildOpenHarmonyProvider("studio",n.OPENHARMONY_STUDIO_ROOT))}static buildOpenHarmonyToolPaths(e){let t=S.join(e,"sdk");return{nodePath:S.join(e,"node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:"",clangdPath:S.join(e,"clangd","clangd"),lspServerPath:S.join(e,"ace-server","out","index.js")}}static buildOpenHarmonyProvider(e,t){let r=e==="clt"?"COMMAND_LINE_TOOL_PATH is invalid":"DevEco Studio toolchain is invalid";if(!n.isDirectory(t))throw new Error(`${r}: ${t} is not a valid directory.`);let i=n.buildOpenHarmonyToolPaths(t),o=Object.entries({node:i.nodePath,ohpm:i.ohpmJsPath,hvigor:i.hvigorJsPath,hdc:i.hdcPath}).filter(([,s])=>!s||!ge.existsSync(s)).map(([s])=>s);if(o.length>0)throw new Error(`${r}: ${t} \u2014 missing required: ${o.join(", ")}.`);return n.assertBuiltPathsInsideRoot(t,i,!1),new n(e,t,e==="studio"?t:void 0,i.nodePath,i.ohpmJsPath,i.hvigorJsPath,"",i.sdkPath,i.hdcPath,i.emulatorPath,i.clangdPath,i.lspServerPath)}static devecoContentRootForClangd(e){return ze.platform()==="darwin"&&e.endsWith(".app")?S.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let i of r){let o=S.join(i,...Gb);t.add(ze.platform()==="win32"?o+".exe":o)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(ge.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=ze.platform(),r;if(t==="win32")r=S.join(e,"plugins","openharmony");else if(t==="darwin")r=S.join(e,"Contents","plugins","openharmony");else return"";let i=S.join(r,"ace-server","out","index.js");return ge.existsSync(i)?i:""}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):Sr(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){b()||(this.assertStudio(),n.assertMinimumVersion(Sr(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot))}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${o}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${o}`);if(ki(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
16
- ${vl}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),i=r.find(n.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new Error(`${a}
15
+ `,"utf8")}catch{return}try{await Z.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,r.push(e[o])}return r.reverse(),r}};var I=new Ni;import{spawn as Jb}from"child_process";import{existsSync as Kb}from"fs";import{dirname as Xb,join as Zb}from"path";import{fileURLToPath as Qb}from"url";function eE(){let n=Xb(Qb(import.meta.url)),e=Zb(n,"internal","telemetry-upload-background.js");return Kb(e)?e:null}function Pl(n){if(Ze()||!gm(n))return;let e=eE();if(!e){h.warn("[telemetry] background upload script not found, skipping spawn");return}try{Jb(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 T=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function W(n){if(n instanceof T)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var D={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var K=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=V.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=V.join(e,"build-profile.json5");if(!ne.existsSync(t))return null;try{let r=ne.readFileSync(t,"utf-8"),i=jt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new T(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"src","main","module.json5");if(!ne.existsSync(i))return"entry";try{let o=ne.readFileSync(i,"utf-8");return jt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=V.normalize(e);for(let r of this.profile.modules){let i=V.normalize(V.join(this.rootDir,r.srcPath)),o=i+V.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new T(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"build-profile.json5");if(!ne.existsSync(i))throw new T(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");let o=ne.readFileSync(i,"utf-8");return jt.parse(o)}getBundleName(){let e=V.join(this.rootDir,"AppScope","app.json5");if(ne.existsSync(e))try{let t=ne.readFileSync(e,"utf-8"),r=jt.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=V.join(this.rootDir,"AppScope","app.json5");if(!ne.existsSync(e))return!1;try{let t=ne.readFileSync(e,"utf-8");return jt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=x.resolvePathWithinRoot(this.rootDir,r.srcPath),o=V.join(i,"src","main","module.json5");if(!ne.existsSync(o))return"EntryAbility";try{let s=ne.readFileSync(o,"utf-8"),c=jt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new T(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new T(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"oh-package.json5");if(!ne.existsSync(i))return[];let o=[];try{let s=ne.readFileSync(i,"utf-8"),c=jt.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=V.join(t.srcPath,d),v=x.resolvePathWithinRoot(this.rootDir,w),k=this.profile.modules.find(ce=>V.resolve(this.rootDir,ce.srcPath)===v);k&&o.push(k.name)}}catch{}return o}getModuleName(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)return e;let r=x.resolvePathWithinRoot(this.rootDir,t.srcPath),i=V.join(r,"src","main","module.json5");if(!ne.existsSync(i))return e;try{let o=ne.readFileSync(i,"utf-8");return jt.parse(o)?.module?.name||e}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),e}}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new T(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!ne.existsSync(a))throw new T(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let v=this.getSignedHapName(c,o.srcPath,i,t);v&&(d=v)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new T(`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(o.srcPath,i,["outputs",t,d]);if(!ne.existsSync(w))throw new T(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=V.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!ne.existsSync(l))throw new T(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return ne.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=x.resolvePathWithinRoot(this.rootDir,e),o=V.resolve(i,"build",t,...r);return x.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r=ne.readFileSync(e,"utf-8"),i=jt.parse(r),o,s=!1,a=Array.isArray(i)?i:[i];for(let l of a)o||(o=l[t]),s||(s=l.isSigned===!0);if(!o)throw new T(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(o);let c=this.collectRemoteHsps(a);return{packageName:o,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=V.basename(e);if(t!==e)throw new T(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new T(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import he from"fs";import*as Ge from"os";import*as S from"path";import Pm from"fs";import*as ys from"os";import*as hs from"path";import rE from"regedit";import{execFileSync as tE}from"child_process";import vm from"fs";import*as Sm from"os";import*as Cl from"path";function gs(n,e){let t=Cl.join(n,"Contents","Info.plist");if(!vm.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=tE(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function nE(n){let e=gs(n,"CFBundleShortVersionString");if(!e)return gs(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[gs(n,"CFBundleVersion"),gs(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Ir(n){if(Sm.platform()==="darwin")return nE(n);let e=Cl.join(n,"product-info.json");try{let t=JSON.parse(vm.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Li(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function iE(n){return n.filter(e=>{try{return Pm.statSync(e).isDirectory()}catch{return!1}})}function oE(){let n=[];for(let e of[hs.join(ys.homedir(),"Applications"),"/Applications"])try{n.push(...Pm.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>hs.join(e,t)))}catch{}return n}function bm(n){return new Promise((e,t)=>rE.list(n,(r,i)=>r?t(r):e(i)))}async function Em(n,e,t){let i=((await bm([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await bm(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function sE(){let n=[hs.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 Em(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 Em(e,()=>!0,""))}catch{}return n}async function Cm(){let n=ys.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"?oE():await sE(),t=iE(e).flatMap(r=>{let i=Ir(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,i)=>Li(i.version,r.version)>0?i:r)}function ws(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function vs(n){let e=ws(n);if(!e)throw new Error("Path must not be empty.");return Ke(e)}import{homedir as dn}from"os";import $t from"path";import{xdgConfig as aE}from"xdg-basedir";var ge={"trae-cn":$t.join(dn(),".trae-cn"),opencode:$t.join(aE,"opencode"),cursor:$t.join(dn(),".cursor"),codebuddy:$t.join(dn(),".codebuddy"),qoder:$t.join(dn(),".qoder"),"claude-code":$t.join(dn(),".claude"),codex:$t.join(dn(),".codex"),bitfun:$t.join(dn(),".bitfun"),opendesk:$t.join(dn(),".opendesk")};import un from"path";var Il="https://matrix.openharmony.cn",ct={TAGS_API_URL:`${Il}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Il}/api/registry/skill/skills`,SKILL_API_BASE:`${Il}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Im={"trae-cn":{path:un.join(ge["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:un.join(ge.opencode,"skills"),displayName:"opencode"},cursor:{path:un.join(ge.cursor,"skills"),displayName:"cursor"},codebuddy:{path:un.join(ge.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:un.join(ge.qoder,"skills"),displayName:"qoder"},"claude-code":{path:un.join(ge["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:un.join(ge.codex,"skills"),displayName:"codex"}},Dm={opencode:{path:un.join(ge.opencode,"skills"),displayName:"opencode"}};function Ht(){return b()?Dm:Im}import{homedir as Oi}from"os";import Ve from"path";var Ct="deveco-mcp";var pn={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Ve.join(ge.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Ve.join(process.platform==="win32"?Ve.join(process.env.APPDATA??Ve.join(Oi(),"AppData","Roaming"),"Trae CN","User"):Ve.join(Oi(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Ve.join(ge.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Ve.join(ge.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Ve.join(process.platform==="win32"?Ve.join(process.env.APPDATA??Ve.join(Oi(),"AppData","Roaming"),"Qoder","SharedClientCache"):Ve.join(Oi(),"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:Ve.join(Oi(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Ve.join(ge.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Tm(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Am(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Rm(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Ss(n,e){return n.format==="opencode"?Tm(e):n.format==="claude-code"||n.format==="codex"?Am(e):Rm(e)}var lt={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Dl="https://developer.huawei.com/consumer/cn/download/";var cE=/^#\s*Version:\s*(\S+)/,lE="26.0.0.810",dE=["sdk","default","openharmony","native","llvm","bin","clangd"];function uE(n){try{let e=JSON.parse(he.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function pE(n){let e=S.join(n,"default","openharmony");return[S.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>S.join(e,t,"oh-uni-package.json"))]}var A=class n{constructor(e,t,r,i,o,s,a,c,l,d,g="",w=""){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d;this._clangdPath=g;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;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 javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this._clangdPath&&he.existsSync(this._clangdPath)?this._clangdPath:""}get lspServerPath(){return this._lspServerPath&&he.existsSync(this._lspServerPath)?this._lspServerPath:""}assertJava(){if(!b()&&(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 Li(e,t)}static async checkVersion(){if(b())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(b())return n.fromOpenHarmony();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,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static OPENHARMONY_STUDIO_ROOT="/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0";static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH?.trim();if(!e&&!n.isDirectory(n.OPENHARMONY_STUDIO_ROOT))throw new Error("No toolchain found. Set COMMAND_LINE_TOOL_PATH.");return e?(m(`[ToolProvider] Using COMMAND_LINE_TOOL_PATH \u2192 ${e}`),n.buildOpenHarmonyProvider("clt",e)):(m("[ToolProvider] COMMAND_LINE_TOOL_PATH not set, using fallback DevEco Studio toolchain"),n.buildOpenHarmonyProvider("studio",n.OPENHARMONY_STUDIO_ROOT))}static buildOpenHarmonyToolPaths(e){let t=S.join(e,"sdk");return{nodePath:S.join(e,"node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:"",clangdPath:S.join(e,"clangd","clangd"),lspServerPath:S.join(e,"ace-server","out","index.js")}}static buildOpenHarmonyProvider(e,t){let r=e==="clt"?"COMMAND_LINE_TOOL_PATH is invalid":"DevEco Studio toolchain is invalid";if(!n.isDirectory(t))throw new Error(`${r}: ${t} is not a valid directory.`);let i=n.buildOpenHarmonyToolPaths(t),o=Object.entries({node:i.nodePath,ohpm:i.ohpmJsPath,hvigor:i.hvigorJsPath,hdc:i.hdcPath}).filter(([,s])=>!s||!he.existsSync(s)).map(([s])=>s);if(o.length>0)throw new Error(`${r}: ${t} \u2014 missing required: ${o.join(", ")}.`);return n.assertBuiltPathsInsideRoot(t,i,!1),new n(e,t,e==="studio"?t:void 0,i.nodePath,i.ohpmJsPath,i.hvigorJsPath,"",i.sdkPath,i.hdcPath,i.emulatorPath,i.clangdPath,i.lspServerPath)}static devecoContentRootForClangd(e){return Ge.platform()==="darwin"&&e.endsWith(".app")?S.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let i of r){let o=S.join(i,...dE);t.add(Ge.platform()==="win32"?o+".exe":o)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(he.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=Ge.platform(),r;if(t==="win32")r=S.join(e,"plugins","openharmony");else if(t==="darwin")r=S.join(e,"Contents","plugins","openharmony");else return"";let i=S.join(r,"ace-server","out","index.js");return he.existsSync(i)?i:""}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):Ir(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){b()||(this.assertStudio(),n.assertMinimumVersion(Ir(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot))}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${o}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${o}`);if(Li(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
16
+ ${Dl}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),i=r.find(n.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new Error(`${a}
17
17
  Searched paths:
18
18
  ${r.join(`
19
- `)}`)}let o=Xe(e),s=Xe(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){if(b())return[S.join(e,"codelinter","index.js")];let r=ze.platform()==="darwin"?["Contents"]:[];return[S.join(e,...r,"plugins","codelinter","run","index.js"),S.join(e,...r,"plugins","codelinter","index.js"),S.join(e,...r,"tools","codelinter","bin","codelinter.js"),S.join(e,...r,"tools","codelinter","codelinter.js")]}return[S.join(e,"codelinter","index.js"),S.join(e,"codelinter","run","index.js"),S.join(e,"tool","codelinter","bin","codelinter.js"),S.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return ge.existsSync(S.join(e,"version.txt"));let r=ze.platform()==="darwin"?S.join(e,"Contents"):e,i=ze.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!ge.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(ge.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=ze.platform()==="win32",i=r?".exe":"";return{nodePath:r?S.join(e,"tool","node","node.exe"):S.join(e,"tool","node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains",`hdc${i}`),emulatorPath:S.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=ze.platform()==="darwin",r=ze.platform()==="win32",i=t?S.join(e,"Contents"):e,o=S.join(i,"tools"),s=S.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(o,"node","node.exe"):S.join(o,"node","bin","node"),ohpmJsPath:S.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(i,"jbr","Contents","Home","bin","java"):S.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(o,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return ge.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return ge.existsSync(e)&&ge.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.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[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await am();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=hs(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&ze.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=Xe(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)a&&n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(Un(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${S.sep}Contents`,r=S.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return ge.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(Wb)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(S.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return ge.realpathSync(o);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(ze.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(ge.existsSync)}getMaxApiLevel(){for(let e of qb(this.sdkPath)){let t=zb(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=ze.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":"",r=S.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=S.join(r,"resources","apiChange"),o=S.join(r,"api-change-scan.js");if(!ge.existsSync(i)||!ge.existsSync(o)){let s=Sr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${Vb}. Upgrade before using 'check compat' at ${vl}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as aE}from"execa";import*as jt from"path";import*as Ss from"fs";import*as Pl from"os";import{execFile as El,spawn as mm}from"child_process";import{existsSync as Yb,readdirSync as Jb,readFileSync as Kb}from"fs";var ws="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Sl,bl="---MEMORY-SAMPLE-DELIMITER---";function hm(){return Sl===void 0&&(Sl=Yb(ws)),Sl}function Ni(n){return new Promise(e=>{let t=process.platform==="win32",r=t?"tasklist":"ps",i=t?["/fi",`PID eq ${n}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(n)];m(`Executing: ${r} ${i.join(" ")}`),El(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?sE(s):oE(s))})})}async function Xb(){return process.platform==="linux"?ys():process.platform==="darwin"?Zb():process.platform==="win32"?Qb():[]}function ys(){let n=[],e;try{e=Jb("/proc")}catch{return n}for(let t of e){if(!/^\d+$/.test(t))continue;let r=Number(t);try{let i=Kb(`/proc/${r}/status`,"utf8"),o=i.match(/VmRSS:\s+(\d+)\s+kB/),s=i.match(/^PPid:\s+(\d+)/m);if(!o||!s)continue;n.push({pid:r,ppid:Number(s[1]),rssBytes:Number(o[1])*1024})}catch{}}return n}function Zb(){return new Promise(n=>{El("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){n([]);return}n(gm(t))})})}function gm(n){let e=[];for(let t of n.trim().split(`
20
- `)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let i=Number(r[0]),o=Number(r[1]),s=Number(r[2]);isNaN(i)||isNaN(o)||isNaN(s)||e.push({pid:i,ppid:o,rssBytes:s*1024})}return e}function Qb(){return new Promise(n=>{if(!hm()){n([]);return}El(ws,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,r)=>{if(t){n([]);return}n(ym(r))})})}function ym(n){let e=[];for(let t of n.trim().split(`
21
- `)){let r=t.trim();if(!r)continue;let i=r.split(",");if(i.length<3)continue;let o=Number(i[0]),s=Number(i[1]),a=Number(i[2]);isNaN(o)||isNaN(s)||isNaN(a)||e.push({pid:o,ppid:s,rssBytes:a})}return e}function wm(n,e){let t=new Map,r=new Map;for(let a of n){t.set(a.pid,a.rssBytes);let c=r.get(a.ppid);c?c.push(a.pid):r.set(a.ppid,[a.pid])}let i=0,o=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(o.has(a))continue;o.add(a),i+=t.get(a)??0;let c=r.get(a);c&&s.push(...c)}return i}async function eE(n){let e=await Xb();return wm(e,n)}function tE(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${bl}'; sleep ${e}; done`;return m(`Executing: sh -c ${t}`),mm("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&hm()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${bl}'; Start-Sleep -Milliseconds ${n} }`;return m(`Executing: ${ws} -NoProfile -Command ${e}`),mm(ws,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function Dt(n){return`${(n/1024/1024).toFixed(2)}MB`}async function fm(n,e){if(!n)return process.memoryUsage().rss;if(e)return eE(n);let t=await Ni(n);return t?Number(t)*1024:0}function vs(n,e=500,t=!1){let r=0,i=!1,o=a=>{if(i||!n)return;let c=t?wm(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return rE(e);if(process.platform==="linux")return iE(e,o,()=>r);let s=tE(e);return s?(nE(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await fm(n,t);return Math.max(r,a)}}):{stop:async()=>{i=!0;let a=await fm(n,t);return Math.max(r,a)}}}function nE(n,e){let t=process.platform==="darwin"?gm:ym,r="";n.stdout?.on("data",i=>{r+=i.toString();let o=r.split(bl);r=o.pop()??"";for(let s of o)e(t(s))}),n.on("error",()=>{})}function rE(n){let e=process.memoryUsage().rss,t=setInterval(()=>{let r=process.memoryUsage().rss;r>e&&(e=r)},n);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function iE(n,e,t){e(ys());let r=setInterval(()=>e(ys()),n);return{stop:async()=>(clearInterval(r),e(ys()),t())}}function oE(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function sE(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var Ne=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=jt.dirname(e.javaPath);i.PATH=`${o}${jt.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(i.JAVA_HOME=jt.dirname(o))}b()&&(i.HVIGOR_USER_HOME=jt.join(Pl.homedir(),".hvigor")),this.env=i}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return b()?"":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}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!Ss.existsSync(t))return null;try{let r=Ss.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||jt.join(Pl.homedir(),".hvigor");return jt.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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=aE(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=Qe()?void 0:vs(o.pid,500,!0),a="";try{await o}finally{if(s){let c=await s.stop();c>0&&(a=Dt(c),m(`Hvigor peak memory: ${a}`))}}return a}};import{execa as cE}from"execa";var ln=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`);let r=cE(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Qe()?void 0:vs(r.pid,500,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=Dt(o))}}}};import{mkdir as lE}from"fs/promises";import{dirname as dE,resolve as uE}from"path";import{execa as pE}from"execa";import{lock as Cl,check as w$}from"proper-lockfile";function Il(n){return uE(n,".hvigor",".build-lock")}function mE(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function vm(n){let e=dE(Il(n));if(await lE(e,{recursive:!0}),process.platform==="win32")try{await pE("attrib",["+h",e])}catch{}}async function fE(n,e){let t=new AbortController,r=mE(e);await vm(n);let i={lockfilePath:Il(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Cl(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Cl(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function $t(n,e,t){let{release:r,signal:i}=await fE(n,t);try{return await e(i)}finally{await r()}}async function bs(n,e){let t=new AbortController;await vm(n);let r={lockfilePath:Il(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Cl(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as dn from"fs";import*as Gn from"path";import hE from"json5";var gE=1e3;function Ps(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Gn.join(n,ut.SYNC_OUTPUT_PATH);if(!dn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=dn.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=yE(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=Gn.join(n,ut.OH_PACKAGE_JSON5),o=Es(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=Gn.join(n,ut.BUILD_PROFILE_JSON5),a=Es(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Gn.join(n,l.srcPath,ut.OH_PACKAGE_JSON5),h=Es(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=Gn.join(n,l.srcPath,ut.BUILD_PROFILE_JSON5),v=Es(w,t,l.name);if(v.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${v.reason}`),v}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Es(n,e,t){if(!dn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=dn.statSync(n).mtimeMs;return r-e>gE?{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 yE(n){let e=Gn.join(n,ut.BUILD_PROFILE_JSON5);try{let t=dn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=hE.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Ye from"fs";import*as mt from"path";import*as Sm from"util";var Dl="";function Is(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Dl="";return}Dl=n}function bm(){return Dl||(Gp()??"")}function Cs(n,...e){if(e.length===0)return n;try{return Sm.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${Cs(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${Cs(n,...e)}`)},error(n,...e){g.error(`[lsp] ${Cs(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${Cs(n,...e)}`)}};import*as Li from"fs";import*as Oi from"os";import*as br from"path";import wE 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"},N="2.0";var Em=8192,Al=100,Pm=.03,Cm=.7,et=900*1e3,Ds="/data/app/sdk.org/sdk_1.0.0";function qe(n){if(!Li.existsSync(n))return null;try{let e=Li.readFileSync(n,"utf-8");return e.trim()?wE.parse(e):null}catch{return null}}function As(n,e){let t=Math.floor(Oi.totalmem()/1048576),r=Math.floor(t*Cm),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Em,n>Al&&(i+=(n-Al)*Pm*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return f.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function pt(n){if(n.startsWith("file:"))return n;try{let e=br.resolve(n),t=new URL(`file://${e}`).toString();if(Oi.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function Er(n){return n&&n.replace(/\\/g,"/")}function z(n){let e=br.normalize(n).replace(/\\/g,"/");if(Oi.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Im(n){return br.join(n,"build-profile.json5")}var Ht=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Im(this.projectRoot);try{let t=qe(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import*as Dm from"os";import*as Am from"path";import{spawn as vE}from"child_process";var SE=600*1e3;function bE(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Ts(n){return n.join("")}function EE(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
19
+ `)}`)}let o=Ke(e),s=Ke(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){if(b())return[S.join(e,"codelinter","index.js")];let r=Ge.platform()==="darwin"?["Contents"]:[];return[S.join(e,...r,"plugins","codelinter","run","index.js"),S.join(e,...r,"plugins","codelinter","index.js"),S.join(e,...r,"tools","codelinter","bin","codelinter.js"),S.join(e,...r,"tools","codelinter","codelinter.js")]}return[S.join(e,"codelinter","index.js"),S.join(e,"codelinter","run","index.js"),S.join(e,"tool","codelinter","bin","codelinter.js"),S.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return he.existsSync(S.join(e,"version.txt"));let r=Ge.platform()==="darwin"?S.join(e,"Contents"):e,i=Ge.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!he.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(he.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=Ge.platform()==="win32",i=r?".exe":"";return{nodePath:r?S.join(e,"tool","node","node.exe"):S.join(e,"tool","node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains",`hdc${i}`),emulatorPath:S.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=Ge.platform()==="darwin",r=Ge.platform()==="win32",i=t?S.join(e,"Contents"):e,o=S.join(i,"tools"),s=S.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(o,"node","node.exe"):S.join(o,"node","bin","node"),ohpmJsPath:S.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(i,"jbr","Contents","Home","bin","java"):S.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(o,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return he.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return he.existsSync(e)&&he.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.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[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Cm();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=vs(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&Ge.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=Ke(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)a&&n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(zn(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${S.sep}Contents`,r=S.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return he.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(cE)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(S.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return he.realpathSync(o);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(Ge.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(he.existsSync)}getMaxApiLevel(){for(let e of pE(this.sdkPath)){let t=uE(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ge.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":"",r=S.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=S.join(r,"resources","apiChange"),o=S.join(r,"api-change-scan.js");if(!he.existsSync(i)||!he.existsSync(o)){let s=Ir(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${lE}. Upgrade before using 'check compat' at ${Dl}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}};import{execa as DE}from"execa";import*as Ut from"path";import*as Cs from"fs";import*as kl from"os";import{execFile as Rl,spawn as km}from"child_process";import{existsSync as mE,readdirSync as fE,readFileSync as gE}from"fs";var Es="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",Al,Tl="---MEMORY-SAMPLE-DELIMITER---";function Nm(){return Al===void 0&&(Al=mE(Es)),Al}function Mi(n){return new Promise(e=>{let t=process.platform==="win32",r=t?"tasklist":"ps",i=t?["/fi",`PID eq ${n}`,"/fo","csv","/nh"]:["-o","rss=","-p",String(n)];m(`Executing: ${r} ${i.join(" ")}`),Rl(r,i,{timeout:5e3,windowsHide:!0},(o,s)=>{if(o){e(null);return}e(t?IE(s):CE(s))})})}async function hE(){return process.platform==="linux"?bs():process.platform==="darwin"?yE():process.platform==="win32"?wE():[]}function bs(){let n=[],e;try{e=fE("/proc")}catch{return n}for(let t of e){if(!/^\d+$/.test(t))continue;let r=Number(t);try{let i=gE(`/proc/${r}/status`,"utf8"),o=i.match(/VmRSS:\s+(\d+)\s+kB/),s=i.match(/^PPid:\s+(\d+)/m);if(!o||!s)continue;n.push({pid:r,ppid:Number(s[1]),rssBytes:Number(o[1])*1024})}catch{}}return n}function yE(){return new Promise(n=>{Rl("ps",["-ax","-o","pid=,ppid=,rss="],{timeout:5e3,windowsHide:!0},(e,t)=>{if(e){n([]);return}n(Lm(t))})})}function Lm(n){let e=[];for(let t of n.trim().split(`
20
+ `)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let i=Number(r[0]),o=Number(r[1]),s=Number(r[2]);isNaN(i)||isNaN(o)||isNaN(s)||e.push({pid:i,ppid:o,rssBytes:s*1024})}return e}function wE(){return new Promise(n=>{if(!Nm()){n([]);return}Rl(Es,["-NoProfile","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }'],{timeout:5e3,windowsHide:!0},(t,r)=>{if(t){n([]);return}n(Om(r))})})}function Om(n){let e=[];for(let t of n.trim().split(`
21
+ `)){let r=t.trim();if(!r)continue;let i=r.split(",");if(i.length<3)continue;let o=Number(i[0]),s=Number(i[1]),a=Number(i[2]);isNaN(o)||isNaN(s)||isNaN(a)||e.push({pid:o,ppid:s,rssBytes:a})}return e}function Mm(n,e){let t=new Map,r=new Map;for(let a of n){t.set(a.pid,a.rssBytes);let c=r.get(a.ppid);c?c.push(a.pid):r.set(a.ppid,[a.pid])}let i=0,o=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(o.has(a))continue;o.add(a),i+=t.get(a)??0;let c=r.get(a);c&&s.push(...c)}return i}async function vE(n){let e=await hE();return Mm(e,n)}function SE(n){if(process.platform==="darwin"){let e=(n/1e3).toFixed(1),t=`while true; do ps -ax -o pid=,ppid=,rss=; echo '${Tl}'; sleep ${e}; done`;return m(`Executing: sh -c ${t}`),km("sh",["-c",t],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}if(process.platform==="win32"&&Nm()){let e=`while ($true) { Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId),$($_.WorkingSetSize)" }; Write-Output '${Tl}'; Start-Sleep -Milliseconds ${n} }`;return m(`Executing: ${Es} -NoProfile -Command ${e}`),km(Es,["-NoProfile","-Command",e],{stdio:["ignore","pipe","ignore"],windowsHide:!0})}return null}function It(n){return`${(n/1024/1024).toFixed(2)}MB`}async function xm(n,e){if(!n)return process.memoryUsage().rss;if(e)return vE(n);let t=await Mi(n);return t?Number(t)*1024:0}function Ps(n,e=500,t=!1){let r=0,i=!1,o=a=>{if(i||!n)return;let c=t?Mm(a,n):a.find(l=>l.pid===n)?.rssBytes??0;c>r&&(r=c)};if(!n)return EE(e);if(process.platform==="linux")return PE(e,o,()=>r);let s=SE(e);return s?(bE(s,o),{stop:async()=>{i=!0;try{s.kill()}catch{}let a=await xm(n,t);return Math.max(r,a)}}):{stop:async()=>{i=!0;let a=await xm(n,t);return Math.max(r,a)}}}function bE(n,e){let t=process.platform==="darwin"?Lm:Om,r="";n.stdout?.on("data",i=>{r+=i.toString();let o=r.split(Tl);r=o.pop()??"";for(let s of o)e(t(s))}),n.on("error",()=>{})}function EE(n){let e=process.memoryUsage().rss,t=setInterval(()=>{let r=process.memoryUsage().rss;r>e&&(e=r)},n);return{stop:async()=>(clearInterval(t),Math.max(e,process.memoryUsage().rss))}}function PE(n,e,t){e(bs());let r=setInterval(()=>e(bs()),n);return{stop:async()=>(clearInterval(r),e(bs()),t())}}function CE(n){let e=n.trim().match(/^(\d+)$/);return e?e[1]:null}function IE(n){let e=n.match(/"([^"]+?)\s*K"/i);return e&&e[1].replace(/\D/g,"")||null}var xe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let o=Ut.dirname(e.javaPath);i.PATH=`${o}${Ut.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(i.JAVA_HOME=Ut.dirname(o))}b()&&(i.HVIGOR_USER_HOME=Ut.join(kl.homedir(),".hvigor")),this.env=i}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];return this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];return this.runHvigor(e)}async stopDaemon(){return b()?"":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}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!Cs.existsSync(t))return null;try{let r=Cs.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Ut.join(kl.homedir(),".hvigor");return Ut.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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit",o=DE(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i}),s=Ze()?void 0:Ps(o.pid,500,!0),a="";try{await o}finally{if(s){let c=await s.stop();c>0&&(a=It(c),m(`Hvigor peak memory: ${a}`))}}return a}};import{execa as AE}from"execa";var mn=class{toolProvider;projectRoot;peakMemoryMb="";constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`);let r=AE(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"}),i=Ze()?void 0:Ps(r.pid,500,!1);try{await r}finally{if(i){let o=await i.stop();o>0&&(this.peakMemoryMb=It(o))}}}};import{mkdir as TE}from"fs/promises";import{dirname as RE,resolve as kE}from"path";import{execa as xE}from"execa";import{lock as xl,check as H$}from"proper-lockfile";function Nl(n){return kE(n,".hvigor",".build-lock")}function NE(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function _m(n){let e=RE(Nl(n));if(await TE(e,{recursive:!0}),process.platform==="win32")try{await xE("attrib",["+h",e])}catch{}}async function LE(n,e){let t=new AbortController,r=NE(e);await _m(n);let i={lockfilePath:Nl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await xl(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await xl(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Bt(n,e,t){let{release:r,signal:i}=await LE(n,t);try{return await e(i)}finally{await r()}}async function Is(n,e){let t=new AbortController;await _m(n);let r={lockfilePath:Nl(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await xl(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as fn from"fs";import*as Kn from"path";import OE from"json5";var ME=1e3;function As(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Kn.join(n,lt.SYNC_OUTPUT_PATH);if(!fn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=fn.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=_E(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=Kn.join(n,lt.OH_PACKAGE_JSON5),o=Ds(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=Kn.join(n,lt.BUILD_PROFILE_JSON5),a=Ds(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Kn.join(n,l.srcPath,lt.OH_PACKAGE_JSON5),g=Ds(d,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=Kn.join(n,l.srcPath,lt.BUILD_PROFILE_JSON5),v=Ds(w,t,l.name);if(v.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${v.reason}`),v}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Ds(n,e,t){if(!fn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=fn.statSync(n).mtimeMs;return r-e>ME?{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 _E(n){let e=Kn.join(n,lt.BUILD_PROFILE_JSON5);try{let t=fn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=OE.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as qe from"fs";import*as ut from"path";import*as Fm from"util";var Ll="";function Rs(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Ll="";return}Ll=n}function jm(){return Ll||(cm()??"")}function Ts(n,...e){if(e.length===0)return n;try{return Fm.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){h.info(`[lsp] ${Ts(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${Ts(n,...e)}`)},error(n,...e){h.error(`[lsp] ${Ts(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${Ts(n,...e)}`)}};import*as _i from"fs";import*as Fi from"os";import*as Dr from"path";import FE 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"},N="2.0";var $m=8192,Ol=100,Hm=.03,Um=.7,Qe=900*1e3,ks="/data/app/sdk.org/sdk_1.0.0";function ze(n){if(!_i.existsSync(n))return null;try{let e=_i.readFileSync(n,"utf-8");return e.trim()?FE.parse(e):null}catch{return null}}function xs(n,e){let t=Math.floor(Fi.totalmem()/1048576),r=Math.floor(t*Um),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=$m,n>Ol&&(i+=(n-Ol)*Hm*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return f.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function dt(n){if(n.startsWith("file:"))return n;try{let e=Dr.resolve(n),t=new URL(`file://${e}`).toString();if(Fi.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function Ar(n){return n&&n.replace(/\\/g,"/")}function z(n){let e=Dr.normalize(n).replace(/\\/g,"/");if(Fi.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Bm(n){return Dr.join(n,"build-profile.json5")}var Wt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Bm(this.projectRoot);try{let t=ze(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import*as Wm from"os";import*as Vm from"path";import{spawn as jE}from"child_process";var $E=600*1e3;function HE(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Ns(n){return n.join("")}function UE(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
22
22
  Output so far:
23
- `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function PE(n,e,t){return new Promise(r=>{let i=vE(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=bE(i),a=setTimeout(()=>{i.kill();let c=[Ts(o),Ts(s)].filter(Boolean).join(`
23
+ `+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function BE(n,e,t){return new Promise(r=>{let i=jE(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=HE(i),a=setTimeout(()=>{i.kill();let c=[Ns(o),Ns(s)].filter(Boolean).join(`
24
24
  `).trim();r({success:!1,output:`Build process timeout after 10 minutes.
25
25
  Output so far:
26
- `+c,exitCode:-1})},SE);i.on("close",(c,l)=>{clearTimeout(a);let d=[Ts(o),Ts(s)].filter(Boolean).join(`
27
- `).trim()||"";r(EE(c,l,d))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Tl(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r};return b()&&(o.HVIGOR_USER_HOME=Am.join(Dm.homedir(),".hvigor")),await PE([e,[t,...i]],n,o)}var CE=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Tm(n,e){try{return(await Tl(n,e.nodePath,e.hvigorJsPath,e.sdkPath,CE)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function IE(n){let e=mt.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function DE(n,e){let t=mt.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Rm(t):IE(t)}function Rm(n){if(!Ye.existsSync(n))return!1;try{return Ye.readdirSync(n,{withFileTypes:!0}).some(t=>DE(n,t))}catch{}return!1}function zn(n){try{let t=new Ht(n).getAllModuleInfo(),r=[];for(let i of t){let o=mt.resolve(n,i.srcPath);Rm(o)&&r.push(i)}return r}catch(e){throw g.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function AE(n){let e=[],r=new Ht(n).getAllModuleInfo();for(let i of r){let o=mt.resolve(n,i.srcPath),s=mt.join(o,".cxx");Ye.existsSync(s)&&km(s,e)}return e}function km(n,e){try{let t=Ye.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=mt.join(n,r.name);r.isDirectory()?km(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function TE(n){let e=[];for(let t of n)try{let r=Ye.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function RE(n,e){let t=mt.join(n,...il.slice(0,-1));Ye.mkdirSync(t,{recursive:!0});let r=mt.join(t,"compile_commands.json");Ye.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function Rl(n){let e=AE(n);if(e.length>0){let t=TE(e);RE(n,t),g.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else g.warn("[CppCompile] No compile_commands.json files found")}async function kE(n,e,t){g.info(`[CppCompile] devecoPath: ${e.devecoStudioPath}, sdkPath: ${e.sdkPath}, nodePath: ${e.nodePath},hvigorJsPath:${e.hvigorJsPath}`);for(let r of t){let i=["--mode","module","-p",`module=${r.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"];g.info(`[CppCompile] Running compileNative for module: ${r.name}`);let o=await Tl(n,e.nodePath,e.hvigorJsPath,e.sdkPath,i);o.success?g.info(`[CppCompile] compileNative ${r.name} succeeded`):g.warn(`[CppCompile] compileNative ${r.name} failed: ${o.output}`)}}async function xm(n,e){let t=zn(n);if(t.length===0){g.info("[CppCompile] No C++ modules found, skipping initialization");return}g.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await kE(n,e,t),Rl(n)}function NE(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function LE(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new T(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new T(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function _i(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Mi(n,e){let t=e,r=`${n} failed`;console.error(Nm(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Fi(n,e,t,r,i,o){let s=Ps(o);console.log(`
28
- [ohpm install] Running...`);try{await n.installAll()}catch(l){Mi("ohpm install",l)}let a="";if(s.required){console.log(`
29
- [hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){Mi("hvigor sync",l)}}else console.log(`
26
+ `+c,exitCode:-1})},$E);i.on("close",(c,l)=>{clearTimeout(a);let d=[Ns(o),Ns(s)].filter(Boolean).join(`
27
+ `).trim()||"";r(UE(c,l,d))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Ml(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r};return b()&&(o.HVIGOR_USER_HOME=Vm.join(Wm.homedir(),".hvigor")),await BE([e,[t,...i]],n,o)}var WE=["--sync","-p","product=default","--analyze=normal","--parallel","--incremental","--no-daemon"];async function Gm(n,e){try{return(await Ml(n,e.nodePath,e.hvigorJsPath,e.sdkPath,WE)).success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function VE(n){let e=ut.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function GE(n,e){let t=ut.join(n,e.name);return e.isDirectory()?e.name===".cxx"||zm(t):VE(t)}function zm(n){if(!qe.existsSync(n))return!1;try{return qe.readdirSync(n,{withFileTypes:!0}).some(t=>GE(n,t))}catch{}return!1}function Xn(n){try{let t=new Wt(n).getAllModuleInfo(),r=[];for(let i of t){let o=ut.resolve(n,i.srcPath);zm(o)&&r.push(i)}return r}catch(e){throw h.error(`[CppCompile] findCppModules threw: ${e instanceof Error?e.message:String(e)}`),e}}function zE(n){let e=[],r=new Wt(n).getAllModuleInfo();for(let i of r){let o=ut.resolve(n,i.srcPath),s=ut.join(o,".cxx");qe.existsSync(s)&&qm(s,e)}return e}function qm(n,e){try{let t=qe.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=ut.join(n,r.name);r.isDirectory()?qm(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function qE(n){let e=[];for(let t of n)try{let r=qe.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function YE(n,e){let t=ut.join(n,...ul.slice(0,-1));qe.mkdirSync(t,{recursive:!0});let r=ut.join(t,"compile_commands.json");qe.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function _l(n){let e=zE(n);if(e.length>0){let t=qE(e);YE(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}async function JE(n,e,t){h.info(`[CppCompile] devecoPath: ${e.devecoStudioPath}, sdkPath: ${e.sdkPath}, nodePath: ${e.nodePath},hvigorJsPath:${e.hvigorJsPath}`);for(let r of t){let i=["--mode","module","-p",`module=${r.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"];h.info(`[CppCompile] Running compileNative for module: ${r.name}`);let o=await Ml(n,e.nodePath,e.hvigorJsPath,e.sdkPath,i);o.success?h.info(`[CppCompile] compileNative ${r.name} succeeded`):h.warn(`[CppCompile] compileNative ${r.name} failed: ${o.output}`)}}async function Ym(n,e){let t=Xn(n);if(t.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await JE(n,e,t),_l(n)}function XE(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode&&!n.profile.app.buildModeSet.some(r=>r.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function ZE(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new T(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"Multiple entry modules found."):new T(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`,"No entry module found and multiple modules available.")}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function $i(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function ji(n,e){let t=e,r=`${n} failed`;console.error(Jm(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function Hi(n,e,t,r,i,o){let s=As(o);console.log(`
28
+ [ohpm install] Running...`);try{await n.installAll()}catch(l){ji("ohpm install",l)}let a="";if(s.required){console.log(`
29
+ [hvigor sync] Running...`);try{a=await e.sync(t,r)}catch(l){ji("hvigor sync",l)}}else console.log(`
30
30
  [hvigor sync] Skipped (configurations unchanged)`);console.log(`
31
- [hvigor build] Running...`);let c="";try{i.type==="product"?c=await e.buildProduct(t,r):c=await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(l){Mi("hvigor build",l)}return OE(o),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function OE(n){try{if(zn(n).length===0)return;Rl(n),console.log(kl(`
32
- Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(xl(`
33
- Failed to merge compile_commands.json: ${e.message}`))}}async function Lm(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=W(o),console.error(Nm(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o)}}function ME(n){let e={event:D.CommandExecuted,args:["build",...n.product?["--product"]:[],...n.modules?["--modules"]:[],...n.buildMode?["--build-mode"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.modules&&(e.module_count=n.modules.length),e}function _E(){return{event:D.CommandExecuted,args:["build","clean"]}}async function FE(n){let e=process.cwd(),t=K.discover(e);console.warn(xl("Ensure the project source is trustworthy before proceeding."));let r=await A.new();r.assertJava(),NE(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let d=LE(t,n),h=_i(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:h}}let a=new ln(r,t.rootDir),c=new Ne(r,t.rootDir),l=await $t(t.rootDir,async()=>Fi(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
34
- `+kl("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function jE(){let n=process.cwd(),e=K.discover(n);console.warn(xl("Ensure the project source is trustworthy before proceeding."));let t=await A.new();t.assertJava();let r=new Ne(t,e.rootDir);return await $t(e.rootDir,async()=>{console.log(`
35
- [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Mi("hvigor clean",i)}console.log(`
36
- [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Mi("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
37
- `+kl("Clean completed successfully.")),e.getBundleName()}var Om=new xE("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 n=>{let e=ME(n);await Lm(e,async()=>{let t=await FE(n);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)})});Om.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let n=_E();await Lm(n,async()=>{n.bundle_name=await jE()})});var Mm=Om;import{Command as VP}from"commander";import{green as Vi,red as GP,yellow as Bs}from"colorette";import*as Ws from"path";import{randomUUID as ZE}from"crypto";import{execa as QE}from"execa";import{execa as KE}from"execa";import{execFile as $E,spawn as HE}from"child_process";import{promisify as UE}from"util";var BE=UE($E);function _m(n,e,t){let i=n.replace(/\r\n/g,`
31
+ [hvigor build] Running...`);let c="";try{i.type==="product"?c=await e.buildProduct(t,r):c=await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(l){ji("hvigor build",l)}return QE(o),{ohpmMemoryMb:n.peakMemoryMb,syncMemoryMb:a,buildMemoryMb:c}}function QE(n){try{if(Xn(n).length===0)return;_l(n),console.log(Fl(`
32
+ Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(jl(`
33
+ Failed to merge compile_commands.json: ${e.message}`))}}async function Km(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=W(o),console.error(Jm(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o)}}function eP(n){let e={event:D.CommandExecuted,args:["build",...n.product?["--product"]:[],...n.modules?["--modules"]:[],...n.buildMode?["--build-mode"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.modules&&(e.module_count=n.modules.length),e}function tP(){return{event:D.CommandExecuted,args:["build","clean"]}}async function nP(n){let e=process.cwd(),t=K.discover(e);console.warn(jl("Ensure the project source is trustworthy before proceeding."));let r=await A.new();r.assertJava(),XE(t,n);let i=n.product||"default",o=n.buildMode||"debug",s;if(n.product&&!n.modules)s={type:"product"};else{let d=ZE(t,n),g=$i(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:g}}let a=new mn(r,t.rootDir),c=new xe(r,t.rootDir),l=await Bt(t.rootDir,async()=>Hi(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")});return console.log(`
34
+ `+Fl("Build completed successfully")),{bundleName:t.getBundleName(),ohpmMemoryMb:l.ohpmMemoryMb,syncMemoryMb:l.syncMemoryMb,buildMemoryMb:l.buildMemoryMb}}async function rP(){let n=process.cwd(),e=K.discover(n);console.warn(jl("Ensure the project source is trustworthy before proceeding."));let t=await A.new();t.assertJava();let r=new xe(t,e.rootDir);return await Bt(e.rootDir,async()=>{console.log(`
35
+ [1/2] Running hvigor clean...`);try{await r.clean()}catch(i){ji("hvigor clean",i)}console.log(`
36
+ [2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){ji("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
37
+ `+Fl("Clean completed successfully.")),e.getBundleName()}var Xm=new KE("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 n=>{let e=eP(n);await Km(e,async()=>{let t=await nP(n);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)})});Xm.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{let n=tP();await Km(n,async()=>{n.bundle_name=await rP()})});var Zm=Xm;import{Command as lC}from"commander";import{green as qi,red as dC,yellow as zs}from"colorette";import*as qs from"path";import{randomUUID as yP}from"crypto";import{execa as wP}from"execa";import{execa as gP}from"execa";import{execFile as iP,spawn as oP}from"child_process";import{promisify as sP}from"util";var aP=sP(iP);function Qm(n,e,t){let i=n.replace(/\r\n/g,`
38
38
  `).split(`
39
- `),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function Fm(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function WE(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function VE(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function GE(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=_m(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=_m(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,Fm(e.stdoutLineBuffer,"stdout",t),Fm(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=WE(e,o);r(s)})}async function qn(n,e=[],t={}){try{let{stdout:r,stderr:i}=await BE(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function jm(n,e,t){return await new Promise((r,i)=>{let o=HE(n,e,{stdio:["inherit","pipe","pipe"]}),s=VE();GE(o,s,t,r,i)})}function $m(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var zE=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],qE=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Pr(n){return n?zE.some(e=>e.test(n))?"transient":qE.some(e=>e.test(n))?"fatal":"ok":"ok"}var Nl=[800,1500,2500];function YE(n){return new Promise(e=>setTimeout(e,n))}async function se(n,e){let t=1+Nl.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await qn(n,e),r.exitCode===0||Pr(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Nl[i]}ms`),await YE(Nl[i])}return r}var Hm=/^[\w.-]+$/;async function Rs(n,e,t){if(!Hm.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let i=await se(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Pr(o)!=="ok"))return $m(o)}var Ll="__DEVECO_PARAM_DELIM__";function JE(n,e){let t=new Map,r=n.split(Ll);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Pr(o)!=="ok")continue;let s=$m(o);s&&t.set(e[i],s)}return t}async function Cr(n,e,t){let r=t.filter(a=>Hm.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await Rs(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${Ll}; `)+`; echo ${Ll}`,o=await se(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=JE(o.stdout,r);if(a.size>0)return a}m(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await Rs(n,e,a);c&&s.set(a,c)}return s}function ji(n){return n.startsWith("127.0.0.1:")}var Um=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ae=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),KE(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
40
- `)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){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 r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Cr(this.hdcPath,e,[...Um]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
39
+ `),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function ef(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function cP(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function lP(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function dP(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Qm(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Qm(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,ef(e.stdoutLineBuffer,"stdout",t),ef(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=cP(e,o);r(s)})}async function Zn(n,e=[],t={}){try{let{stdout:r,stderr:i}=await aP(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function tf(n,e,t){return await new Promise((r,i)=>{let o=oP(n,e,{stdio:["inherit","pipe","pipe"]}),s=lP();dP(o,s,t,r,i)})}function nf(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var uP=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],pP=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Tr(n){return n?uP.some(e=>e.test(n))?"transient":pP.some(e=>e.test(n))?"fatal":"ok":"ok"}var $l=[800,1500,2500];function mP(n){return new Promise(e=>setTimeout(e,n))}async function se(n,e){let t=1+$l.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Zn(n,e),r.exitCode===0||Tr(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${$l[i]}ms`),await mP($l[i])}return r}var rf=/^[\w.-]+$/;async function Ls(n,e,t){if(!rf.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let i=await se(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Tr(o)!=="ok"))return nf(o)}var Hl="__DEVECO_PARAM_DELIM__";function fP(n,e){let t=new Map,r=n.split(Hl);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Tr(o)!=="ok")continue;let s=nf(o);s&&t.set(e[i],s)}return t}async function Rr(n,e,t){let r=t.filter(a=>rf.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await Ls(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${Hl}; `)+`; echo ${Hl}`,o=await se(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=fP(o.stdout,r);if(a.size>0)return a}m(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await Ls(n,e,a);c&&s.set(a,c)}return s}function Ui(n){return n.startsWith("127.0.0.1:")}var of=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],ae=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),gP(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
40
+ `)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){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 r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Rr(this.hdcPath,e,[...of]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
41
41
  `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
42
- `)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Cr(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=b()?!1:ji(e),r,i;try{let o=await Cr(this.hdcPath,e,[...Um]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}async ensureWirelessSelfConnection(){if(!b())return{mode:"tcp"};let e=await this.getLocalParam("persist.hdc.mode");if(!e)return{mode:""};if(e!=="tcp")return{mode:e};let t=await this.getLocalParam("persist.hdc.port");if(!t)return{mode:"tcp"};let r=await this.listDevices();if(this.hasDeviceWithPort(r,t))return{mode:"tcp",port:t,autoConnected:!1};let i=`127.0.0.1:${t}`;m(`Executing: ${this.hdcPath} tconn ${i}`);let o=!1;try{await this.executeHdc(["tconn",i]),o=!0}catch(s){m(`hdc tconn ${i} failed: ${s.message}`)}return{mode:"tcp",port:t,autoConnected:o}}async getLocalParam(e){m(`Executing: param get ${e}`);let t=await qn("param",["get",e]);return t.exitCode!==0||!t.stdout||/^Get parameter\b.*fail!/i.test(t.stdout)?"":this.parseLocalParamValue(t.stdout)}parseLocalParamValue(e){let t=e.trim(),r=t.indexOf("=");if(r!==-1)return t.slice(r+1).trim();let i=t.match(/^[\w.]+\s*:\s*(.+)$/);return i?i[1].trim():t}hasDeviceWithPort(e,t){let r=`127.0.0.1:${t}`;return e.some(i=>i.serial===r)}};import{execa as Ol}from"execa";var Ir="local";function At(n){return n===Ir}function ks(n){return n.length>=2&&n[0]==="-t"&&At(n[1])}var XE=["failed to execute","permission denied","inaccessible","not found"];function Bm(n){let e=n.toLowerCase();return XE.some(t=>e.includes(t))}async function $i(){try{let n=await Ol("sh",["-c","bm help 2>&1"],{reject:!1,timeout:5e3}),e=(n.stdout||"")+(n.stderr||"");if(Bm(e))return!1;let t=await Ol("sh",["-c","aa help 2>&1"],{reject:!1,timeout:5e3}),r=(t.stdout||"")+(t.stderr||"");return!Bm(r)}catch{return!1}}async function xs(n,e){let t=n.join(" ");m(`Executing: ${t}`);try{let{stdout:r}=await Ol("sh",["-c",t]);return r}catch(r){if(!e)return r.stdout||"";throw r}}var Ut=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;if(ks(e)&&e[2]==="shell")return xs(e.slice(3),t);m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await QE(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){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;if(At(e)){for(let o of t){let s=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!s.includes("install bundle successfully."))throw new Error(s)}console.log("App installed successfully");return}let i=`/data/local/tmp/${ZE()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async connectTarget(e){await this.runHdc(["tconn",e])}async disconnectTarget(e){await this.runHdc(["tconn",e,"-remove"],!1)}async listRawTargets(){return(await this.runHdc(["list","targets"],!1)).split(`
42
+ `)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Rr(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=b()?!1:Ui(e),r,i;try{let o=await Rr(this.hdcPath,e,[...of]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}async ensureWirelessSelfConnection(){if(!b())return{mode:"tcp"};let e=await this.getLocalParam("persist.hdc.mode");if(!e)return{mode:""};if(e!=="tcp")return{mode:e};let t=await this.getLocalParam("persist.hdc.port");if(!t)return{mode:"tcp"};let r=await this.listDevices();if(this.hasDeviceWithPort(r,t))return{mode:"tcp",port:t,autoConnected:!1};let i=`127.0.0.1:${t}`;m(`Executing: ${this.hdcPath} tconn ${i}`);let o=!1;try{await this.executeHdc(["tconn",i]),o=!0}catch(s){m(`hdc tconn ${i} failed: ${s.message}`)}return{mode:"tcp",port:t,autoConnected:o}}async getLocalParam(e){m(`Executing: param get ${e}`);let t=await Zn("param",["get",e]);return t.exitCode!==0||!t.stdout||/^Get parameter\b.*fail!/i.test(t.stdout)?"":this.parseLocalParamValue(t.stdout)}parseLocalParamValue(e){let t=e.trim(),r=t.indexOf("=");if(r!==-1)return t.slice(r+1).trim();let i=t.match(/^[\w.]+\s*:\s*(.+)$/);return i?i[1].trim():t}hasDeviceWithPort(e,t){let r=`127.0.0.1:${t}`;return e.some(i=>i.serial===r)}};import{execa as Ul}from"execa";var kr="local";function Dt(n){return n===kr}function Os(n){return n.length>=2&&n[0]==="-t"&&Dt(n[1])}var hP=["failed to execute","permission denied","inaccessible","not found"];function sf(n){let e=n.toLowerCase();return hP.some(t=>e.includes(t))}async function Bi(){try{let n=await Ul("sh",["-c","bm help 2>&1"],{reject:!1,timeout:5e3}),e=(n.stdout||"")+(n.stderr||"");if(sf(e))return!1;let t=await Ul("sh",["-c","aa help 2>&1"],{reject:!1,timeout:5e3}),r=(t.stdout||"")+(t.stderr||"");return!sf(r)}catch{return!1}}async function Ms(n,e){let t=n.join(" ");m(`Executing: ${t}`);try{let{stdout:r}=await Ul("sh",["-c",t]);return r}catch(r){if(!e)return r.stdout||"";throw r}}var Vt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;if(Os(e)&&e[2]==="shell")return Ms(e.slice(3),t);m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await wP(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){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;if(Dt(e)){for(let o of t){let s=await this.runHdc(["-t",e,"shell","bm","install","-p",o]);if(!s.includes("install bundle successfully."))throw new Error(s)}console.log("App installed successfully");return}let i=`/data/local/tmp/${yP()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async connectTarget(e){await this.runHdc(["tconn",e])}async disconnectTarget(e){await this.runHdc(["tconn",e,"-remove"],!1)}async listRawTargets(){return(await this.runHdc(["list","targets"],!1)).split(`
43
43
  `).map(t=>t.trim()).filter(t=>t.length>0&&t!=="[Empty]")}async isDevEcoStudioRunningViaHdc(e){return(await this.runHdc(["-t",e,"shell","ps -ef | grep com.huawei.devecostudio | grep -v grep"],!1)).trim().length>0}async isDevEcoStudioRunningOnLocal(){if(process.env.DEVECO_RUNTIME==="deveco-studio")return m("DEVECO_RUNTIME=deveco-studio detected, skipping IDE process check"),!0;if(!(await this.deviceManager.ensureWirelessSelfConnection()).mode)throw new Error(`Wireless debugging is not enabled. The previewer requires wireless debugging to detect DevEco Studio.
44
- Enable: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`);let r=(await this.deviceManager.listDevices()).find(i=>i.serial.includes("127.0.0.1"));if(!r)throw new Error("Local device not found in hdc targets. Please ensure wireless debugging is enabled and connected.");return await this.isDevEcoStudioRunningViaHdc(r.serial)}async launchPreview(e,t,r,i,o,s,a,c,l){let h=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:i,productType:o,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),w=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${h}'`;return await this.runHdc(["-t",e,"shell",w])}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import Ml from"fs";import*as Yn from"path";function Hi(n,e){if(!Ml.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Ml.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Yn.resolve(e),o=new Set,s=[];for(let a of r){let c=Yn.resolve(i,a),l=Yn.isAbsolute(a)?Yn.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=x.isPathContainedWithSymlink(l,i);if(!d.contained){if(!Ml.existsSync(c))throw new Error(`File not found: ${a}`);let h=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${h}`)}o.has(c)||(o.add(c),s.push(c))}return s}import _l from"fs";import Dr from"path";import{execa as nP}from"execa";import Wm from"fs";import*as Vm from"path";import eP from"json5";function tP(n,e){try{let r=eP.parse(Wm.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function Tt(n,e){let t=Vm.join(n,"build-profile.json5");return Wm.existsSync(t)?tP(t,e)??e:e}import*as Gm from"os";async function zm(n,e,t,r){let i={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=Dr.dirname(n.javaPath);i.PATH=`${c}${Dr.delimiter}${process.env.PATH||""}`}b()&&(i.HVIGOR_USER_HOME=Dr.join(Gm.homedir(),".hvigor"));let o=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${o.join(" ")}`);let s=await nP(n.nodePath,o,{cwd:e,env:i,stdout:"inherit",stderr:"inherit",reject:!1}),a=(s.exitCode??0)|0;if(a===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(a!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${s.exitCode}`);return t.map(c=>iP(e,c,r))}function qm(n,e,t){let r=Tt(n,e);return Dr.join(n,r,"build",t,"outputs")}function rP(n,e,t){return Dr.join(qm(n,e,t),`${e}-${t}-signed.hqf`)}function iP(n,e,t){let r=qm(n,e,t),i=rP(n,e,t);if(_l.existsSync(i))return i;let o=Fl(r,"-signed.hqf")??Fl(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function Fl(n,e){if(!_l.existsSync(n))return null;for(let t of _l.readdirSync(n,{withFileTypes:!0})){let r=Dr.join(n,t.name);if(t.isDirectory()){let i=Fl(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import Q from"fs";import*as M from"path";import jl from"json5";var Ym="default",Ar=class n{static writeChangedFileLists(e,t,r,i){let o=t||Ym,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),h=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:h}}static initEmptyChangedFileLists(e,t,r){let i=t||Ym,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=M.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let h=n.resolveTargetModules(d,t,r,i);if(h.length===0){s.push(c);continue}n.dispatchToCollectors(h,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=M.join(e,r,"build",t,"intermediates","patch","default"),s=M.join(o,"changedFileList.json");if(Q.existsSync(s)||(Q.mkdirSync(o,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=M.join(e,r,"build",t,"intermediates","hotReload"),c=M.join(a,"changedFileList.json");Q.existsSync(c)||(Q.mkdirSync(a,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=M.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8");return jl.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=M.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=M.normalize(e);for(let o of r){let s=M.normalize(M.join(t,o.srcPath)),a=s+M.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=M.join(e,t,"src","main","module.json5");if(!Q.existsSync(r))return"entry";try{let i=Q.readFileSync(r,"utf-8");return jl.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=M.join(e,t,"oh-package.json5");if(!Q.existsSync(r))return[];try{let i=Q.readFileSync(r,"utf-8"),o=jl.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=M.resolve(e,t,o);return i.find(l=>M.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(h=>h.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=M.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=M.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=M.dirname(s);Q.existsSync(l)||Q.mkdirSync(l,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[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,i,o,s){let a=t.replace(/^\.\//,""),c=M.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=M.join(e,a,"src","main","ets"),h=i.map(We=>n.resolveRelativePathForPatch(We,d)),w=n.mergeStrings(l.modifiedFiles,h),v=n.mergePatchResources(l.rawFile,o),k=n.mergePatchResources(l.resFile,s),ce=M.dirname(c);Q.existsSync(ce)||Q.mkdirSync(ce,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({resources:{resFile:k,rawFile:v},modifiedFiles:w}),"utf-8"),m(`[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 M.relative(M.normalize(t),M.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import oP from"fs";import{randomUUID as sP}from"crypto";import{execa as aP}from"execa";var Tr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!oP.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}if(At(e))return await this.executeQuickfix(e,t);let o=`/data/local/tmp/${sP()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let o=await this.runHdc(r,!1);if(m(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;if(ks(e)&&e[2]==="shell")return xs(e.slice(3),t);m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await aP(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var cP="6.1.1",Ns=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await $t(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(cP);let t=Hi(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),i=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Ar.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 m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await zm(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Tr(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Ut(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 Ut(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 Jm from"fs";import*as U from"path";var Ls=class n{static generate(e,t,r,i){let o=Tt(e,t),s=U.join(e,o),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Jm.mkdirSync(a,{recursive:!0}),Jm.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=U.dirname(i.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:o,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,"patch","default","changedFileList.json"),patchAbcPath:U.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import Km from"fs";import*as B from"path";var Os=class n{static generate(e,t,r,i){let o=Tt(e,t),s=B.join(e,o),a=B.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Km.mkdirSync(a,{recursive:!0}),Km.writeFileSync(B.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=B.dirname(i.nodePath)+B.sep,s=B.join(t,"build",r),a=B.join(s,"intermediates"),c=B.join(a,"loader_out",r),l=B.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:B.join(e,"build-profile.json5"),localPropertiesPath:B.join(e,"local.properties"),appResource:B.join(l,"ResourceTable.txt"),cachePath:B.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:B.join(a,"loader",r,"loader.json"),aceModuleJsonPath:B.join(l,"module.json"),aceSoPath:B.join(c,"nativeDependencies.txt"),aceModuleRoot:B.join(t,"src","main","ets"),aceModuleBuild:B.join(c,"ets"),aceProfilePath:B.join(l,"resources","base","profile"),aceSuperVisualPath:B.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:B.join(c,"ets"),changedFileList:B.join(a,"hotReload","changedFileList.json"),patchAbcPath:B.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Xm from"crypto";import tt from"fs";import nt from"path";import Zm from"os";import{io as lP}from"socket.io-client";var dP=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Rr=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;tt.mkdirSync(nt.dirname(i),{recursive:!0}),tt.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
44
+ Enable: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`);let r=(await this.deviceManager.listDevices()).find(i=>i.serial.includes("127.0.0.1"));if(!r)throw new Error("Local device not found in hdc targets. Please ensure wireless debugging is enabled and connected.");return await this.isDevEcoStudioRunningViaHdc(r.serial)}async launchPreview(e,t,r,i,o,s,a,c,l){let g=JSON.stringify({bundleName:t,abilityName:r,moduleName:s,productName:i,productType:o,subProductType:a,instanceId:c,launchDeviceIndex:l,launchFlag:"{}",isCustom:!1,nativeDebuggable:!1,appDebuggable:!1}).replace(/'/g,"'\\''"),w=`aa start -a DevEcoViewerAbility -b com.huawei.devecostudio -m DevEcoViewer --pi instanceId ${c} --ps paramJson '${g}'`;return await this.runHdc(["-t",e,"shell",w])}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import Bl from"fs";import*as Qn from"path";function Wi(n,e){if(!Bl.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=Bl.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=Qn.resolve(e),o=new Set,s=[];for(let a of r){let c=Qn.resolve(i,a),l=Qn.isAbsolute(a)?Qn.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=x.isPathContainedWithSymlink(l,i);if(!d.contained){if(!Bl.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import Wl from"fs";import xr from"path";import{execa as bP}from"execa";import af from"fs";import*as cf from"path";import vP from"json5";function SP(n,e){try{let r=vP.parse(af.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function At(n,e){let t=cf.join(n,"build-profile.json5");return af.existsSync(t)?SP(t,e)??e:e}import*as lf from"os";async function df(n,e,t,r){let i={...process.env,DEVECO_SDK_HOME:n.sdkPath};if(n.javaPath){let c=xr.dirname(n.javaPath);i.PATH=`${c}${xr.delimiter}${process.env.PATH||""}`}b()&&(i.HVIGOR_USER_HOME=xr.join(lf.homedir(),".hvigor"));let o=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${o.join(" ")}`);let s=await bP(n.nodePath,o,{cwd:e,env:i,stdout:"inherit",stderr:"inherit",reject:!1}),a=(s.exitCode??0)|0;if(a===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(a!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${s.exitCode}`);return t.map(c=>PP(e,c,r))}function uf(n,e,t){let r=At(n,e);return xr.join(n,r,"build",t,"outputs")}function EP(n,e,t){return xr.join(uf(n,e,t),`${e}-${t}-signed.hqf`)}function PP(n,e,t){let r=uf(n,e,t),i=EP(n,e,t);if(Wl.existsSync(i))return i;let o=Vl(r,"-signed.hqf")??Vl(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function Vl(n,e){if(!Wl.existsSync(n))return null;for(let t of Wl.readdirSync(n,{withFileTypes:!0})){let r=xr.join(n,t.name);if(t.isDirectory()){let i=Vl(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import Q from"fs";import*as M from"path";import Gl from"json5";var pf="default",Nr=class n{static writeChangedFileLists(e,t,r,i){let o=t||pf,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||pf,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=M.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=M.join(e,r,"build",t,"intermediates","patch","default"),s=M.join(o,"changedFileList.json");if(Q.existsSync(s)||(Q.mkdirSync(o,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=M.join(e,r,"build",t,"intermediates","hotReload"),c=M.join(a,"changedFileList.json");Q.existsSync(c)||(Q.mkdirSync(a,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=M.join(e,"build-profile.json5");if(!Q.existsSync(t))return null;try{let r=Q.readFileSync(t,"utf-8");return Gl.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=M.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=M.normalize(e);for(let o of r){let s=M.normalize(M.join(t,o.srcPath)),a=s+M.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=M.join(e,t,"src","main","module.json5");if(!Q.existsSync(r))return"entry";try{let i=Q.readFileSync(r,"utf-8");return Gl.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=M.join(e,t,"oh-package.json5");if(!Q.existsSync(r))return[];try{let i=Q.readFileSync(r,"utf-8"),o=Gl.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=M.resolve(e,t,o);return i.find(l=>M.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=M.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=M.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=M.dirname(s);Q.existsSync(l)||Q.mkdirSync(l,{recursive:!0}),Q.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[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,i,o,s){let a=t.replace(/^\.\//,""),c=M.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=M.join(e,a,"src","main","ets"),g=i.map(Be=>n.resolveRelativePathForPatch(Be,d)),w=n.mergeStrings(l.modifiedFiles,g),v=n.mergePatchResources(l.rawFile,o),k=n.mergePatchResources(l.resFile,s),ce=M.dirname(c);Q.existsSync(ce)||Q.mkdirSync(ce,{recursive:!0}),Q.writeFileSync(c,JSON.stringify({resources:{resFile:k,rawFile:v},modifiedFiles:w}),"utf-8"),m(`[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 M.relative(M.normalize(t),M.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import CP from"fs";import{randomUUID as IP}from"crypto";import{execa as DP}from"execa";var Lr=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r){for(let a of t)if(!CP.existsSync(a)){let c=`Signed hqf file not found: ${a}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}if(Dt(e))return await this.executeQuickfix(e,t);let o=`/data/local/tmp/${IP()}`,s=[];try{for(let a=0;a<t.length;a++){let c=`${o}/${r}_${a}.hqf`;s.push(c),await this.pushHqf(e,t[a],o,c)}return await this.executeQuickfix(e,s)}catch(a){let c=`hqf install error: ${a.message}`;return console.error(`[Apply] ${c}`),{success:!1,message:c}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",o],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let r=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];await this.getApiVersion(e)>17&&r.push("-o");let o=await this.runHdc(r,!1);if(m(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async getApiVersion(e){try{let t=await this.runHdc(["-t",e,"shell","param","get","const.ohos.apiversion"],!1),r=parseInt(t.trim(),10);if(!isNaN(r))return console.log(`[InstallHqf] device API version: ${r}`),r}catch{}return 0}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;if(Os(e)&&e[2]==="shell")return Ms(e.slice(3),t);m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await DP(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var AP="6.1.1",_s=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Bt(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(AP);let t=Wi(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),i=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Nr.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 m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await df(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Lr(this.toolProvider).install(e.targetDeviceId,t,e.bundleName);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Vt(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 Vt(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 mf from"fs";import*as U from"path";var Fs=class n{static generate(e,t,r,i){let o=At(e,t),s=U.join(e,o),a=U.join(s,"build","config"),c=n.buildConfig(e,s,r,i);mf.mkdirSync(a,{recursive:!0}),mf.writeFileSync(U.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=U.dirname(i.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:o,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,"patch","default","changedFileList.json"),patchAbcPath:U.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import ff from"fs";import*as B from"path";var js=class n{static generate(e,t,r,i){let o=At(e,t),s=B.join(e,o),a=B.join(s,"build","config"),c=n.buildConfig(e,s,r,i);ff.mkdirSync(a,{recursive:!0}),ff.writeFileSync(B.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=B.dirname(i.nodePath)+B.sep,s=B.join(t,"build",r),a=B.join(s,"intermediates"),c=B.join(a,"loader_out",r),l=B.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:B.join(e,"build-profile.json5"),localPropertiesPath:B.join(e,"local.properties"),appResource:B.join(l,"ResourceTable.txt"),cachePath:B.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:B.join(a,"loader",r,"loader.json"),aceModuleJsonPath:B.join(l,"module.json"),aceSoPath:B.join(c,"nativeDependencies.txt"),aceModuleRoot:B.join(t,"src","main","ets"),aceModuleBuild:B.join(c,"ets"),aceProfilePath:B.join(l,"resources","base","profile"),aceSuperVisualPath:B.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:B.join(c,"ets"),changedFileList:B.join(a,"hotReload","changedFileList.json"),patchAbcPath:B.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import gf from"crypto";import et from"fs";import tt from"path";import hf from"os";import{io as TP}from"socket.io-client";var RP=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Or=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;et.mkdirSync(tt.dirname(i),{recursive:!0}),et.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
45
45
  `)?a:a+`
46
- `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),tt.writeFileSync(e,[...r,c+`
47
- `].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return nt.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 r=lP(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((i,o)=>{let s=setTimeout(()=>{o(new Error("Socket connect timeout (10s)"))},1e4);r.once("connect",()=>{clearTimeout(s),i()}),r.once("connect_error",a=>{clearTimeout(s),o(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=r,this.cachedDaemonPort=e.port,r}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let r=await this.getOrCreateSocket(e);return new Promise((i,o)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(r,()=>s,d=>s=d,o),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),r.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),i(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),r.off("BuildStatus",l),this.invalidateSocket(),o(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};r.on("disconnect",c.onDisconnect),r.on("Output",c.onOutput),r.on("BuildStatus",l),r.on("WatchLog",c.onWatchLog),r.on("WatchResult",c.onWatchResult),r.on("WatchCompileResult",c.onWatchCompileResult),r.on("WatchCompileData",c.onWatchCompileData),r.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,r,i){let o=w=>{t()||(r(!0),h(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),h=()=>{e.off("disconnect",o),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:o,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:h}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
46
+ `),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),et.writeFileSync(e,[...r,c+`
47
+ `].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return tt.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 r=TP(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((i,o)=>{let s=setTimeout(()=>{o(new Error("Socket connect timeout (10s)"))},1e4);r.once("connect",()=>{clearTimeout(s),i()}),r.once("connect_error",a=>{clearTimeout(s),o(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=r,this.cachedDaemonPort=e.port,r}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let r=await this.getOrCreateSocket(e);return new Promise((i,o)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(r,()=>s,d=>s=d,o),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),r.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),i(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),r.off("BuildStatus",l),this.invalidateSocket(),o(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};r.on("disconnect",c.onDisconnect),r.on("Output",c.onOutput),r.on("BuildStatus",l),r.on("WatchLog",c.onWatchLog),r.on("WatchResult",c.onWatchResult),r.on("WatchCompileResult",c.onWatchCompileResult),r.on("WatchCompileData",c.onWatchCompileData),r.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,r,i){let o=w=>{t()||(r(!0),g(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",o),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:o,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
48
48
  `)?"":`
49
- `))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!tt.existsSync(e))return null;try{let t=tt.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=nt.join(t,"fd"),i=nt.join(t,"ac"),o=nt.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(dP)]),c=this.readSingleFile(i),l=Xm.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),h=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(h,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Xm.createDecipheriv("aes-128-gcm",e,o);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 i=tt.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return tt.readFileSync(nt.join(r,i[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 i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||nt.join(Zm.homedir(),".hvigor");return nt.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||nt.join(Zm.homedir(),".hvigor");return nt.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import tf from"fs";import*as Bt from"path";import{green as js,yellow as $l}from"colorette";import Jn from"fs";import*as Kn from"path";import uP from"json5";var pP=2e6,mP=1e6,fP="hotreload",Ms=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Kn.resolve(e,t),s=Kn.join(o,"patch.json"),a;return Jn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:pP,versionCode:i.versionCode},module:{name:r,type:fP}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Kn.join(e,"AppScope","app.json5");if(!Jn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Jn.readFileSync(t,"utf-8"),i=uP.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??mP;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Jn.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=Kn.dirname(e);Jn.existsSync(r)||Jn.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Jn.writeFileSync(e,i,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${i}`)}};import ye from"fs";import*as G from"path";import Qm from"crypto";import hP from"json5";import{execa as ef}from"execa";var _s=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}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=G.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=G.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(G.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(G.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=Qm.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=Qm.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=ye.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=G.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(ye.statSync(e).isDirectory()){let i=ye.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(ye.readFileSync(G.join(e,i[0])))}return new Int8Array(ye.readFileSync(e))}},Fs=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${G.dirname(e.javaPath)}${G.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=G.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 i=G.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=Tt(this.projectRoot,e),i=G.join(this.projectRoot,r,"build",t,"outputs","default");return ye.existsSync(i)||ye.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:G.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:G.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=G.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await ef(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 i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath;m(`[GenSignHqf] Signing: ${o} ${i.join(" ")}`);try{let s=Date.now(),a=await ef(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.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(s){return this.signFailResult(e,`hqf signing failed: ${s.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=_s.decryptPwd(r,t.storePassword,"storePassword"),o=_s.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=G.resolve(e.storeFile,".."),r=G.join(t,"material");return ye.existsSync(r)?t:null}readSigningConfig(e){let t=G.join(this.projectRoot,"build-profile.json5");if(!ye.existsSync(t))return null;try{let r=ye.readFileSync(t,"utf-8"),i=hP.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[G.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),G.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=[G.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),G.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(ye.existsSync(r))return r;return null}};async function nf(n){let e=Date.now(),t=Tt(n.projectPath,n.moduleName),r=gP(n);console.log($l("[HotReload] Ensure the project source is trusted before proceeding."));let i=yP(n),o=Hi(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),wP(n,o),vP(n,t),await SP(n,i);let s=Bt.join(n.projectPath,t,"patch.json"),a=await EP(n,t,s);return await PP(n,a),console.log(js("[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 gP(n){if(Bt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Bt.join(n.projectPath,".hvigor",n.applyFileName)}function yP(n){let{projectPath:e,toolProvider:t}=n,r=new Rr(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 wP(n,e){let t=Ar.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(js(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn($l(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function vP(n,e){let t=Ms.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(js(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function SP(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=bP(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
49
+ `))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!et.existsSync(e))return null;try{let t=et.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=tt.join(t,"fd"),i=tt.join(t,"ac"),o=tt.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(RP)]),c=this.readSingleFile(i),l=gf.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=gf.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=et.readdirSync(e).map(r=>tt.join(e,r)).filter(r=>et.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let i=et.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return et.readFileSync(tt.join(r,i[0]))})}readSingleFile(e){let t=et.readdirSync(e).map(r=>tt.join(e,r)).filter(r=>et.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return et.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||tt.join(hf.homedir(),".hvigor");return tt.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||tt.join(hf.homedir(),".hvigor");return tt.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import vf from"fs";import*as Gt from"path";import{green as Bs,yellow as zl}from"colorette";import er from"fs";import*as tr from"path";import kP from"json5";var xP=2e6,NP=1e6,LP="hotreload",$s=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=tr.resolve(e,t),s=tr.join(o,"patch.json"),a;return er.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:xP,versionCode:i.versionCode},module:{name:r,type:LP}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=tr.join(e,"AppScope","app.json5");if(!er.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=er.readFileSync(t,"utf-8"),i=kP.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??NP;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=er.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=tr.dirname(e);er.existsSync(r)||er.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);er.writeFileSync(e,i,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${i}`)}};import ye from"fs";import*as G from"path";import yf from"crypto";import OP from"json5";import{execa as wf}from"execa";var Hs=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}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=G.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=G.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(G.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(G.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=yf.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=yf.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=ye.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=G.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(ye.statSync(e).isDirectory()){let i=ye.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(ye.readFileSync(G.join(e,i[0])))}return new Int8Array(ye.readFileSync(e))}},Us=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${G.dirname(e.javaPath)}${G.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=G.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 i=G.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=At(this.projectRoot,e),i=G.join(this.projectRoot,r,"build",t,"outputs","default");return ye.existsSync(i)||ye.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:G.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:G.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=G.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await wf(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 i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath;m(`[GenSignHqf] Signing: ${o} ${i.join(" ")}`);try{let s=Date.now(),a=await wf(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.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(s){return this.signFailResult(e,`hqf signing failed: ${s.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=Hs.decryptPwd(r,t.storePassword,"storePassword"),o=Hs.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=G.resolve(e.storeFile,".."),r=G.join(t,"material");return ye.existsSync(r)?t:null}readSigningConfig(e){let t=G.join(this.projectRoot,"build-profile.json5");if(!ye.existsSync(t))return null;try{let r=ye.readFileSync(t,"utf-8"),i=OP.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[G.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),G.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=[G.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),G.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(ye.existsSync(r))return r;return null}};async function Sf(n){let e=Date.now(),t=At(n.projectPath,n.moduleName),r=MP(n);console.log(zl("[HotReload] Ensure the project source is trusted before proceeding."));let i=_P(n),o=Wi(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),FP(n,o),jP(n,t),await $P(n,i);let s=Gt.join(n.projectPath,t,"patch.json"),a=await UP(n,t,s);return await BP(n,a),console.log(Bs("[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 MP(n){if(Gt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Gt.join(n.projectPath,".hvigor",n.applyFileName)}function _P(n){let{projectPath:e,toolProvider:t}=n,r=new Or(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 FP(n,e){let t=Nr.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(Bs(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(zl(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function jP(n,e){let t=$s.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Bs(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function $P(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=HP(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
50
50
  --- compile output (from watch session) ---
51
- ${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function bP(n){try{return tf.existsSync(n)?tf.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
52
- `):""}catch{return""}}async function EP(n,e,t){let r=Bt.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[Bt.join(r,"hotReload","patchAbcPath"),Bt.join(r,"patch","default")],o=Date.now(),s=new Fs(n.toolProvider,n.projectPath),a=n.targetDeviceId.includes("127.0.0.1")||n.targetDeviceId.includes("localhost"),c=null;for(let l of i){let d=await s.generateAndSign(n.moduleName,l,t,n.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-o}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function PP(n,e){let t=Date.now(),i=await new Tr(n.toolProvider).install(n.targetDeviceId,e,n.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!i.success)throw new Error(`hqf install failed: ${i.message}`)}function Hl(n,e){if(!n||n.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function rf(n,e,t){let r=Bt.join(n.rootDir,".hvigor",t),i;try{i=Hi(r,n.rootDir)}catch{return}let o=new Set;for(let s of i){let a=n.findOwningModule(s);if(!a||a===e)continue;let c=n.getModuleType(a);(c==="feature"||c==="shared")&&o.add(`${a} (${c})`)}o.size>0&&console.warn($l(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...o].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function of(n,e,t,r,i){let o=new Set,s=n.collectNonHarDependentModuleList(e);for(let a of s)o.add(n.findArtifactPath(a,t,r,i));return o.add(n.findArtifactPath(e,t,r,i)),[...o]}async function sf(n,e){await new Ne(n,e.rootDir).stopDaemon(),console.log(js("Hvigor daemon stopped."))}import{execa as Wl}from"execa";import*as RP from"readline/promises";import{stdin as mB,stdout as fB}from"process";import{green as Bi,red as Us,yellow as kP}from"colorette";import Hs from"fs";import*as Wi from"path";import xP from"json5";var CP=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],Ui={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function IP(){return[]}async function Ul(){let n=await IP();return n.length>0?n:CP}function $s(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var DP={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function AP(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let i=new Array(r+1),o=new Array(r+1);for(let s=0;s<=r;s++)i[s]=s;for(let s=1;s<=t;s++){o[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;o[a]=Math.min(i[a]+1,o[a-1]+1,i[a-1]+c)}for(let a=0;a<=r;a++)i[a]=o[a]}return i[r]}function TP(n,e){let t=n.map(o=>({spec:o,dist:AP(e,$s(o.productName))})),r=t.reduce((o,s)=>Math.min(o,s.dist),1/0);if(r>2)return;let i=t.filter(o=>o.dist===r);return i.length===1?{spec:i[0].spec,matchedName:i[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:i.map(o=>o.spec.productName)}}function Bl(n,e){if(/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u30ff\uac00-\ud7af]/.test(e))return{matchType:"none"};let t=$s(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>$s(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let i=DP[t];if(i){let a=n.find(c=>c.productName===i);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let o=n.filter(a=>{let c=$s(a.productName);return c.includes(t)||t.includes(c)});if(o.length===1)return{spec:o[0],matchedName:o[0].productName,matchType:"substring"};if(o.length>1)return{matchType:"none",ambiguous:o.map(a=>a.productName)};let s=TP(n,t);return s||{matchType:"none"}}async function NP(n){for(let e of n){let{stdout:t}=await Wl("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function LP(){try{let n=tl();if(n==="win32")return NP(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await Wl("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Wl("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function OP(n,e){if(!b()){if(await LP()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
53
- Please start DevEco Studio manually, then retry.`)}if(e&&At(e)){if(!n)throw new Error("Internal error: hdcAdapter is required for IDE detection on HarmonyOS.");if(await n.isDevEcoStudioRunningOnLocal()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
51
+ ${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function HP(n){try{return vf.existsSync(n)?vf.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
52
+ `):""}catch{return""}}async function UP(n,e,t){let r=Gt.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[Gt.join(r,"hotReload","patchAbcPath"),Gt.join(r,"patch","default")],o=Date.now(),s=new Us(n.toolProvider,n.projectPath),a=n.targetDeviceId.includes("127.0.0.1")||n.targetDeviceId.includes("localhost"),c=null;for(let l of i){let d=await s.generateAndSign(n.moduleName,l,t,n.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-o}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function BP(n,e){let t=Date.now(),i=await new Lr(n.toolProvider).install(n.targetDeviceId,e,n.bundleName);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!i.success)throw new Error(`hqf install failed: ${i.message}`)}function ql(n,e){if(!n||n.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function bf(n,e,t){let r=Gt.join(n.rootDir,".hvigor",t),i;try{i=Wi(r,n.rootDir)}catch{return}let o=new Set;for(let s of i){let a=n.findOwningModule(s);if(!a||a===e)continue;let c=n.getModuleType(a);(c==="feature"||c==="shared")&&o.add(`${a} (${c})`)}o.size>0&&console.warn(zl(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...o].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function Ef(n,e,t,r,i){let o=new Set,s=n.collectNonHarDependentModuleList(e);for(let a of s)o.add(n.findArtifactPath(a,t,r,i));return o.add(n.findArtifactPath(e,t,r,i)),[...o]}async function Pf(n,e){await new xe(n,e.rootDir).stopDaemon(),console.log(Bs("Hvigor daemon stopped."))}import{execa as Kl}from"execa";import*as YP from"readline/promises";import{stdin as MB,stdout as _B}from"process";import{green as Gi,red as Gs,yellow as JP}from"colorette";import Vs from"fs";import*as zi from"path";import KP from"json5";var WP=[{productIndex:0,productName:"Pura 90 Pro",productType:"phone",subProductType:"phone"},{productIndex:1,productName:"MatePad 11.5'S",productType:"tablet",subProductType:"tablet"},{productIndex:2,productName:"Mate X7",productType:"phone",subProductType:"foldable"},{productIndex:3,productName:"Pura X",productType:"phone",subProductType:"widefold"},{productIndex:4,productName:"Mate XT",productType:"phone",subProductType:"triplefold"}],Vi={productIndex:0,productName:"phone",productType:"phone",subProductType:"phone"};async function VP(){return[]}async function Yl(){let n=await VP();return n.length>0?n:WP}function Ws(n){return n.toLowerCase().replace(/[\s\W]+/g,"")}var GP={phone:"Pura 90 Pro",tablet:"MatePad 11.5'S",pad:"MatePad 11.5'S",fold:"Mate X7",foldable:"Mate X7",widefold:"Pura X",wide:"Pura X",triplefold:"Mate XT",triple:"Mate XT",pura90:"Pura 90 Pro",pura90pro:"Pura 90 Pro",matepad:"MatePad 11.5'S",matex7:"Mate X7",purax:"Pura X",matext:"Mate XT"};function zP(n,e){let t=n.length,r=e.length;if(t===0)return r;if(r===0)return t;let i=new Array(r+1),o=new Array(r+1);for(let s=0;s<=r;s++)i[s]=s;for(let s=1;s<=t;s++){o[0]=s;for(let a=1;a<=r;a++){let c=n[s-1]===e[a-1]?0:1;o[a]=Math.min(i[a]+1,o[a-1]+1,i[a-1]+c)}for(let a=0;a<=r;a++)i[a]=o[a]}return i[r]}function qP(n,e){let t=n.map(o=>({spec:o,dist:zP(e,Ws(o.productName))})),r=t.reduce((o,s)=>Math.min(o,s.dist),1/0);if(r>2)return;let i=t.filter(o=>o.dist===r);return i.length===1?{spec:i[0].spec,matchedName:i[0].spec.productName,fuzzy:!0,matchType:"fuzzy"}:{matchType:"none",ambiguous:i.map(o=>o.spec.productName)}}function Jl(n,e){if(/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u30ff\uac00-\ud7af]/.test(e))return{matchType:"none"};let t=Ws(e);if(t.length===0)return{matchType:"none"};let r=n.find(a=>Ws(a.productName)===t);if(r)return{spec:r,matchedName:r.productName,matchType:"exact"};let i=GP[t];if(i){let a=n.find(c=>c.productName===i);if(a)return{spec:a,matchedName:a.productName,matchType:"alias"}}let o=n.filter(a=>{let c=Ws(a.productName);return c.includes(t)||t.includes(c)});if(o.length===1)return{spec:o[0],matchedName:o[0].productName,matchType:"substring"};if(o.length>1)return{matchType:"none",ambiguous:o.map(a=>a.productName)};let s=qP(n,t);return s||{matchType:"none"}}async function XP(n){for(let e of n){let{stdout:t}=await Kl("tasklist",["/FI",`IMAGENAME eq ${e}`,"/FO","CSV","/NH"],{reject:!1});if(t.toLowerCase().includes(e.toLowerCase()))return!0}return!1}async function ZP(){try{let n=cl();if(n==="win32")return XP(["devecostudio64.exe","devecostudio.exe"]);if(n==="darwin"){let{stdout:e}=await Kl("pgrep",["-x","DevEco Studio"],{reject:!1});return e.trim().length>0}if(n==="openharmony"||n==="linux"){let{stdout:e}=await Kl("pgrep",["-f","com.huawei.devecostudio"],{reject:!1});return e.trim().length>0}}catch{}return!1}async function QP(n,e){if(!b()){if(await ZP()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
53
+ Please start DevEco Studio manually, then retry.`)}if(e&&Dt(e)){if(!n)throw new Error("Internal error: hdcAdapter is required for IDE detection on HarmonyOS.");if(await n.isDevEcoStudioRunningOnLocal()){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
54
54
  Please start DevEco Studio manually, then retry.`)}if(!n||!e)throw new Error("Internal error: hdcAdapter and targetDeviceId are required for IDE detection on HarmonyOS.");if(await n.isDevEcoStudioRunningViaHdc(e)){console.log("DevEco Studio is already running.");return}throw new Error(`DevEco Studio is not running. The previewer requires DevEco Studio to be running.
55
- Please start DevEco Studio manually, then retry.`)}async function MP(n,e){let t=await e.listDevices();if(t.length===0)return!1;let r=await e.listDevicesWithName();for(let i of n){if(t.some(s=>s.serial===i))return!0;let o=i.toLowerCase();if(r.some(s=>s.name.toLowerCase()===o))return!0}return!1}async function af(n,e){if(!n)return!1;let t=n.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0||e&&await MP(t,e))return!1;let r=await Ul(),i=r.length>0?r:[Ui];return t.every(o=>Bl(i,o).spec!==void 0)}function _P(n,e){if(!n)return[e[0]||Ui];let t=n.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0)return[e[0]||Ui];let r=[],i=[];for(let o of t){let s=Bl(e,o);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn(kP(` [fuzzy] "${o}" \u2192 ${s.matchedName}`)):(s.matchType==="alias"||s.matchType==="substring")&&console.log(` [${s.matchType}] "${o}" \u2192 ${s.matchedName}`);else{if(s.ambiguous&&s.ambiguous.length>0)throw new Error(`Ambiguous device name "${o}". Candidates:
55
+ Please start DevEco Studio manually, then retry.`)}async function eC(n,e){let t=await e.listDevices();if(t.length===0)return!1;let r=await e.listDevicesWithName();for(let i of n){if(t.some(s=>s.serial===i))return!0;let o=i.toLowerCase();if(r.some(s=>s.name.toLowerCase()===o))return!0}return!1}async function Cf(n,e){if(!n)return!1;let t=n.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0||e&&await eC(t,e))return!1;let r=await Yl(),i=r.length>0?r:[Vi];return t.every(o=>Jl(i,o).spec!==void 0)}function tC(n,e){if(!n)return[e[0]||Vi];let t=n.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0)return[e[0]||Vi];let r=[],i=[];for(let o of t){let s=Jl(e,o);if(s.spec)r.push(s.spec),s.matchType==="fuzzy"?console.warn(JP(` [fuzzy] "${o}" \u2192 ${s.matchedName}`)):(s.matchType==="alias"||s.matchType==="substring")&&console.log(` [${s.matchType}] "${o}" \u2192 ${s.matchedName}`);else{if(s.ambiguous&&s.ambiguous.length>0)throw new Error(`Ambiguous device name "${o}". Candidates:
56
56
  `+s.ambiguous.map(a=>` - ${a}`).join(`
57
57
  `)+`
58
58
  Please specify a more precise name.`);i.push(o)}}if(i.length>0){let o=e.map(s=>s.productName).join(", ");throw new Error(`Device type(s) not found: ${i.join(", ")}
59
- Available: ${o}`)}return FP(r)}function FP(n){let e=new Set,t=[];for(let r of n)e.has(r.productName)||(e.add(r.productName),t.push(r));return t}async function jP(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
60
- `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function $P(n){if(!Hs.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=Hs.readFileSync(n,"utf8"),t=xP.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},Hs.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${Wi.basename(n)}`),()=>{Hs.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${Wi.basename(n)}`)})}async function HP(n){let{options:e,project:t,toolProvider:r,hdcAdapter:i,moduleName:o,isMulti:s,targetDeviceId:a}=n,c=Wi.join(t.rootDir,"AppScope","app.json5"),l=s?$P(c):()=>{},d=s?"[multi-preview]":"[preview]";try{let h=e.product||"default",w=e.buildMode||"debug",v="default";if(s||!e.skipBuild){console.log(s?`
59
+ Available: ${o}`)}return nC(r)}function nC(n){let e=new Set,t=[];for(let r of n)e.has(r.productName)||(e.add(r.productName),t.push(r));return t}async function rC(n,e){let t=await n.listDevices();if(t.length===0)throw new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
60
+ `))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function iC(n){if(!Vs.existsSync(n))throw new Error(`app.json5 not found at ${n}`);let e=Vs.readFileSync(n,"utf8"),t=KP.parse(e);return t.app?.multiAppMode?(console.log("[multi-preview] app.json5 already has multiAppMode, skipping injection."),()=>{}):(t.app||(t.app={}),t.app.multiAppMode={multiAppModeType:"appClone",maxCount:5},Vs.writeFileSync(n,JSON.stringify(t,null,2),"utf8"),console.log(`[multi-preview] Injected multiAppMode into ${zi.basename(n)}`),()=>{Vs.writeFileSync(n,e,"utf8"),console.log(`[multi-preview] Restored original ${zi.basename(n)}`)})}async function oC(n){let{options:e,project:t,toolProvider:r,hdcAdapter:i,moduleName:o,isMulti:s,targetDeviceId:a}=n,c=zi.join(t.rootDir,"AppScope","app.json5"),l=s?iC(c):()=>{},d=s?"[multi-preview]":"[preview]";try{let g=e.product||"default",w=e.buildMode||"debug",v="default";if(s||!e.skipBuild){console.log(s?`
61
61
  ${d} Building with multiAppMode (appClone) for multi-instance preview...`:`
62
- ${d} Building and installing hap for preview...`);let ce=new ln(r,t.rootDir),We=new Ne(r,t.rootDir),lt=t.collectNonHarDependentModuleList(o).map(Xc=>`${Xc}@${v}`),Ap=_i(t,lt),Kc={type:"modules",modulesToBuild:lt,moduleTasks:Ap};await $t(t.rootDir,async()=>{await Fi(ce,We,h,w,Kc,t.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(Bi(`${d} Build completed.`))}else console.log(`${d} Skipping build (--skip-build), installing existing hap...`);let k=t.findArtifactPath(o,v,!1,h);console.log(`${d} Installing hap to ${a}...`),await i.installApp(a,[k]),console.log(Bi(`${d} Installed hap.`))}finally{l()}}function UP(n){console.log(`
63
- Launching DevEco Studio previewer on ${n.targetDeviceId}...`),console.log(` bundleName : ${n.bundleName}`),console.log(` abilityName : ${n.mainAbility}`),console.log(` moduleName : ${n.moduleJsonName}`),console.log(` instanceId : ${n.instanceId}`),console.log(` mode : ${n.isMulti?"multi":"single"}`),console.log(` previewers : ${n.targets.map(e=>e.productName).join(", ")}`)}async function BP(n){let{hdcAdapter:e,targets:t,isMulti:r,targetDeviceId:i,bundleName:o,mainAbility:s,moduleJsonName:a,instanceId:c}=n,l=[];for(let d=0;d<t.length;d++){let h=t[d],w=r?d:-1;console.log(`
64
- [${d+1}/${t.length}] Launching ${h.productName} (${h.productType}/${h.subProductType})...`);try{let v=await e.launchPreview(i,o,s,h.productName,h.productType,a,h.subProductType,c,w),k=/start ability successfully/i.test(v);l.push({name:h.productName,success:k,output:v}),k?console.log(Bi(` \u2713 ${h.productName}: ${v.trim()}`)):console.error(Us(` \u2717 ${h.productName}: ${v.trim()}`))}catch(v){let k=v.message;l.push({name:h.productName,success:!1,output:k}),console.error(Us(` \u2717 ${h.productName}: ${k}`))}}return l}function WP(n){console.log(`
65
- `+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${Bi(String(e))} succeeded, ${t>0?Us(String(t)):"0"} failed.`);for(let r of n){let i=r.success?Bi("\u2713"):Us("\u2717");console.log(` ${i} ${r.name}`)}return t===0}async function cf(n,e,t,r,i,o){let s=await Ul(),a=s.length>0?s:[Ui],c=_P(n.device,a),l=c.length>1,d;b()&&await $i()?(d=Ir,console.log("Using local machine for preview (bm/aa directly callable).")):d=await jP(i,void 0);let h={options:n,project:e,toolProvider:t,hdcAdapter:r,moduleName:o,targetDeviceId:d,isMulti:l,targets:c,bundleName:e.getBundleName(),mainAbility:e.getMainAbility(o,n.ability),moduleJsonName:e.getModuleName(o),instanceId:process.pid};await HP(h),await OP(r,d),UP(h);let w=await BP(h);return WP(w)}function Vl(n){let e=n.indexOf("@"),t=e!==-1?n.substring(0,e):n,r=e!==-1?n.substring(e+1):"default";return{moduleName:t,targetName:r}}async function zP(n){if(n)return n.serial;if(await $i())return Ir;throw new Error(`--device local: no wireless debugging connection and bm/aa not available.
66
- Enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`)}function qP(n){throw n.mode?new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."):new Error("No active devices found. To run on the local device, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging")}async function YP(n){let e=await n.listDevicesWithName();throw new T("Multiple targets found. Specify a target using `--device <Name>`, `--device <ID>`, or `--device local`.\nAvailable targets:\n"+e.filter(t=>!t.serial.includes("127.0.0.1")).map(t=>` - ${t.name} (${t.serial})`).join(`
62
+ ${d} Building and installing hap for preview...`);let ce=new mn(r,t.rootDir),Be=new xe(r,t.rootDir),at=t.collectNonHarDependentModuleList(o).map(il=>`${il}@${v}`),Vp=$i(t,at),rl={type:"modules",modulesToBuild:at,moduleTasks:Vp};await Bt(t.rootDir,async()=>{await Hi(ce,Be,g,w,rl,t.rootDir)},()=>console.log("Another build is already running. Waiting...")),console.log(Gi(`${d} Build completed.`))}else console.log(`${d} Skipping build (--skip-build), installing existing hap...`);let k=t.findArtifactPath(o,v,!1,g);console.log(`${d} Installing hap to ${a}...`),await i.installApp(a,[k]),console.log(Gi(`${d} Installed hap.`))}finally{l()}}function sC(n){console.log(`
63
+ Launching DevEco Studio previewer on ${n.targetDeviceId}...`),console.log(` bundleName : ${n.bundleName}`),console.log(` abilityName : ${n.mainAbility}`),console.log(` moduleName : ${n.moduleJsonName}`),console.log(` instanceId : ${n.instanceId}`),console.log(` mode : ${n.isMulti?"multi":"single"}`),console.log(` previewers : ${n.targets.map(e=>e.productName).join(", ")}`)}async function aC(n){let{hdcAdapter:e,targets:t,isMulti:r,targetDeviceId:i,bundleName:o,mainAbility:s,moduleJsonName:a,instanceId:c}=n,l=[];for(let d=0;d<t.length;d++){let g=t[d],w=r?d:-1;console.log(`
64
+ [${d+1}/${t.length}] Launching ${g.productName} (${g.productType}/${g.subProductType})...`);try{let v=await e.launchPreview(i,o,s,g.productName,g.productType,a,g.subProductType,c,w),k=/start ability successfully/i.test(v);l.push({name:g.productName,success:k,output:v}),k?console.log(Gi(` \u2713 ${g.productName}: ${v.trim()}`)):console.error(Gs(` \u2717 ${g.productName}: ${v.trim()}`))}catch(v){let k=v.message;l.push({name:g.productName,success:!1,output:k}),console.error(Gs(` \u2717 ${g.productName}: ${k}`))}}return l}function cC(n){console.log(`
65
+ `+"\u2500".repeat(50));let e=n.filter(r=>r.success).length,t=n.length-e;console.log(`Previewer launch summary: ${Gi(String(e))} succeeded, ${t>0?Gs(String(t)):"0"} failed.`);for(let r of n){let i=r.success?Gi("\u2713"):Gs("\u2717");console.log(` ${i} ${r.name}`)}return t===0}async function If(n,e,t,r,i,o){let s=await Yl(),a=s.length>0?s:[Vi],c=tC(n.device,a),l=c.length>1,d;b()&&await Bi()?(d=kr,console.log("Using local machine for preview (bm/aa directly callable).")):d=await rC(i,void 0);let g={options:n,project:e,toolProvider:t,hdcAdapter:r,moduleName:o,targetDeviceId:d,isMulti:l,targets:c,bundleName:e.getBundleName(),mainAbility:e.getMainAbility(o,n.ability),moduleJsonName:e.getModuleName(o),instanceId:process.pid};await oC(g),await QP(r,d),sC(g);let w=await aC(g);return cC(w)}function Xl(n){let e=n.indexOf("@"),t=e!==-1?n.substring(0,e):n,r=e!==-1?n.substring(e+1):"default";return{moduleName:t,targetName:r}}async function uC(n){if(n)return n.serial;if(await Bi())return kr;throw new Error(`--device local: no wireless debugging connection and bm/aa not available.
66
+ Enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`)}function pC(n){throw n.mode?new Error(b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."):new Error("No active devices found. To run on the local device, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging")}async function mC(n){let e=await n.listDevicesWithName();throw new T("Multiple targets found. Specify a target using `--device <Name>`, `--device <ID>`, or `--device local`.\nAvailable targets:\n"+e.filter(t=>!t.serial.includes("127.0.0.1")).map(t=>` - ${t.name} (${t.serial})`).join(`
67
67
  `)+`
68
- - local machine (--device local)`,"Multiple targets found.")}async function JP(n){let e=await n.listDevicesWithName();throw new T("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+e.map(t=>` - ${t.name} (${t.serial})`).join(`
69
- `),"Multiple devices found.")}async function Vs(n,e){let t=await n.ensureWirelessSelfConnection(),r=await n.listDevices(),i=r.find(c=>c.serial.includes("127.0.0.1")),o=r.filter(c=>!c.serial.includes("127.0.0.1"));if(b()&&e&&At(e))return zP(i);let s=b()&&!e&&await $i();if(r.length===0){if(s)return console.log("Using local machine (bm/aa directly callable)."),Ir;qP(t)}if(!e&&(i||s)&&o.length>0&&await YP(n),s&&o.length===0)return console.log(`Auto-selected device: local machine (${i.serial})`),i.serial;!e&&r.length>1&&await JP(n);let a=await n.getDeviceInfo(r,e);if(!a)throw new Error("No active devices found.");if(!e){let c=await n.getDeviceName(a.serial);console.log(`Auto-selected device: ${c} (${a.serial})`)}return a.serial}function Gl(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new T(`Specify module(s) using --module <name> [<name>...].
68
+ - local machine (--device local)`,"Multiple targets found.")}async function fC(n){let e=await n.listDevicesWithName();throw new T("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+e.map(t=>` - ${t.name} (${t.serial})`).join(`
69
+ `),"Multiple devices found.")}async function Ys(n,e){let t=await n.ensureWirelessSelfConnection(),r=await n.listDevices(),i=r.find(c=>c.serial.includes("127.0.0.1")),o=r.filter(c=>!c.serial.includes("127.0.0.1"));if(b()&&e&&Dt(e))return uC(i);let s=b()&&!e&&await Bi();if(r.length===0){if(s)return console.log("Using local machine (bm/aa directly callable)."),kr;pC(t)}if(!e&&(i||s)&&o.length>0&&await mC(n),s&&o.length===0)return console.log(`Auto-selected device: local machine (${i.serial})`),i.serial;!e&&r.length>1&&await fC(n);let a=await n.getDeviceInfo(r,e);if(!a)throw new Error("No active devices found.");if(!e){let c=await n.getDeviceName(a.serial);console.log(`Auto-selected device: ${c} (${a.serial})`)}return a.serial}function Zl(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new T(`Specify module(s) using --module <name> [<name>...].
70
70
  Available runnable modules:
71
71
  `+t.map(r=>` - ${r.name}`).join(`
72
- `),"Specify module error.")}function lf(n,e,t){if(t)return t;let r=e.find(({moduleName:o})=>n.getModuleType(o)==="entry");if(r)return n.getMainAbility(r.moduleName);let i=e.find(({moduleName:o})=>n.getModuleType(o)==="feature");if(i)return n.getMainAbility(i.moduleName)}async function df(n,e,t,r,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
73
- Installing artifacts to ${At(e)?"local machine":"device "+e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(Vi(`
72
+ `),"Specify module error.")}function Df(n,e,t){if(t)return t;let r=e.find(({moduleName:o})=>n.getModuleType(o)==="entry");if(r)return n.getMainAbility(r.moduleName);let i=e.find(({moduleName:o})=>n.getModuleType(o)==="feature");if(i)return n.getMainAbility(i.moduleName)}async function Af(n,e,t,r,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
73
+ Installing artifacts to ${Dt(e)?"local machine":"device "+e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(qi(`
74
74
  Application '${t}': ${s}`))}else console.log(`
75
- Application '${t}' installed successfully (no ability to launch).`)}function KP(n){let e={event:D.CommandExecuted,args:["run",...n.module?["--module"]:[],...n.device?["--device"]:[],...n.product?["--product"]:[],...n.buildMode?["--build-mode"]:[],...n.ability?["--ability"]:[],...n.uninstall?["--uninstall"]:[],...n.skipBuild?["--skip-build"]:[],...n.apply?["--apply"]:[],...n.hotreload?["--hotreload"]:[],...n.hotreloadApply?["--hotreload-apply"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.module&&(e.module_count=n.module.length),e}var zl=new VP("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/");b()||zl.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.");zl.action(async n=>{let e=KP(n),t=Date.now(),r=!0,i=null;try{let o=await eC(n,e);o&&(o.ohpmMemoryMb&&(e.ohpm_install_memory=o.ohpmMemoryMb),o.syncMemoryMb&&(e.hvigor_sync_memory=o.syncMemoryMb),o.buildMemoryMb&&(e.hvigor_build_memory=o.buildMemoryMb))}catch(o){r=!1,i=W(o),console.error(GP(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}});async function XP(n,e,t,r,i){let o=new ln(e,n.rootDir),s=new Ne(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:v,targetName:k}of t)for(let ce of n.collectNonHarDependentModuleList(v))a.add(`${ce}@${k}`),c.add(ce);let l=[...a],d=_i(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let v of c)Ls.generate(n.rootDir,v,r,e);let w=await $t(n.rootDir,()=>Fi(o,s,r,i,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
76
- `+Vi("Build completed successfully.")),w}async function ZP(n,e,t,r,i){let o=new Ut(t),s=ae.from(t),a=r[0]?.moduleName||i[0];await cf(n,e,t,o,s,a)}function QP(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new T(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}}async function eC(n,e){let t=K.discover(process.cwd());console.warn(Bs("Ensure the project source is trusted before proceeding."));let r=await A.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await nC(n,t,r);return}if(n.hotreload){await tC(n,t,r);return}if(n.apply){await iC(n,t,r);return}return uf(n,t,r)}async function tC(n,e,t){if(n.hotreload==="stop"){await sf(t,e);return}let i=Gl(e,n.module).map(Vl),{moduleName:o,targetName:s}=i[0];Hl(n.module,o);let a=new Ut(t),c=ae.from(t),l=await Vs(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(),v=lf(e,i,n.ability);Os.generate(e.rootDir,o,h,t);let k=new Ne(t,e.rootDir);console.log(Vi("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await k.ensureDaemonRunning();let ce=[`${o}@${h}`];for(let lt of e.collectNonHarDependentModuleList(o))ce.includes(`${lt}@${h}`)||ce.push(`${lt}@${h}`);console.log(Vi("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let We=new Rr(e.rootDir,t);await We.startWatchSession({moduleSpecs:ce,productName:h});let ct=of(e,o,s,d,h);await df(a,l,w,ct,v,!!n.uninstall),console.log(Vi("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.")),We.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function nC(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let i=Gl(e,n.module),{moduleName:o}=Vl(i[0]);Hl(n.module,o);let s=ae.from(t),a=await Vs(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();rf(e,o,r);let d=[`${o}@${c}`],h=await nf({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function rC(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function uf(n,e,t){let r=Gl(e,n.module),i=r.map(Vl),o=ae.from(t);if(await af(n.device,o)){await ZP(n,e,t,i,r);return}QP(e,i);let s=new Ut(t),a=await Vs(o,n.device),c=!b()&&(a.includes("127.0.0.1")||a.includes("localhost")),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",h;n.skipBuild||(h=await XP(e,t,i,l,d));let w=rC(e,i,c,l),v=e.getBundleName(),k=lf(e,i,n.ability);return await df(s,a,v,w,k,!!n.uninstall),h}async function iC(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Ws.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Ws.join(e.rootDir,".hvigor",r),o=ae.from(t),s=await Vs(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new Ns(t,e.rootDir);try{await h.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(Bs("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(w){console.warn(Bs(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(Bs("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await uf(n,e,t)}var pf=zl;import{Command as oC}from"commander";import{green as mf,red as ff,cyan as ql}from"colorette";import{execa as hf}from"execa";function sC(){return"daily"}function aC(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-openharmony-arm64"}function cC(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.12-Test.1"}var lC={event:D.CommandExecuted,args:["update"]};async function Yl(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(lC,r).catch(()=>{})}async function dC(n,e,t){let r=W(t);console.error(ff(`Failed to update ${n}`));let i=t instanceof Error?t.message:"";i&&console.error(ff(i)),await Yl(e,!1,r),process.exit(1)}var uC=new oC("update").description("Update deveco-cli to latest").action(async()=>{let n=aC(),e=cC(),t=sC(),r=Date.now();console.log(ql("Checking for updates..."));try{let{stdout:i}=await hf("npm",["view",n,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(mf(`
77
- ${n} is already up to date (v${e}, tag: ${t})`)),await Yl(r,!0,null);return}console.log(ql(`
78
- New version found: ${o} (current: ${e})`)),console.log(ql(`Updating ${n}...`)),await hf("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
79
- `+mf(`${n} updated successfully to version ${o}.`)),await Yl(r,!0,null)}catch(i){await dC(n,r,i)}}),gf=uC;import{Command as HC}from"commander";import{execa as zs}from"execa";function Ce(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as pC}from"child_process";var mC=2500;function fC(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function hC(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,mC);n.once("error",d=>c(d.message)),fC(n,l,s,a,c,o)}function yf(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=pC(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),hC(s,o,r,i)})}import*as kr from"path";function gC(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function yC(n){let e=n.instancePath?.trim();if(e)return kr.dirname(kr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?kr.dirname(kr.normalize(t)).replace(/\\/g,"/"):""}function wC(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function wf(n,e){return e?[...n,"-bootmode",e]:n}function vC(n,e,t){let r=[wf(["-start",n],t)],i=yC(e);if(i)for(let o of wC(e.imageRoot))r.push(wf(["-hvd",n,"-path",i,...o],t));return gC(r)}async function vf(n,e,t,r){let i=new Error("No start strategy ran"),o=vC(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function Jl(n){return(await ae.withHdcPath(n).listDevices()).map(t=>t.serial).filter(ji)}async function Kl(n){let e=await Jl(n);return e.length===0?[]:(await Promise.all(e.map(r=>Rs(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Sf(n,e){return(await Kl(n)).includes(e)}import*as Nr from"path";import{existsSync as SC,statSync as bC}from"fs";function xr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function EC(n){let e=xr(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 i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function PC(n){return xr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function CC(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Nr.dirname(Nr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=Nr.join(t,r.name);SC(i)&&bC(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function IC(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=PC(t),i=xr(t,["deviceType","DeviceType","devicetype"]),o=xr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:EC(t),path:xr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:xr(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function DC(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.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 bf(n){let t=IC(n)??DC(n);return CC(t),t}function Xl(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function AC(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function TC(n){if(!AC(n))return null;let e=Xl(n,["osVersion","OsVersion","OSVersion"]),t=Xl(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Xl(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Gs(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let o=TC(i);o&&r.push(o)}return r}catch{return[]}}function Ef(n){let t=Gs(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Pf=/no images are available/i,RC="7.0.0",kC={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"]};function ft(n){return n.normalize("NFKC").trim().toLowerCase()}function xC(n,e){let t=n.deviceType?.trim(),r=t?kC[ft(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function NC(n){let e=n.message||"";return Pf.test(e)}function LC(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Gi(n,e){return`${n} ${e.join(" ")}`.trim()}function OC(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 Lr=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${Gi(this.emulatorPath,e)}`),zs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return yf(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return bf(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),i=t.find(a=>Ce(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await vf(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
80
- Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:Sf(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Ce(e),i=t.find(a=>Ce(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new T(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(i.name,i))throw new T(`Emulator "${e}" is not running.`,"Emulator instance is not running.");t.type==="folded-state"&&xC(i,t.state);let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${OC(t)} -> ${Gi(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${Gi(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await zs(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
81
- `).trim(),a=LC(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(A.compareVersion(a,RC)<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.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e],{type:i}=t;switch(i){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unsupported emulator control action type: ${i}`)}}async executeEmulatorInherit(e){m(`Executing: ${Gi(this.emulatorPath,e)}`);let{exitCode:t}=await zs(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 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 r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!NC(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}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:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return Ef(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
82
- `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Gs(t),i=ft(e.deviceType),o=ft(e.osVersion);return r.filter(s=>ft(s.deviceType)===i&&(ft(s.osVersion)===o||ft(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=Gs(r),o=ft(t),s=e?.trim()?ft(e):void 0;return i.some(a=>ft(a.osVersion)===o||ft(a.softwareVersion)===o?s===void 0?!0:ft(a.deviceType)===s:!1)}async assertSystemImageAvailable(e){let t=e.osVersion?.trim();if(!t)throw new Error("The system image file cannot be found, download it again.");if(!await this.hasDownloadedSystemImage(e.deviceType,t))throw new Error(`The system image file ${t} cannot be found, download it again.`)}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Pf]})}async runEmulatorChecked(e,t){m(`Executing: ${Gi(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await zs(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
75
+ Application '${t}' installed successfully (no ability to launch).`)}function gC(n){let e={event:D.CommandExecuted,args:["run",...n.module?["--module"]:[],...n.device?["--device"]:[],...n.product?["--product"]:[],...n.buildMode?["--build-mode"]:[],...n.ability?["--ability"]:[],...n.uninstall?["--uninstall"]:[],...n.skipBuild?["--skip-build"]:[],...n.apply?["--apply"]:[],...n.hotreload?["--hotreload"]:[],...n.hotreloadApply?["--hotreload-apply"]:[]]};return n.buildMode&&(e.build_mode=n.buildMode),n.module&&(e.module_count=n.module.length),e}var Ql=new lC("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/");b()||Ql.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.");Ql.action(async n=>{let e=gC(n),t=Date.now(),r=!0,i=null;try{let o=await vC(n,e);o&&(o.ohpmMemoryMb&&(e.ohpm_install_memory=o.ohpmMemoryMb),o.syncMemoryMb&&(e.hvigor_sync_memory=o.syncMemoryMb),o.buildMemoryMb&&(e.hvigor_build_memory=o.buildMemoryMb))}catch(o){r=!1,i=W(o),console.error(dC(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}});async function hC(n,e,t,r,i){let o=new mn(e,n.rootDir),s=new xe(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:v,targetName:k}of t)for(let ce of n.collectNonHarDependentModuleList(v))a.add(`${ce}@${k}`),c.add(ce);let l=[...a],d=$i(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let v of c)Fs.generate(n.rootDir,v,r,e);let w=await Bt(n.rootDir,()=>Hi(o,s,r,i,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion..."));return console.log(`
76
+ `+qi("Build completed successfully.")),w}async function yC(n,e,t,r,i){let o=new Vt(t),s=ae.from(t),a=r[0]?.moduleName||i[0];await If(n,e,t,o,s,a)}function wC(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new T(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`,"Module is not runnable.")}}async function vC(n,e){let t=K.discover(process.cwd());console.warn(zs("Ensure the project source is trusted before proceeding."));let r=await A.new();if(n.skipBuild||r.assertJava(),e.bundle_name=t.getBundleName(),n.hotreloadApply){await bC(n,t,r);return}if(n.hotreload){await SC(n,t,r);return}if(n.apply){await PC(n,t,r);return}return Tf(n,t,r)}async function SC(n,e,t){if(n.hotreload==="stop"){await Pf(t,e);return}let i=Zl(e,n.module).map(Xl),{moduleName:o,targetName:s}=i[0];ql(n.module,o);let a=new Vt(t),c=ae.from(t),l=await Ys(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let w=e.getBundleName(),v=Df(e,i,n.ability);js.generate(e.rootDir,o,g,t);let k=new xe(t,e.rootDir);console.log(qi("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await k.ensureDaemonRunning();let ce=[`${o}@${g}`];for(let at of e.collectNonHarDependentModuleList(o))ce.includes(`${at}@${g}`)||ce.push(`${at}@${g}`);console.log(qi("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Be=new Or(e.rootDir,t);await Be.startWatchSession({moduleSpecs:ce,productName:g});let st=Ef(e,o,s,d,g);await Af(a,l,w,st,v,!!n.uninstall),console.log(qi("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.")),Be.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function bC(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let i=Zl(e,n.module),{moduleName:o}=Xl(i[0]);ql(n.module,o);let s=ae.from(t),a=await Ys(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();bf(e,o,r);let d=[`${o}@${c}`],g=await Sf({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function EC(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function Tf(n,e,t){let r=Zl(e,n.module),i=r.map(Xl),o=ae.from(t);if(await Cf(n.device,o)){await yC(n,e,t,i,r);return}wC(e,i);let s=new Vt(t),a=await Ys(o,n.device),c=!b()&&(a.includes("127.0.0.1")||a.includes("localhost")),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug",g;n.skipBuild||(g=await hC(e,t,i,l,d));let w=EC(e,i,c,l),v=e.getBundleName(),k=Df(e,i,n.ability);return await Af(s,a,v,w,k,!!n.uninstall),g}async function PC(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(qs.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=qs.join(e.rootDir,".hvigor",r),o=ae.from(t),s=await Ys(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new _s(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(zs("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(w){console.warn(zs(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(zs("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Tf(n,e,t)}var Rf=Ql;import{Command as CC}from"commander";import{green as kf,red as xf,cyan as ed}from"colorette";import{execa as Nf}from"execa";function IC(){return"latest"}function DC(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco-test/deveco-cli-openharmony-arm64"}function AC(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.13-23.1"}var TC={event:D.CommandExecuted,args:["update"]};async function td(n,e,t){let r={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(TC,r).catch(()=>{})}async function RC(n,e,t){let r=W(t);console.error(xf(`Failed to update ${n}`));let i=t instanceof Error?t.message:"";i&&console.error(xf(i)),await td(e,!1,r),process.exit(1)}var kC=new CC("update").description("Update deveco-cli to latest").action(async()=>{let n=DC(),e=AC(),t=IC(),r=Date.now();console.log(ed("Checking for updates..."));try{let{stdout:i}=await Nf("npm",["view",n,`dist-tags.${t}`]),o=i.trim();if(!o||o===e){console.log(kf(`
77
+ ${n} is already up to date (v${e}, tag: ${t})`)),await td(r,!0,null);return}console.log(ed(`
78
+ New version found: ${o} (current: ${e})`)),console.log(ed(`Updating ${n}...`)),await Nf("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
79
+ `+kf(`${n} updated successfully to version ${o}.`)),await td(r,!0,null)}catch(i){await RC(n,r,i)}}),Lf=kC;import{Command as oI}from"commander";import{execa as Ks}from"execa";function Ce(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as xC}from"child_process";var NC=2500;function LC(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function OC(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,NC);n.once("error",d=>c(d.message)),LC(n,l,s,a,c,o)}function Of(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=xC(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),OC(s,o,r,i)})}import*as Mr from"path";function MC(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function _C(n){let e=n.instancePath?.trim();if(e)return Mr.dirname(Mr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?Mr.dirname(Mr.normalize(t)).replace(/\\/g,"/"):""}function FC(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Mf(n,e){return e?[...n,"-bootmode",e]:n}function jC(n,e,t){let r=[Mf(["-start",n],t)],i=_C(e);if(i)for(let o of FC(e.imageRoot))r.push(Mf(["-hvd",n,"-path",i,...o],t));return MC(r)}async function _f(n,e,t,r){let i=new Error("No start strategy ran"),o=jC(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function nd(n){return(await ae.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Ui)}async function rd(n){let e=await nd(n);return e.length===0?[]:(await Promise.all(e.map(r=>Ls(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Ff(n,e){return(await rd(n)).includes(e)}import*as Fr from"path";import{existsSync as $C,statSync as HC}from"fs";function _r(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function UC(n){let e=_r(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 i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function BC(n){return _r(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function WC(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Fr.dirname(Fr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=Fr.join(t,r.name);$C(i)&&HC(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function VC(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=BC(t),i=_r(t,["deviceType","DeviceType","devicetype"]),o=_r(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:UC(t),path:_r(t,["path","Path","hvdPath","hvd_path"]),imageRoot:_r(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function GC(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.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 jf(n){let t=VC(n)??GC(n);return WC(t),t}function id(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function zC(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function qC(n){if(!zC(n))return null;let e=id(n,["osVersion","OsVersion","OSVersion"]),t=id(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=id(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Js(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let o=qC(i);o&&r.push(o)}return r}catch{return[]}}function $f(n){let t=Js(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Hf=/no images are available/i,YC="7.0.0",JC={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"]};function pt(n){return n.normalize("NFKC").trim().toLowerCase()}function KC(n,e){let t=n.deviceType?.trim(),r=t?JC[pt(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function XC(n){let e=n.message||"";return Hf.test(e)}function ZC(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Yi(n,e){return`${n} ${e.join(" ")}`.trim()}function QC(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 jr=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${Yi(this.emulatorPath,e)}`),Ks(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Of(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return jf(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),i=t.find(a=>Ce(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await _f(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
80
+ Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:Ff(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=Ce(e),i=t.find(a=>Ce(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new T(`Emulator "${e}" not found.`,"Emulator instance not found.");if(!await this.isAlreadyRunning(i.name,i))throw new T(`Emulator "${e}" is not running.`,"Emulator instance is not running.");t.type==="folded-state"&&KC(i,t.state);let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${QC(t)} -> ${Yi(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${Yi(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Ks(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
81
+ `).trim(),a=ZC(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(A.compareVersion(a,YC)<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.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e],{type:i}=t;switch(i){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unsupported emulator control action type: ${i}`)}}async executeEmulatorInherit(e){m(`Executing: ${Yi(this.emulatorPath,e)}`);let{exitCode:t}=await Ks(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 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 r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!XC(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}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:r}=await this.executeEmulator(t);return r}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,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
82
+ `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Js(t),i=pt(e.deviceType),o=pt(e.osVersion);return r.filter(s=>pt(s.deviceType)===i&&(pt(s.osVersion)===o||pt(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=Js(r),o=pt(t),s=e?.trim()?pt(e):void 0;return i.some(a=>pt(a.osVersion)===o||pt(a.softwareVersion)===o?s===void 0?!0:pt(a.deviceType)===s:!1)}async assertSystemImageAvailable(e){let t=e.osVersion?.trim();if(!t)throw new Error("The system image file cannot be found, download it again.");if(!await this.hasDownloadedSystemImage(e.deviceType,t))throw new Error(`The system image file ${t} cannot be found, download it again.`)}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Hf]})}async runEmulatorChecked(e,t){m(`Executing: ${Yi(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Ks(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
83
83
  `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),i=Ce(e),o=r.find(s=>Ce(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
84
84
  `)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`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.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>Ce(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=Ce(e),i=t.find(s=>Ce(s.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
85
- The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as UC,yellow as Df,gray as Af}from"colorette";import BC from"ora";import{green as MC}from"colorette";var _C=[[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]],FC=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],jC=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Cf(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function Zl(n){let e=n.replace(jC,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;Cf(i,FC)||(Cf(i,_C)?t+=2:t+=1),r+=i>65535?2:1}return t}function If(n,e){let t=Zl(n);return n+" ".repeat(Math.max(0,e-t))}function $C(n,e){return n.map((t,r)=>{let i=Zl(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,Zl(s))}return i})}function ht(n,e){let t=$C(n,e),r=[];r.push(n.map((i,o)=>If(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>If(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?MC(o):o)}return r.join(`
86
- `)}async function Tf(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=W(o),console.error(UC(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o)}}function WC(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Ce(t.name));r&&(t.deviceType=r)}}var VC=["Name","Serial","Kind","Device Type"];function GC(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function zC(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function qC(){console.log(Df(" No active devices.")),console.log(Af(b()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Ql(n,e){n||console.log(Af(` To ${e==="list"?"list local devices":"view local device details"}, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`))}function YC(n){let t=[...n].sort(zC).map(GC);console.log(ht(VC,t))}async function JC(n,e){if(b()||!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await Lr.from(e).getDeviceTypeByName();WC(n,r)}async function KC(n,e,t){try{let r=await n.ensureWirelessSelfConnection(),i=await n.getConnectedEntries();await JC(i,e),t?.stop(),i.length===0?qC():YC(i),Ql(r.mode,"list")}catch(r){throw new T(`Failed to list devices: ${r.message}`,"Failed to list devices.")}finally{t?.stop()}}async function XC(n,e){let t=await n.listDevices();if(t.length<2)return;let r=["Multiple devices connected. Specify a device with:"];for(let i of t){let o=await n.getDeviceName(i.serial);r.push(` ${e} -t ${i.serial} # ${o}`)}throw new T(r.join(`
87
- `),"Multiple devices connected.")}async function ZC(n,e){let t=await n.ensureWirelessSelfConnection();e||await XC(n,"devecocli device view");let r=await n.listDevices(),i=await n.getDeviceInfo(r,e);if(!i)throw console.log(Df("No connected device found.")),Ql(t.mode,"view"),new T("No connected device found.");let o=await n.getDeviceDetail(i.serial),s=await n.getDeviceName(i.serial);console.log(` Serial: ${i.serial}`),console.log(` Device Name: ${s}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`),Ql(t.mode,"view")}async function Rf(){try{let n=await A.new();return{manager:ae.from(n),toolProvider:n}}catch(n){throw new T(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}var ed=new HC("device").description("Manage connected devices");ed.command("list").description("List all connected devices").action(async()=>{let n={event:D.CommandExecuted,args:["device","list"]};await Tf(n,async()=>{let{manager:e,toolProvider:t}=await Rf(),r=BC({text:"Querying connected devices\u2026",color:"cyan"}).start();await KC(e,t,r)})});ed.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let e={event:D.CommandExecuted,args:["device","view",...n.target?["--target"]:[]]};await Tf(e,async()=>{let{manager:t}=await Rf();await ZC(t,n.target)})});var kf=ed;import{Argument as ad,Command as cd,Option as Ji}from"commander";import{green as Ki,cyan as Mr,red as Le,yellow as Rt,gray as Yi}from"colorette";import hI from"ora";import{red as QC}from"colorette";function xf(n,e){n?n.fail(e):console.error(QC(e)),process.exit(1)}import eI from"readline/promises";import{execa as Lf}from"execa";import*as un from"fs/promises";import*as nd from"os";import*as Xn from"path";var td=`1/4:\r
85
+ The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as sI,yellow as Wf,gray as Vf}from"colorette";import aI from"ora";import{green as eI}from"colorette";var tI=[[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]],nI=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],rI=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function Uf(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function od(n){let e=n.replace(rI,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;Uf(i,nI)||(Uf(i,tI)?t+=2:t+=1),r+=i>65535?2:1}return t}function Bf(n,e){let t=od(n);return n+" ".repeat(Math.max(0,e-t))}function iI(n,e){return n.map((t,r)=>{let i=od(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,od(s))}return i})}function mt(n,e){let t=iI(n,e),r=[];r.push(n.map((i,o)=>Bf(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Bf(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?eI(o):o)}return r.join(`
86
+ `)}async function Gf(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=W(o),console.error(sI(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o)}}function cI(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(Ce(t.name));r&&(t.deviceType=r)}}var lI=["Name","Serial","Kind","Device Type"];function dI(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function uI(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function pI(){console.log(Wf(" No active devices.")),console.log(Vf(b()?" Connect a USB device with debugging enabled.":" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function sd(n,e){n||console.log(Vf(` To ${e==="list"?"list local devices":"view local device details"}, enable wireless debugging: Settings \u2192 System \u2192 Developer options \u2192 Wireless debugging`))}function mI(n){let t=[...n].sort(uI).map(dI);console.log(mt(lI,t))}async function fI(n,e){if(b()||!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await jr.from(e).getDeviceTypeByName();cI(n,r)}async function gI(n,e,t){try{let r=await n.ensureWirelessSelfConnection(),i=await n.getConnectedEntries();await fI(i,e),t?.stop(),i.length===0?pI():mI(i),sd(r.mode,"list")}catch(r){throw new T(`Failed to list devices: ${r.message}`,"Failed to list devices.")}finally{t?.stop()}}async function hI(n,e){let t=await n.listDevices();if(t.length<2)return;let r=["Multiple devices connected. Specify a device with:"];for(let i of t){let o=await n.getDeviceName(i.serial);r.push(` ${e} -t ${i.serial} # ${o}`)}throw new T(r.join(`
87
+ `),"Multiple devices connected.")}async function yI(n,e){let t=await n.ensureWirelessSelfConnection();e||await hI(n,"devecocli device view");let r=await n.listDevices(),i=await n.getDeviceInfo(r,e);if(!i)throw console.log(Wf("No connected device found.")),sd(t.mode,"view"),new T("No connected device found.");let o=await n.getDeviceDetail(i.serial),s=await n.getDeviceName(i.serial);console.log(` Serial: ${i.serial}`),console.log(` Device Name: ${s}`),o.deviceType&&console.log(` Device Type: ${o.deviceType}`),o.osVersion&&console.log(` OS Version: ${o.osVersion}`),sd(t.mode,"view")}async function zf(){try{let n=await A.new();return{manager:ae.from(n),toolProvider:n}}catch(n){throw new T(`Failed to initialize device manager: ${n.message}`,"Failed to initialize device manager.")}}var ad=new oI("device").description("Manage connected devices");ad.command("list").description("List all connected devices").action(async()=>{let n={event:D.CommandExecuted,args:["device","list"]};await Gf(n,async()=>{let{manager:e,toolProvider:t}=await zf(),r=aI({text:"Querying connected devices\u2026",color:"cyan"}).start();await gI(e,t,r)})});ad.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let e={event:D.CommandExecuted,args:["device","view",...n.target?["--target"]:[]]};await Gf(e,async()=>{let{manager:t}=await zf();await yI(t,n.target)})});var qf=ad;import{Argument as fd,Command as gd,Option as Zi}from"commander";import{green as Qi,cyan as Hr,red as Ne,yellow as Tt,gray as Xi}from"colorette";import OI from"ora";import{red as wI}from"colorette";function Yf(n,e){n?n.fail(e):console.error(wI(e)),process.exit(1)}import vI from"readline/promises";import{execa as Kf}from"execa";import*as gn from"fs/promises";import*as ld from"os";import*as nr from"path";var cd=`1/4:\r
88
88
  ---------------------------------------\r
89
89
  Statement About HarmonyOS and Privacy\r
90
90
  \r
@@ -1254,13 +1254,13 @@ Part I: Chinese mainland.\r
1254
1254
  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
1255
1255
  \r
1256
1256
  Part III: Other countries and regions.\r
1257
- ---------------------------------------\r`;var tI=new Set,qs=new Map,rd="HarmonyOS_Software_Service_Agreement",Of=["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(`
1258
- `),Mf=Of,id="HarmonyOS_SDK_Agreement";function _f(n,e){return`${n}\0${e}`}function Ff(){tI.clear(),qs.clear()}var nI=Of,rt=class extends Error{constructor(e=nI){super(e),this.name="EmulatorLicenseBlockedError"}};function jf(n,e){return[n??"",e??""].join(`
1259
- `)}function $f(n){let e=n.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let r=e.match(/(\d+)\.(\d+)\b/);return r?`${r[1]}.${r[2]}`:null}function rI(n){return`Emulator${n.trim()}`}function Hf(n){let e=rI(n);if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;if(!r)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return Xn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Xn.join(nd.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Xn.join(nd.homedir(),".cache");return Xn.join(t,"Huawei",e,".emu_config")}async function iI(n,e,t){let r=_f(n,e),i=qs.get(r);if(i!==void 0)return i;let o=await Lf(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=jf(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new rt(t);return qs.set(r,s),s}function oI(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function sI(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function aI(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=oI(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function cI(n){let e={};for(let t of n.split(/\r?\n/)){let r=aI(t);r&&(e[r.key]=r.entry)}return e}function lI(n){let e=n.trim();if(!e)return{};let t=sI(e);return t||cI(n)}function dI(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Uf(n,e,t,r){let i=await iI(n,e,r),o=$f(i);if(!o)throw new rt(r);let s=Hf(o),a;try{a=await un.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new rt(r):d}let l=lI(a)[t];if(!l)throw new rt(r);if(l.delimiter==="=")throw new rt(r);if(!dI(l.value))throw new rt(r)}async function od(n,e){await Uf(n,e,rd,Mf)}async function sd(n,e){await Uf(n,e,id,Mf)}async function uI(n,e){let t=await Lf(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=jf(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=_f(n,e);return qs.set(i,r),r}async function Bf(n,e){let t=await uI(n,e),r=$f(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1260
- ${t}.`);return Hf(r)}function Nf(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function pI(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[rd]="agree",r[id]="agree",await un.writeFile(n,`${JSON.stringify(r,null,2)}
1261
- `,"utf8"),!0}catch{}return!1}async function mI(n,e){let t=rd,r=id,i=[{k:t,re:new RegExp(`^\\s*${Nf(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Nf(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:h}of i)if(h.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await un.writeFile(n,s.join(`
1257
+ ---------------------------------------\r`;var SI=new Set,Xs=new Map,dd="HarmonyOS_Software_Service_Agreement",Xf=["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(`
1258
+ `),Zf=Xf,ud="HarmonyOS_SDK_Agreement";function Qf(n,e){return`${n}\0${e}`}function eg(){SI.clear(),Xs.clear()}var bI=Xf,nt=class extends Error{constructor(e=bI){super(e),this.name="EmulatorLicenseBlockedError"}};function tg(n,e){return[n??"",e??""].join(`
1259
+ `)}function ng(n){let e=n.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let r=e.match(/(\d+)\.(\d+)\b/);return r?`${r[1]}.${r[2]}`:null}function EI(n){return`Emulator${n.trim()}`}function rg(n){let e=EI(n);if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;if(!r)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return nr.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return nr.join(ld.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||nr.join(ld.homedir(),".cache");return nr.join(t,"Huawei",e,".emu_config")}async function PI(n,e,t){let r=Qf(n,e),i=Xs.get(r);if(i!==void 0)return i;let o=await Kf(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=tg(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new nt(t);return Xs.set(r,s),s}function CI(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function II(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function DI(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=CI(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function AI(n){let e={};for(let t of n.split(/\r?\n/)){let r=DI(t);r&&(e[r.key]=r.entry)}return e}function TI(n){let e=n.trim();if(!e)return{};let t=II(e);return t||AI(n)}function RI(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function ig(n,e,t,r){let i=await PI(n,e,r),o=ng(i);if(!o)throw new nt(r);let s=rg(o),a;try{a=await gn.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new nt(r):d}let l=TI(a)[t];if(!l)throw new nt(r);if(l.delimiter==="=")throw new nt(r);if(!RI(l.value))throw new nt(r)}async function pd(n,e){await ig(n,e,dd,Zf)}async function md(n,e){await ig(n,e,ud,Zf)}async function kI(n,e){let t=await Kf(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=tg(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=Qf(n,e);return Xs.set(i,r),r}async function og(n,e){let t=await kI(n,e),r=ng(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
1260
+ ${t}.`);return rg(r)}function Jf(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function xI(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[dd]="agree",r[ud]="agree",await gn.writeFile(n,`${JSON.stringify(r,null,2)}
1261
+ `,"utf8"),!0}catch{}return!1}async function NI(n,e){let t=dd,r=ud,i=[{k:t,re:new RegExp(`^\\s*${Jf(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Jf(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:g}of i)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(r)||s.push(`${r}:agree`),await gn.writeFile(n,s.join(`
1262
1262
  `)+(s.length>0?`
1263
- `:""),"utf8")}async function Wf(n){await un.mkdir(Xn.dirname(n),{recursive:!0});let e="";try{e=await un.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await pI(n,e,t)||await mI(n,e)}async function Vf(n,e){return console.log(td),0}var fI="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Gf(n,e){try{return await od(n,e),await sd(n,e),!0}catch(t){if(t instanceof rt)return!1;throw t}}async function zf(n,e){if(await Gf(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(td),!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 r=eI.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(fI)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await Bf(n,e);await Wf(s),Ff()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function qf(n,e){if(await Gf(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await Bf(n,e);await Wf(t),Ff()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var gI=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Yf=["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"],yI=`
1263
+ `:""),"utf8")}async function sg(n){await gn.mkdir(nr.dirname(n),{recursive:!0});let e="";try{e=await gn.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await xI(n,e,t)||await NI(n,e)}async function ag(n,e){return console.log(cd),0}var LI="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function cg(n,e){try{return await pd(n,e),await md(n,e),!0}catch(t){if(t instanceof nt)return!1;throw t}}async function lg(n,e){if(await cg(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(cd),!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 r=vI.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(LI)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await og(n,e);await sg(s),eg()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function dg(n,e){if(await cg(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await og(n,e);await sg(t),eg()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var MI=["ohos.qemu.hvd.name","const.product.name","const.product.model"],ug=["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"],_I=`
1264
1264
  Folded state scene mappings:
1265
1265
  foldableFold (3):
1266
1266
  open Fully expanded state
@@ -1283,43 +1283,43 @@ Folded state scene mappings:
1283
1283
  left-half-folded-right-folded
1284
1284
  left-expanded-right-half-folded
1285
1285
  left-half-folded-right-half-folded
1286
- `;function wI(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function vI(n){let e=n.trim();if(!Yf.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Yf.join(", ")}`);return e}function Kf(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function Xf(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!SI(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function SI(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function bI(n,e,t,r,i){return Number(Xf(n,e,t,r,i))}function EI(n){let e=n.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 PI(n){let e=n.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${n}" 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 "${n}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function CI(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(Rt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(Rt("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(i=>t(i)===r)){console.error(Le("--os-version does not match any downloaded image (exact string required).")),console.log(Rt("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var II=["Name","Status","Serial","Device Type","OS Version"];function DI(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function AI(n,e){let t=await Promise.all(e.map(async r=>{let i=await Cr(n,r,gI);return[r,i]}));return new Map(t)}async function TI(n){let e=await Jl(n),t=await AI(n,e);return{serials:e,params:t}}function RI(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function kI(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&RI(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function xI(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(i=>DI(i.emu,i.serial,i.effectiveRunning))}async function NI(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),TI(e)]);if(r.length===0){t?.stop(),console.log(Rt(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=kI(i.serials,i.params,o);t?.stop();let c=xI(r,s,a);console.log(ht(II,c))}catch(r){xf(t,`Failed to list emulators: ${r.message}`)}}function Zf(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(Le(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Yi(s.stdout)),s.stderr&&console.error(Yi(s.stderr))}return r}var LI=2e3,OI=6e4;async function MI(n,e){let t=Ce(e);return(await Kl(n)).some(i=>Ce(i)===t)}async function Qf(n,e,t,r=OI,i=LI){let o=Date.now()+r;for(;Date.now()<o;){if(await MI(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function _I(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(Rt(`Emulator "${t}" is already running.`));return}console.log(Mr(`Starting emulator "${t}"...`));let i=await Qf(e,t,!0);console.log(i?Ki(`Emulator "${t}" started successfully.`):Rt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function FI(n,e,t){let r=await Promise.allSettled(t.map(o=>_I(n,e,o)));Zf(r,t,"start")&&process.exit(1)}async function eh(n,e){let t=e.trim();if(!ji(t))return t;let r=await ae.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function jI(n,e,t){let r=await eh(e,t);if(console.log(Mr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Rt(`Emulator "${r}" is already stopped.`));return}let o=await Qf(e,r,!1);console.log(o?Ki(`Emulator "${r}" stopped successfully.`):Rt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function $I(n,e,t){let r=await Promise.allSettled(t.map(o=>jI(n,e,o)));Zf(r,t,"stop")&&process.exit(1)}async function it(){try{let n=await A.new();return{manager:Lr.from(n),toolProvider:n}}catch(n){throw new Error(`Failed to initialize emulator: ${n.message}`,{cause:n})}}async function Wt(n,e,t){let r={event:D.CommandExecuted,args:["emulator",t,"--target"]},i=Date.now(),o=!0,s=null;try{let a=wI(n.target),c=e(),{manager:l,toolProvider:d}=await it(),h=await eh(d.hdcPath,a);await l.controlEmulator(h,c),console.log(Ki(`Emulator "${a}" operation completed.`))}catch(a){o=!1,s=W(a);let c=n.target?.trim()||"<unknown>";console.error(Le(`Failed to operate emulator "${c}": ${a.message}`)),process.exitCode=1}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await I.track(r,a)}}function HI(n){let e=[];return Ys(e,"longitude",n.longitude,-180,180,8),Ys(e,"latitude",n.latitude,-90,90,8),Ys(e,"altitude",n.altitude,-1e4,1e4,2),Ys(e,"bearing",n.direction,0,359.99,2,"--direction"),ld(e,"Specify one geolocation option.")}function UI(n){let e=[];return zi(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),zi(e,"humidity",n.humidity,0,100,!1),zi(e,"temperature",n.temperature,-273.1,100,!1),zi(e,"steps",n.steps,0,1e4,!0),zi(e,"heartrate",n.heartrate,0,255,!0),ld(e,"Specify one sensor option.")}function ld(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function Ys(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Xf(s,t,r,i,o)})}function zi(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Kf(s,t,r,i):bI(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function BI(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Kf("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),ld(e,"Specify --level or --status.")}var we=new cd("emulator").description("Manage emulator instances"),WI=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Js(n){let e=new Ji("--device-type <type>","Emulator device type").choices([...WI]);return n?e.makeOptionMandatory():e}function Or(n,e){for(let t of e)if(t in n)return n[t]}function qi(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Jf(n){let e=qi(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var VI=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],GI="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function th(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function nh(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=qi(Or(i,["osVersion","OsVersion","OSVersion","os_version"])),s=qi(Or(i,["deviceType","DeviceType","device_type"])),a=Jf(Or(i,["downloaded","Downloaded","isDownloaded"])),c=qi(Or(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=qi(Or(i,["releaseType","ReleaseType","release_type"])),d=Jf(Or(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function zI(n){let e=n.trim();if(!e)return!0;let t=th(e);return t===null?!1:t.length===0?!0:nh(t,!0).length===0}function qI(n,e){let t=n.trim();if(!t)return"";let r=th(t);if(!r)return n.trimEnd();let i=nh(r,e);return ht(VI,i)}var Ks=new cd("image").description("HarmonyOS emulator system images (download, list, remove)");Ks.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 n=>{let{manager:e,toolProvider:t}=await it();try{await sd(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof rt&&(console.error(Le(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Le("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Le("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(Le(`Failed to download system image: ${r.message}`)),process.exit(1)}});Ks.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 n=>{let{manager:e}=await it();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Le(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Ks.command("list").description("List system images").addOption(Js(!1)).option("--all","List all images (local and remote)").addOption(new Ji("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await it();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(zI(r)){console.log(Rt(GI));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=qI(r,n.all===!0);console.log(i)}catch(t){console.error(Le(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});we.addCommand(Ks);var Xs=new cd("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");Xs.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await it(),e=await Vf(n.emulatorPath,n.sdkPath);process.exit(e)});Xs.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await it(),e=await qf(n.emulatorPath,n.sdkPath);process.exit(e)});Xs.action(async()=>{let{toolProvider:n}=await it(),e=await zf(n.emulatorPath,n.sdkPath);process.exit(e)});we.addCommand(Xs);we.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Wt(n,()=>({type:"shake"}),"shake"));we.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Wt(n,()=>({type:"power"}),"power"));we.command("rotate").description("Rotate emulator").addOption(new Ji("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ad("<direction>").choices(["left","right"])).action((n,e)=>Wt(e,()=>({type:"rotation",direction:n}),"rotate"));we.command("volume").description("Change volume").addOption(new Ji("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new ad("<direction>").choices(["up","down"])).action((n,e)=>Wt(e,()=>({type:"volume",direction:n}),"volume"));we.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",yI).action((n,e)=>Wt(e,()=>({type:"folded-state",state:vI(n)}),"fold"));we.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new Ji("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Wt(n,()=>BI(n),"battery"));we.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Wt(n,()=>HI(n),"geolocation"));we.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new ad("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Wt(e,()=>t[n],"scene")});we.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Wt(n,()=>UI(n),"sensor"));we.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await it(),t=hI({text:"Listing emulators\u2026",color:"cyan"}).start();await NI(n,e.hdcPath,t)});we.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await it();try{await od(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof rt&&(console.error(Le(r.message)),process.exit(1)),r}n?.length||(console.error(Le("Error: missing required argument 'names'")),process.exit(1)),await FI(e,t.hdcPath,n)});we.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await it();n?.length||(console.error(Le("Error: missing required argument 'names'")),process.exit(1)),await $I(e,t.hdcPath,n)});var rh=we.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").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");rh.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1287
- ${Rt("Tip: ")}${Yi("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1288
- ${Mr('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1289
- ${Mr('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1290
- `)}});rh.action(async(n,e)=>{try{EI(n),PI(e.osVersion);let{manager:t}=await it(),r=await t.listDownloadedImageOsVersions();CI(e.osVersion,r),console.log(Mr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Ki(`Emulator "${n}" created successfully.`))}catch(t){console.error(Le(`${t.message}`)),process.exit(1)}});we.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await it();console.log(Mr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Ki(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Le(r.message)),r.stdout&&console.error(Yi(r.stdout)),r.stderr&&console.error(Yi(r.stderr)),process.exit(1)}});var ih=we;import{Command as hD}from"commander";import{red as hd,cyan as kt}from"colorette";import*as Dh from"readline";import*as Ch from"crypto";import*as oh from"http";import*as sh from"crypto";import{URL as YI}from"url";var Zs=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=oh.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new YI(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let i="",o=0,s=65536;e.on("data",a=>{if(o+=a.length,o>s){e.destroy(new Error("Request body too large"));return}i+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,i)})}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&sh.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 Me from"fs";import*as pn from"path";import{homedir as tD}from"os";var Vt={};XS(Vt,{LocalCrypto:()=>Vt,decryptForLocalStorage:()=>ZI,decryptForLocalStorageFromDirectory:()=>QI,encryptForLocalStorage:()=>XI,isEncryptedBlob:()=>eD});import*as ee from"fs";import*as Ae from"path";import*as Oe from"crypto";import*as ch from"os";import{homedir as lh}from"os";var De=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var Xi=Hn.ALGORITHM,dh=Hn.IV_LENGTH,Zi=Hn.KEY_LENGTH,Qi=Hn.KEY_LENGTH,Zn=Hn.KEK_VERSIONS,Qs=process.env.DEVECO_CLI_DATA_DIR||Ae.join(lh(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME),ea=Ae.join(lh(),".local","share",Ee.APP_NAME,"keys"),_r=Ae.join(Qs,Ee.KEY_FILE_NAME);function ah(n){return ch.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 dd(n){return Ae.join(ea,`${n}.bin`)}function uh(){if(!ee.existsSync(Qs))try{ee.mkdirSync(Qs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new De(ah(Qs)):n}if(!ee.existsSync(ea))try{ee.mkdirSync(ea,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new De(ah(Ae.dirname(ea))):n}}function ph(){uh();for(let n of Zn){let e=dd(n);ee.existsSync(e)||ee.writeFileSync(e,Oe.randomBytes(Zi),{mode:384})}}function mh(n){if(!Zn.includes(n))throw new Error(`Invalid kekId: ${n}`);ph();let e=dd(n),t=ee.readFileSync(e);if(t.length===Zi)return t;let r=Oe.randomBytes(Zi);return ee.writeFileSync(e,r,{mode:384}),r}function ud(n,e){let t=Oe.randomBytes(dh),r=mh(e),i=Oe.createCipheriv(Xi,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:Xi,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function fh(n,e){return hh(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function hh(n,e,t,r){let i=Oe.createDecipheriv(Xi,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function gh(n,e){return hh(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function JI(){if(ph(),ee.existsSync(_r))return;let n=Oe.randomBytes(Qi),e=ud(n,Zn[0]);ee.writeFileSync(_r,JSON.stringify(e,null,2),{mode:384})}function yh(){JI();let n=JSON.parse(ee.readFileSync(_r,"utf8")),e=fh(n,mh(n.kekId));if(e.length===Qi)return e;let t=Oe.randomBytes(Qi),r=ud(t,Zn[0]);return ee.writeFileSync(_r,JSON.stringify(r,null,2),{mode:384}),t}function KI(){uh();for(let t of Zn){let r=dd(t);ee.existsSync(r)||ee.writeFileSync(r,Oe.randomBytes(Zi),{mode:384})}if(ee.existsSync(_r))return;let n=Oe.randomBytes(Qi),e=ud(n,Zn[0]);ee.writeFileSync(_r,JSON.stringify(e,null,2),{mode:384})}function XI(n){let e=yh(),t=Oe.randomBytes(dh),r=Oe.createCipheriv(Xi,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:Xi,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function ZI(n){try{return gh(n,yh())}catch{throw KI(),new Error("Failed to decrypt local ciphertext")}}function QI(n,e){let t=Ae.join(e,Ee.KEY_FILE_NAME),r=JSON.parse(ee.readFileSync(t,"utf8"));if(!Zn.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=Ae.join(e,"keys",`${r.kekId}.bin`),o=Ae.resolve(i),s=Ae.resolve(Ae.join(e,"keys"));if(!o.startsWith(s+Ae.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=ee.readFileSync(o);if(a.length!==Zi)throw new Error("Invalid external root key");let c=fh(r,a);if(c.length!==Qi)throw new Error("Invalid external data encryption key");return gh(n,c)}function eD(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 gt(){return process.env.DEVECO_CLI_AUTH_SOURCE===Ee.AUTH_SOURCE_DEVECO_CODE}var ta=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||pn.join(tD(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME);return pn.join(e,Ee.TOKEN_FILE_NAME)}ensureConfigDir(){let e=pn.dirname(this.getLocalTokenFilePath());Me.existsSync(e)||Me.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 r=this.getLocalTokenFilePath();Me.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return gt()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!gt())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=pn.resolve(e);try{let r=pn.join(t,Ee.TOKEN_FILE_NAME);if(!Me.existsSync(r))return null;let i=JSON.parse(Me.readFileSync(r,"utf8"));return Vt.isEncryptedBlob(i)?Vt.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Me.existsSync(e))return null;let t=JSON.parse(Me.readFileSync(e,"utf8"));return Vt.isEncryptedBlob(t)?Vt.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(gt()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Me.existsSync(e)&&Me.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Gt=new ta;import{exec as nD}from"child_process";import{promisify as rD}from"util";var iD=rD(nD);async function wh(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;case"openharmony":console.log("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4EE5\u4E0B\u767B\u5F55\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A"),console.log(n);return;default:t=`xdg-open "${n}"`;break}try{await iD(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import oD from"axios";import{getProxyForUrl as sD}from"proxy-from-env";function aD(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 pd=class{client;constructor(){let e={timeout:bi.HTTP_TIMEOUT_MS,headers:{"User-Agent":Qo.USER_AGENT,"accept-language":Qo.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=oD.create(e),this.client.interceptors.request.use(t=>{let r=sD(t.url??"");return t.proxy=r?aD(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}
1291
- ${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}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){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}},O=new pd;function vh(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var zt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},Qn={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},na={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},cD={[zt.CHINA]:Qn.CHINA,[zt.RUSSIA]:Qn.RUSSIA,[zt.EUROPE]:Qn.EUROPE,[zt.SINGAPORE]:Qn.CHINA},lD={[na.CHINA]:zt.CHINA,[na.SINGAPORE]:zt.SINGAPORE,[na.EUROPE]:zt.EUROPE,[na.RUSSIA]:zt.RUSSIA};function Sh(n){return cD[n]??Qn.CHINA}function bh(n){return lD[n]??zt.CHINA}var md=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=bh(t),c={tempToken:s,site:a,version:Ee.API_VERSION,appid:o},l=`${r}/${i}`,d=await O.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let h=d.data.trim();if(!vh(h))throw new Error("Invalid jwtToken format");return h}},Eh=new md;var fd=class{async checkJwtToken(e,t,r=!1){let i={refresh:String(r),jwtToken:e},o=`${t}/${J.JWT_TOKEN_CHECK_PATH}`,s=await O.get(o,{headers:i});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return O.parseJson(s)}async refreshToken(e){let t=await Gt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},i=`${t}/${J.JWT_TOKEN_CHECK_PATH}`,o=await O.get(i,{headers:r});if(o.statusCode!==200)return null;let s=O.parseJson(o);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(r){let i=r;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}async getUserInfoFromJwt(e,t,r=!1){let i=await this.checkJwtToken(e,t,r);return!i.status||!i.userInfo||!i.userInfo.accessToken?(m("jwtToken invalid."),await Gt.clearToken(),null):{userId:i.userInfo.userId??"",userName:i.userInfo.name??"",accessToken:i.userInfo.accessToken,refreshToken:i.userInfo.refreshToken??"",jwtToken:e,countryCode:i.userInfo.nationalCode,language:Sh(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Gt.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},Fr=new fd;import dD from"querystring";import{spawn as uD}from"child_process";function Ph(n){try{let e=JSON.stringify({signInfo:[{agrType:Ei.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=dD.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=uD("curl",["-s","-X","POST",Ei.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});r.unref(),r.stdout?.on("data",i=>{let o=i.toString().trim();o==="200"?m("Agreement sign reported successfully"):m(`Agreement sign failed: HTTP ${o}`)}).on("error",()=>{})}catch(e){m(`Agreement sign error: ${e.message}`)}}var ra=class{config;server=null;constructor(e){this.config={...Pi,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${gt()}`);let e=this.generateClientSecret();this.server=new Zs(e,J.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 De("Non-China accounts are not supported.");let r=await Eh.getJwtToken(t.tempToken,t.siteId,J.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await Fr.getUserInfoFromJwt(r,J.CN_LOGIN_URL);if(!i)throw new De("Login failed: failed to get user info");return m(`User info received: ${i.userName}`),await Gt.saveJwtToken(r),m("JWT token saved"),Ph(i.accessToken),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await Gt.loadJwtToken();if(!e)return!1;let r=`${J.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await O.post(r,{timeout:5e3})}catch{m("Logout: server notification failed, local token cleared")}finally{await Gt.clearToken()}return!0}async getUserInfo(e=!0){return Fr.fetchUserInfo(J.CN_LOGIN_URL,e)}generateClientSecret(){return Ch.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${J.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await wh(i)}async refreshToken(){return Fr.refreshToken(J.CN_LOGIN_URL)}},Te=new ra;function mD(){return gt()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function fD(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var ia=class{config;constructor(e){this.config={...Pi,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Fr.fetchUserInfo(J.CN_LOGIN_URL,!0);if(!e)throw new De(mD());let t=await this.fetchTeamList(e.accessToken,e.userId),r=fD(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,i;try{i=await O.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:Qn.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new De("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:o})}if(i.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${i.statusCode}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}},Ih=new ia;async function mn(){return Ih.listTeams()}async function oa(n,e,t){let r=Date.now(),i=!0,o=null;try{await e()}catch(s){i=!1,o=W(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:i,error_code:o};await I.track(n,s)}}function gD(n){if(n.length===0)return kt("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
1292
- `)}function yD(){return new Promise(n=>{let e=Dh.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}async function wD(n){if(n||!process.stdin.isTTY){console.log(kt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(kt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await yD()}var eo=new hD("auth").description("Authentication commands (login, logout, status, team)");eo.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async n=>{if(gt()){console.log(hd("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:D.CommandExecuted,args:["auth","login"]};await oa(e,async()=>{let t=await Te.getUserInfo();if(t){console.log(kt(`Already logged in, User Name:${t.userName}`));return}console.log(kt("Starting login process...")),await wD(n.prompt===!1);let r=await Te.login();console.log(kt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof De||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})});eo.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(gt()){console.log(hd("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:D.CommandExecuted,args:["auth","logout"]};await oa(n,async()=>{let e=await Te.logout();console.log(e?kt("Logout successful"):kt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});eo.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:D.CommandExecuted,args:["auth","status"]};await oa(n,async()=>{let e=await Te.getUserInfo();if(!e){console.log(kt("Not logged in"));return}console.log(kt(`Current user: ${e.userName}`))},e=>e)});var vD=eo.command("team").description("Team-related commands");vD.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:D.CommandExecuted,args:["auth","team","list"]};await oa(n,async()=>{let e=await mn();console.log(gD(e.teamList))},e=>{if(e instanceof De){console.log(hd(e.message));return}throw e})});var Ah=eo;import{Command as ND}from"commander";import{green as LD,red as oo,cyan as Jh,yellow as Kh,dim as Xh}from"colorette";import OD from"p-limit";import SD from"ora";var yt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=SD(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 Th from"fs";import*as Rh from"path";var kh=["DevEco"];async function sa(){let n=await O.get(dt.TAGS_API_URL),t=aa(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 bD(n){let e=[],t=dt.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await O.post(dt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=aa(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function gd(n){let e=new Map,t=n.map(i=>bD(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!kh.includes(o.name)))}async function ED(n,e){let t=await O.post(dt.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:dt.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return aa(t,"Skills API").data.list}async function yd(n,e){let t=new Map,r=e.map(o=>ED(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!kh.includes(s.name)))}function xh(n){let e=[],t=Ft();for(let[,r]of Object.entries(t)){let i=Rh.join(r.path,n);Th.existsSync(i)&&e.push(r.displayName)}return e.sort()}function aa(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=O.parseJson(n);if(t.code!==dt.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Nh(n){let e=`${dt.SKILL_API_BASE}/${n}/checksum`,t=await O.get(e);return aa(t,"Checksum API").data}import PD from"adm-zip";import CD from"crypto";import Oh from"fs";import le from"path";import{fileURLToPath as ID}from"url";import{red as DD}from"colorette";var qt=Oh.promises;function wd(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Lh(n,e){let t=le.resolve(e),r=le.resolve(n),i=le.relative(r,t);if(i.startsWith("..")||le.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function vd(n){return le.isAbsolute(n)?n:le.resolve(process.cwd(),n)}function AD(n){return CD.createHash("sha256").update(n).digest("hex")}async function TD(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=AD(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Mh(n){let e=`${dt.SKILL_API_BASE}/${n}/install?format=zip`,t=await O.getBinary(e),r=await Nh(n);return await TD(t,r),t}async function RD(n,e,t){wd(t);let r=new PD(n),i=r.getEntries();try{await qt.stat(e)}catch{await qt.mkdir(e,{recursive:!0})}let o=le.join(e,t);Lh(e,o);for(let s of i){let a=le.join(o,s.entryName);Lh(o,a)}r.extractAllTo(o,!0)}async function Sd(n){let e=Ft();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=he[n];try{return await qt.access(r),!0}catch{return!1}}function bd(n){return Ft()[n].path}function Ed(n,e){let r=Ft()[e],i="projectPath"in r?r.projectPath:le.join("."+e,"skills");return le.join(n,i)}async function kD(n,e,t){wd(e);let r=le.join(n,e);try{if(await qt.access(r),t)await qt.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 Pd(n,e,t){await RD(n,e,t),console.log(`Skill ${t} installed to ${le.join(e,t)}.`)}async function Cd(n,e,t){let r=le.join(e,t);await qt.mkdir(r,{recursive:!0});let i=le.join(r,le.basename(n));await qt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function _h(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(DD(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function jr(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await kD(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return _h(n,i,"Installation failed")}}async function Id(n,e){try{wd(n);let t=await e(),r=le.join(t,n);try{await qt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await qt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return _h(n,t,"Removal failed")}}async function Fh(n,e,t,r=!1){return jr(n,()=>bd(e),i=>Pd(t,i,n),r)}async function jh(n,e,t,r=!1){return jr(n,()=>t,i=>Pd(e,i,n),r)}async function $h(n,e,t,r,i=!1){return jr(n,()=>Ed(t,r),o=>Pd(e,o,n),i)}async function Hh(n,e,t,r=!1){return jr(n,()=>bd(t),i=>Cd(e,i,n),r)}async function Uh(n,e,t,r,i=!1){return jr(n,()=>Ed(t,r),o=>Cd(e,o,n),i)}async function Bh(n,e,t,r=!1){return jr(n,()=>t,i=>Cd(e,i,n),r)}async function Wh(n,e){return Id(n,()=>bd(e))}async function Vh(n,e){return Id(n,()=>e)}async function Gh(n,e,t){return Id(n,()=>Ed(e,t))}function zh(){let e=le.dirname(ID(import.meta.url));for(;;){let t=le.join(e,"SKILL.md");if(Oh.existsSync(t))return t;let r=le.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import qh from"fs";import{cyan as xD}from"colorette";async function to(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Sd(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function no(){let n=[],e=Ft();for(let t of Object.keys(e))await Sd(t)&&n.push(t);return n}function ro(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(xD("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function fn(n,e,t){if(!qh.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!qh.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function io(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?vd(n):void 0,resolvedProject:e?vd(e):void 0}}async function ca(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await to(n.agent)).map(a=>({project:t,agent:a})):t?i=(await no()).map(a=>({project:t,agent:a})):n.agent?r=await to(n.agent):r=await no(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function MD(n){let e=await sa();if(n.all)return(await gd(e)).map(r=>r.enName);{let r=(await yd(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new er("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function _D(n,e,t,r){let i=[];if(t.customPath){let o=await jh(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Fh(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await $h(n,e,o,s,r);i.push(a)}return i}function FD(n){if(n.all&&n.skill)throw new er("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new er("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=io(n.path,n.project,n.agent);return t&&fn(t,"Project directory",n.force),e&&fn(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function jD(n,e,t){let r=await ca(n,e,t);return{skillNames:await MD(n),targets:r}}async function $D(n,e,t,r){let i=[],o=0,s=n.length,a=OD(5),c=n.map(l=>a(()=>HD(l)));for(let l=0;l<n.length;l++){let d=n[l],h=s>1?` (${l+1}/${s})`:"";r.start(`Installing ${d}${h}...`);let w=await c[l];if(!w.success){r.fail(),console.log(oo(`${d}: Download failed - ${w.error}`)),i.push({success:!1});continue}o+=w.buffer.length,r.stop();let v=await _D(d,w.buffer,e,t);i.push(...v)}return{results:i,diskBytes:o}}async function HD(n){try{let e=await Mh(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 UD(n){let e=new yt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=FD(n),{skillNames:i,targets:o}=await jD(n,t,r),{results:s,diskBytes:a}=await $D(i,o,n.force||!1,e);return e.stop(),ro(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function Zh(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,i=n.filter(s=>!s.success).length,o=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>BD(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function BD(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var er=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function WD(n){let e=n;return n instanceof er?n.code:e.code??e.name??"UnknownError"}function da(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 ua(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=WD(a),a}finally{let a={event:D.SkillOperation,subAction:n,args:t,...s};await I.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function VD(n){return ua("add",async()=>{let{diskBytes:e,results:t}=await UD(n);return{diskUsage:Dt(e),...n.skill?{skillName:n.skill}:{},...Zh(t)}},da("add",n))}function GD(n){let{resolvedPath:e,resolvedProject:t}=io(n.path,n.project,n.agent);return t&&fn(t,"Project directory"),e&&fn(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function zD(n,e){let t=new yt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=GD(e);t.stop();let o=await qD(e,n,r,i);return t.stop(),ro(o),o}catch(r){throw t.stop(),r}}function Yh(n,e=""){if(n.length===0)throw new er("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function la(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Wh(n,r.agent):await Gh(n,r.project,r.agent);t.push(i)}return t}async function qD(n,e,t,r){if(t)return[await Vh(e,t)];if(r&&n.agent){let a=(await to(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return la(e,a)}if(r){let s=await no();Yh(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return la(e,a)}if(n.agent){let a=(await to(n.agent)).map(c=>({type:"agent",agent:c}));return la(e,a)}let i=await no();Yh(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return la(e,o)}function YD(n,e){if(!e){console.log(n.enName);return}console.log(Jh(n.enName)),console.log(Xh(n.description));let t=xh(n.enName);t.length>0&&console.log(LD(`Installed for: ${t.join(", ")}`)),console.log()}async function JD(n){let e=new yt;try{e.start("Fetching skills...");let t=await sa(),r=await gd(t);if(r.length===0)return e.stop(),console.log(Kh("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r)YD(i,n.long===!0);return{resultTotal:r.length}}finally{e.stop()}}async function KD(n){let e=new yt;try{e.start("Searching skills...");let t=await sa(),r=await yd(n,t);if(r.length===0)return console.log(Kh(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(Jh(i.enName)),console.log(Xh(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}}var so=new ND("skills").description("Manage HarmonyOS skills");so.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await ua("list",()=>JD(n),da("list",n))}catch(e){console.error(oo(e.message)),process.exit(1)}});so.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await ua("find",()=>KD(n),da("find"))}catch(e){console.error(oo(e.message)),process.exit(1)}});so.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 VD(n)}catch(e){console.error(oo(e.message)),process.exit(1)}});so.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 ua("remove",async()=>{let e=await zD(n.skill,n);return{skillName:n.skill,...Zh(e)}},da("remove",n))}catch(e){console.error(oo(e.message)),process.exit(1)}});var Qh=so;import{Command as ZD,InvalidArgumentError as ma}from"commander";import{cyan as pa}from"colorette";function tr(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Pr(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Dd=[800,1500,2500];function XD(n){return new Promise(e=>setTimeout(e,n))}function eg(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var $r=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1293
- `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(pa(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(pa(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(pa(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new T(`Device '${e}' not found.
1286
+ `;function FI(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function jI(n){let e=n.trim();if(!ug.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${ug.join(", ")}`);return e}function mg(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function fg(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!$I(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function $I(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function HI(n,e,t,r,i){return Number(fg(n,e,t,r,i))}function UI(n){let e=n.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 BI(n){let e=n.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${n}" 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 "${n}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function WI(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(Tt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(Tt("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(i=>t(i)===r)){console.error(Ne("--os-version does not match any downloaded image (exact string required).")),console.log(Tt("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var VI=["Name","Status","Serial","Device Type","OS Version"];function GI(n,e,t){return{cells:[n.name,t?"running":"stopped",e??"-",n.deviceType??"-",n.osVersion??"-"],highlight:t}}async function zI(n,e){let t=await Promise.all(e.map(async r=>{let i=await Rr(n,r,MI);return[r,i]}));return new Map(t)}async function qI(n){let e=await nd(n),t=await zI(n,e);return{serials:e,params:t}}function YI(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function JI(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&YI(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function KI(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(i=>GI(i.emu,i.serial,i.effectiveRunning))}async function XI(n,e,t){try{let[r,i]=await Promise.all([n.listEmulators(),qI(e)]);if(r.length===0){t?.stop(),console.log(Tt(" No emulator instances found."));return}let o=r.filter(l=>l.isRunning).map(l=>l.name),{productSerialMap:s,hvdSerialMap:a}=JI(i.serials,i.params,o);t?.stop();let c=KI(r,s,a);console.log(mt(VI,c))}catch(r){Yf(t,`Failed to list emulators: ${r.message}`)}}function gg(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(Ne(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Xi(s.stdout)),s.stderr&&console.error(Xi(s.stderr))}return r}var ZI=2e3,QI=6e4;async function eD(n,e){let t=Ce(e);return(await rd(n)).some(i=>Ce(i)===t)}async function hg(n,e,t,r=QI,i=ZI){let o=Date.now()+r;for(;Date.now()<o;){if(await eD(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function tD(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(Tt(`Emulator "${t}" is already running.`));return}console.log(Hr(`Starting emulator "${t}"...`));let i=await hg(e,t,!0);console.log(i?Qi(`Emulator "${t}" started successfully.`):Tt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function nD(n,e,t){let r=await Promise.allSettled(t.map(o=>tD(n,e,o)));gg(r,t,"start")&&process.exit(1)}async function yg(n,e){let t=e.trim();if(!Ui(t))return t;let r=await ae.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function rD(n,e,t){let r=await yg(e,t);if(console.log(Hr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(Tt(`Emulator "${r}" is already stopped.`));return}let o=await hg(e,r,!1);console.log(o?Qi(`Emulator "${r}" stopped successfully.`):Tt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function iD(n,e,t){let r=await Promise.allSettled(t.map(o=>rD(n,e,o)));gg(r,t,"stop")&&process.exit(1)}async function rt(){try{let n=await A.new();return{manager:jr.from(n),toolProvider:n}}catch(n){throw new Error(`Failed to initialize emulator: ${n.message}`,{cause:n})}}async function zt(n,e,t){let r={event:D.CommandExecuted,args:["emulator",t,"--target"]},i=Date.now(),o=!0,s=null;try{let a=FI(n.target),c=e(),{manager:l,toolProvider:d}=await rt(),g=await yg(d.hdcPath,a);await l.controlEmulator(g,c),console.log(Qi(`Emulator "${a}" operation completed.`))}catch(a){o=!1,s=W(a);let c=n.target?.trim()||"<unknown>";console.error(Ne(`Failed to operate emulator "${c}": ${a.message}`)),process.exitCode=1}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await I.track(r,a)}}function oD(n){let e=[];return Zs(e,"longitude",n.longitude,-180,180,8),Zs(e,"latitude",n.latitude,-90,90,8),Zs(e,"altitude",n.altitude,-1e4,1e4,2),Zs(e,"bearing",n.direction,0,359.99,2,"--direction"),hd(e,"Specify one geolocation option.")}function sD(n){let e=[];return Ji(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),Ji(e,"humidity",n.humidity,0,100,!1),Ji(e,"temperature",n.temperature,-273.1,100,!1),Ji(e,"steps",n.steps,0,1e4,!0),Ji(e,"heartrate",n.heartrate,0,255,!0),hd(e,"Specify one sensor option.")}function hd(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function Zs(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:fg(s,t,r,i,o)})}function Ji(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?mg(s,t,r,i):HI(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function aD(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:mg("--level",n.level,1,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),hd(e,"Specify --level or --status.")}var we=new gd("emulator").description("Manage emulator instances"),cD=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Qs(n){let e=new Zi("--device-type <type>","Emulator device type").choices([...cD]);return n?e.makeOptionMandatory():e}function $r(n,e){for(let t of e)if(t in n)return n[t]}function Ki(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function pg(n){let e=Ki(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var lD=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],dD="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function wg(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function vg(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=Ki($r(i,["osVersion","OsVersion","OSVersion","os_version"])),s=Ki($r(i,["deviceType","DeviceType","device_type"])),a=pg($r(i,["downloaded","Downloaded","isDownloaded"])),c=Ki($r(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=Ki($r(i,["releaseType","ReleaseType","release_type"])),d=pg($r(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function uD(n){let e=n.trim();if(!e)return!0;let t=wg(e);return t===null?!1:t.length===0?!0:vg(t,!0).length===0}function pD(n,e){let t=n.trim();if(!t)return"";let r=wg(t);if(!r)return n.trimEnd();let i=vg(r,e);return mt(lD,i)}var ea=new gd("image").description("HarmonyOS emulator system images (download, list, remove)");ea.command("download").description("Download system image").addOption(Qs(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await rt();try{await md(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof nt&&(console.error(Ne(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(Ne("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(Ne("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(Ne(`Failed to download system image: ${r.message}`)),process.exit(1)}});ea.command("remove").description("Remove a downloaded system image").addOption(Qs(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await rt();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(Ne(`Failed to remove system image: ${t.message}`)),process.exit(1)}});ea.command("list").description("List system images").addOption(Qs(!1)).option("--all","List all images (local and remote)").addOption(new Zi("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await rt();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(uD(r)){console.log(Tt(dD));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=pD(r,n.all===!0);console.log(i)}catch(t){console.error(Ne(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});we.addCommand(ea);var ta=new gd("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");ta.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await rt(),e=await ag(n.emulatorPath,n.sdkPath);process.exit(e)});ta.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await rt(),e=await dg(n.emulatorPath,n.sdkPath);process.exit(e)});ta.action(async()=>{let{toolProvider:n}=await rt(),e=await lg(n.emulatorPath,n.sdkPath);process.exit(e)});we.addCommand(ta);we.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>zt(n,()=>({type:"shake"}),"shake"));we.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>zt(n,()=>({type:"power"}),"power"));we.command("rotate").description("Rotate emulator").addOption(new Zi("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new fd("<direction>").choices(["left","right"])).action((n,e)=>zt(e,()=>({type:"rotation",direction:n}),"rotate"));we.command("volume").description("Change volume").addOption(new Zi("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new fd("<direction>").choices(["up","down"])).action((n,e)=>zt(e,()=>({type:"volume",direction:n}),"volume"));we.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",_I).action((n,e)=>zt(e,()=>({type:"folded-state",state:jI(n)}),"fold"));we.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <1-100>","Battery level, SOC (integer 1-100)").addOption(new Zi("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>zt(n,()=>aD(n),"battery"));we.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>zt(n,()=>oD(n),"geolocation"));we.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new fd("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return zt(e,()=>t[n],"scene")});we.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>zt(n,()=>sD(n),"sensor"));we.command("list").description("List all emulator instances").action(async()=>{let{manager:n,toolProvider:e}=await rt(),t=OI({text:"Listing emulators\u2026",color:"cyan"}).start();await XI(n,e.hdcPath,t)});we.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await rt();try{await pd(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof nt&&(console.error(Ne(r.message)),process.exit(1)),r}n?.length||(console.error(Ne("Error: missing required argument 'names'")),process.exit(1)),await nD(e,t.hdcPath,n)});we.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await rt();n?.length||(console.error(Ne("Error: missing required argument 'names'")),process.exit(1)),await iD(e,t.hdcPath,n)});var Sg=we.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(Qs(!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");Sg.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
1287
+ ${Tt("Tip: ")}${Xi("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1288
+ ${Hr('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1289
+ ${Hr('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1290
+ `)}});Sg.action(async(n,e)=>{try{UI(n),BI(e.osVersion);let{manager:t}=await rt(),r=await t.listDownloadedImageOsVersions();WI(e.osVersion,r),console.log(Hr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Qi(`Emulator "${n}" created successfully.`))}catch(t){console.error(Ne(`${t.message}`)),process.exit(1)}});we.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await rt();console.log(Hr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(Qi(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(Ne(r.message)),r.stdout&&console.error(Xi(r.stdout)),r.stderr&&console.error(Xi(r.stderr)),process.exit(1)}});var bg=we;import{Command as OD}from"commander";import{red as Ed,cyan as Rt}from"colorette";import*as Wg from"readline";import*as Ug from"crypto";import*as Eg from"http";import*as Pg from"crypto";import{URL as mD}from"url";var na=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=Eg.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new mD(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;e.method==="POST"?this.readBody(e,t,s):this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}readBody(e,t,r){let i="",o=0,s=65536;e.on("data",a=>{if(o+=a.length,o>s){e.destroy(new Error("Request body too large"));return}i+=a.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,r,i)})}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&Pg.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 Oe from"fs";import*as hn from"path";import{homedir as SD}from"os";var qt={};hb(qt,{LocalCrypto:()=>qt,decryptForLocalStorage:()=>yD,decryptForLocalStorageFromDirectory:()=>wD,encryptForLocalStorage:()=>hD,isEncryptedBlob:()=>vD});import*as ee from"fs";import*as Ae from"path";import*as Le from"crypto";import*as Ig from"os";import{homedir as Dg}from"os";var De=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var eo=Gn.ALGORITHM,Ag=Gn.IV_LENGTH,to=Gn.KEY_LENGTH,no=Gn.KEY_LENGTH,rr=Gn.KEK_VERSIONS,ra=process.env.DEVECO_CLI_DATA_DIR||Ae.join(Dg(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME),ia=Ae.join(Dg(),".local","share",Ee.APP_NAME,"keys"),Ur=Ae.join(ra,Ee.KEY_FILE_NAME);function Cg(n){return Ig.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 yd(n){return Ae.join(ia,`${n}.bin`)}function Tg(){if(!ee.existsSync(ra))try{ee.mkdirSync(ra,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new De(Cg(ra)):n}if(!ee.existsSync(ia))try{ee.mkdirSync(ia,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new De(Cg(Ae.dirname(ia))):n}}function Rg(){Tg();for(let n of rr){let e=yd(n);ee.existsSync(e)||ee.writeFileSync(e,Le.randomBytes(to),{mode:384})}}function kg(n){if(!rr.includes(n))throw new Error(`Invalid kekId: ${n}`);Rg();let e=yd(n),t=ee.readFileSync(e);if(t.length===to)return t;let r=Le.randomBytes(to);return ee.writeFileSync(e,r,{mode:384}),r}function wd(n,e){let t=Le.randomBytes(Ag),r=kg(e),i=Le.createCipheriv(eo,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:eo,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function xg(n,e){return Ng(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function Ng(n,e,t,r){let i=Le.createDecipheriv(eo,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function Lg(n,e){return Ng(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function fD(){if(Rg(),ee.existsSync(Ur))return;let n=Le.randomBytes(no),e=wd(n,rr[0]);ee.writeFileSync(Ur,JSON.stringify(e,null,2),{mode:384})}function Og(){fD();let n=JSON.parse(ee.readFileSync(Ur,"utf8")),e=xg(n,kg(n.kekId));if(e.length===no)return e;let t=Le.randomBytes(no),r=wd(t,rr[0]);return ee.writeFileSync(Ur,JSON.stringify(r,null,2),{mode:384}),t}function gD(){Tg();for(let t of rr){let r=yd(t);ee.existsSync(r)||ee.writeFileSync(r,Le.randomBytes(to),{mode:384})}if(ee.existsSync(Ur))return;let n=Le.randomBytes(no),e=wd(n,rr[0]);ee.writeFileSync(Ur,JSON.stringify(e,null,2),{mode:384})}function hD(n){let e=Og(),t=Le.randomBytes(Ag),r=Le.createCipheriv(eo,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:eo,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function yD(n){try{return Lg(n,Og())}catch{throw gD(),new Error("Failed to decrypt local ciphertext")}}function wD(n,e){let t=Ae.join(e,Ee.KEY_FILE_NAME),r=JSON.parse(ee.readFileSync(t,"utf8"));if(!rr.includes(r.kekId))throw new Error(`Invalid kekId: ${r.kekId}`);let i=Ae.join(e,"keys",`${r.kekId}.bin`),o=Ae.resolve(i),s=Ae.resolve(Ae.join(e,"keys"));if(!o.startsWith(s+Ae.sep)&&o!==s)throw new Error("kekId resolves outside the keys directory");let a=ee.readFileSync(o);if(a.length!==to)throw new Error("Invalid external root key");let c=xg(r,a);if(c.length!==no)throw new Error("Invalid external data encryption key");return Lg(n,c)}function vD(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 ft(){return process.env.DEVECO_CLI_AUTH_SOURCE===Ee.AUTH_SOURCE_DEVECO_CODE}var oa=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||hn.join(SD(),Ee.CONFIG_DIR_NAME,Ee.APP_NAME);return hn.join(e,Ee.TOKEN_FILE_NAME)}ensureConfigDir(){let e=hn.dirname(this.getLocalTokenFilePath());Oe.existsSync(e)||Oe.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=qt.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Oe.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return ft()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!ft())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;let t=hn.resolve(e);try{let r=hn.join(t,Ee.TOKEN_FILE_NAME);if(!Oe.existsSync(r))return null;let i=JSON.parse(Oe.readFileSync(r,"utf8"));return qt.isEncryptedBlob(i)?qt.decryptForLocalStorageFromDirectory(i,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Oe.existsSync(e))return null;let t=JSON.parse(Oe.readFileSync(e,"utf8"));return qt.isEncryptedBlob(t)?qt.decryptForLocalStorage(t):null}catch(t){let r=t.code;return r==="EACCES"||r==="EPERM"||r==="ENOENT"||await this.clearToken(),null}}async clearToken(){if(ft()){m("clearToken: skipped, session managed by DevEco Code");return}let e=this.getLocalTokenFilePath();try{Oe.existsSync(e)&&Oe.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Yt=new oa;import{exec as bD}from"child_process";import{promisify as ED}from"util";var PD=ED(bD);async function Mg(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;case"openharmony":console.log("\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4EE5\u4E0B\u767B\u5F55\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A"),console.log(n);return;default:t=`xdg-open "${n}"`;break}try{await PD(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import CD from"axios";import{getProxyForUrl as ID}from"proxy-from-env";function DD(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 vd=class{client;constructor(){let e={timeout:Ci.HTTP_TIMEOUT_MS,headers:{"User-Agent":rs.USER_AGENT,"accept-language":rs.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=CD.create(e),this.client.interceptors.request.use(t=>{let r=ID(t.url??"");return t.proxy=r?DD(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}
1291
+ ${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}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){return JSON.parse(e.data)}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}},O=new vd;function _g(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Jt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},ir={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},sa={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},AD={[Jt.CHINA]:ir.CHINA,[Jt.RUSSIA]:ir.RUSSIA,[Jt.EUROPE]:ir.EUROPE,[Jt.SINGAPORE]:ir.CHINA},TD={[sa.CHINA]:Jt.CHINA,[sa.SINGAPORE]:Jt.SINGAPORE,[sa.EUROPE]:Jt.EUROPE,[sa.RUSSIA]:Jt.RUSSIA};function Fg(n){return AD[n]??ir.CHINA}function jg(n){return TD[n]??Jt.CHINA}var Sd=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=jg(t),c={tempToken:s,site:a,version:Ee.API_VERSION,appid:o},l=`${r}/${i}`,d=await O.get(l,{params:c});if(d.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${d.statusCode}`);let g=d.data.trim();if(!_g(g))throw new Error("Invalid jwtToken format");return g}},$g=new Sd;var bd=class{async checkJwtToken(e,t,r=!1){let i={refresh:String(r),jwtToken:e},o=`${t}/${J.JWT_TOKEN_CHECK_PATH}`,s=await O.get(o,{headers:i});if(s.statusCode!==200)throw new Error(`Failed to check jwtToken: ${s.statusCode}`);return O.parseJson(s)}async refreshToken(e){let t=await Yt.loadJwtToken();return t?this.refreshTokenWithToken(t,e):null}async refreshTokenWithToken(e,t){try{let r={refresh:"true",jwtToken:e},i=`${t}/${J.JWT_TOKEN_CHECK_PATH}`,o=await O.get(i,{headers:r});if(o.statusCode!==200)return null;let s=O.parseJson(o);return!s.status||!s.userInfo?null:{accessToken:s.userInfo.accessToken,refreshToken:s.userInfo.refreshToken??""}}catch(r){let i=r;return console.error(`Failed to refresh token: ${i.code??""} ${i.message??""}`),null}}async getUserInfoFromJwt(e,t,r=!1){let i=await this.checkJwtToken(e,t,r);return!i.status||!i.userInfo||!i.userInfo.accessToken?(m("jwtToken invalid."),await Yt.clearToken(),null):{userId:i.userInfo.userId??"",userName:i.userInfo.name??"",accessToken:i.userInfo.accessToken,refreshToken:i.userInfo.refreshToken??"",jwtToken:e,countryCode:i.userInfo.nationalCode,language:Fg(i.userInfo.nationalCode),isRealName:String(i.userInfo.realName)==="true"}}async fetchUserInfo(e,t){let r=await Yt.loadJwtToken();return r?this.getUserInfoFromJwt(r,e,t):null}},Br=new bd;import RD from"querystring";import{spawn as kD}from"child_process";function Hg(n){try{let e=JSON.stringify({signInfo:[{agrType:Ii.PRIVACY_ID,country:"CN",language:"zh_CN",isAgree:!0}]}),t=RD.stringify({nsp_svc:"as.user.sign",access_token:n,request:e}),r=kD("curl",["-s","-X","POST",Ii.TMS_URL,"-H","Content-Type: application/x-www-form-urlencoded","-d",t,"--max-time","5","-o","/dev/null","-w","%{http_code}"],{detached:!0,stdio:["ignore","pipe","ignore"]});r.unref(),r.stdout?.on("data",i=>{let o=i.toString().trim();o==="200"?m("Agreement sign reported successfully"):m(`Agreement sign failed: HTTP ${o}`)}).on("error",()=>{})}catch(e){m(`Agreement sign error: ${e.message}`)}}var aa=class{config;server=null;constructor(e){this.config={...Di,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${ft()}`);let e=this.generateClientSecret();this.server=new na(e,J.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 De("Non-China accounts are not supported.");let r=await $g.getJwtToken(t.tempToken,t.siteId,J.CN_LOGIN_URL,this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await Br.getUserInfoFromJwt(r,J.CN_LOGIN_URL);if(!i)throw new De("Login failed: failed to get user info");return m(`User info received: ${i.userName}`),await Yt.saveJwtToken(r),m("JWT token saved"),Hg(i.accessToken),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){return await this.getUserInfo(!0)!==null}async logout(){let e=await Yt.loadJwtToken();if(!e)return!1;let r=`${J.CN_LOGIN_URL}/${this.config.logoutUrl}?jwtToken=${e}`;try{await O.post(r,{timeout:5e3})}catch{m("Logout: server notification failed, local token cleared")}finally{await Yt.clearToken()}return!0}async getUserInfo(e=!0){return Br.fetchUserInfo(J.CN_LOGIN_URL,e)}generateClientSecret(){return Ug.randomUUID().replace(/-/g,"")}async openLoginPage(e,t){let i=`${J.CN_LOGIN_URL}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await Mg(i)}async refreshToken(){return Br.refreshToken(J.CN_LOGIN_URL)}},Te=new aa;function ND(){return ft()?"Not logged in. Please login via DevEco Code first.":"Please run `devecocli auth login` first."}function LD(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var ca=class{config;constructor(e){this.config={...Di,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Br.fetchUserInfo(J.CN_LOGIN_URL,!0);if(!e)throw new De(ND());let t=await this.fetchTeamList(e.accessToken,e.userId),r=LD(t);return{userId:e.userId,teamList:r}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl,i;try{i=await O.get(r,{headers:{oauth2Token:e,uid:t,source:"cli",lang:ir.CHINA},timeout:15e3})}catch(o){let s=o.message;throw s.includes("401")?new De("Token expired. Run `devecocli auth login` again."):new Error(`Network error while listing teams: ${s}`,{cause:o})}if(i.statusCode!==200)throw new Error(`Failed to list teams: HTTP ${i.statusCode}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}},Bg=new ca;async function yn(){return Bg.listTeams()}async function la(n,e,t){let r=Date.now(),i=!0,o=null;try{await e()}catch(s){i=!1,o=W(s);let a=t?.(s);if(a)throw a}finally{let s={duration_ms:Date.now()-r,success:i,error_code:o};await I.track(n,s)}}function MD(n){if(n.length===0)return Rt("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
1292
+ `)}function _D(){return new Promise(n=>{let e=Wg.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}async function FD(n){if(n||!process.stdin.isTTY){console.log(Rt(n?"Opening browser for login... (--no-prompt: Enter confirmation skipped)":"Non-interactive terminal: opening browser for login without the Enter confirmation..."));return}console.log(Rt("Press Enter to open browser for login (or pass --no-prompt to skip)...")),await _D()}var ro=new OD("auth").description("Authentication commands (login, logout, status, team)");ro.command("login").description("Log in to your Huawei Developer account").option("--no-prompt","Open the browser immediately without the interactive Enter confirmation (agents and non-interactive terminals)").action(async n=>{if(ft()){console.log(Ed("Login is managed by DevEco Code. Login from DevEco Code instead."));return}let e={event:D.CommandExecuted,args:["auth","login"]};await la(e,async()=>{let t=await Te.getUserInfo();if(t){console.log(Rt(`Already logged in, User Name:${t.userName}`));return}console.log(Rt("Starting login process...")),await FD(n.prompt===!1);let r=await Te.login();console.log(Rt(`Login successful. Logged in as ${r.userName}.`))},t=>{throw t instanceof De||(t instanceof Error?t.message:String(t)).includes("Network connection failed")?t:new Error("Login failed",{cause:t})})});ro.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(ft()){console.log(Ed("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}let n={event:D.CommandExecuted,args:["auth","logout"]};await la(n,async()=>{let e=await Te.logout();console.log(e?Rt("Logout successful"):Rt("Already logged out."))},e=>new Error("Logout failed",{cause:e}))});ro.command("status").description("Show the currently logged-in user").action(async()=>{let n={event:D.CommandExecuted,args:["auth","status"]};await la(n,async()=>{let e=await Te.getUserInfo();if(!e){console.log(Rt("Not logged in"));return}console.log(Rt(`Current user: ${e.userName}`))},e=>e)});var jD=ro.command("team").description("Team-related commands");jD.command("list").description("List team accounts the current user has joined").action(async()=>{let n={event:D.CommandExecuted,args:["auth","team","list"]};await la(n,async()=>{let e=await yn();console.log(MD(e.teamList))},e=>{if(e instanceof De){console.log(Ed(e.message));return}throw e})});var Vg=ro;import{Command as XD}from"commander";import{green as ZD,red as co,cyan as ph,yellow as mh,dim as fh}from"colorette";import QD from"p-limit";import $D from"ora";var gt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=$D(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 Gg from"fs";import*as zg from"path";var qg=["DevEco"];async function da(){let n=await O.get(ct.TAGS_API_URL),t=ua(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 HD(n){let e=[],t=ct.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await O.post(ct.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=ua(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function Pd(n){let e=new Map,t=n.map(i=>HD(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!qg.includes(o.name)))}async function UD(n,e){let t=await O.post(ct.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:ct.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return ua(t,"Skills API").data.list}async function Cd(n,e){let t=new Map,r=e.map(o=>UD(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!qg.includes(s.name)))}function Yg(n){let e=[],t=Ht();for(let[,r]of Object.entries(t)){let i=zg.join(r.path,n);Gg.existsSync(i)&&e.push(r.displayName)}return e.sort()}function ua(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=O.parseJson(n);if(t.code!==ct.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Jg(n){let e=`${ct.SKILL_API_BASE}/${n}/checksum`,t=await O.get(e);return ua(t,"Checksum API").data}import BD from"adm-zip";import WD from"crypto";import Xg from"fs";import le from"path";import{fileURLToPath as VD}from"url";import{red as GD}from"colorette";var Kt=Xg.promises;function Id(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Kg(n,e){let t=le.resolve(e),r=le.resolve(n),i=le.relative(r,t);if(i.startsWith("..")||le.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Dd(n){return le.isAbsolute(n)?n:le.resolve(process.cwd(),n)}function zD(n){return WD.createHash("sha256").update(n).digest("hex")}async function qD(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=zD(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Zg(n){let e=`${ct.SKILL_API_BASE}/${n}/install?format=zip`,t=await O.getBinary(e),r=await Jg(n);return await qD(t,r),t}async function YD(n,e,t){Id(t);let r=new BD(n),i=r.getEntries();try{await Kt.stat(e)}catch{await Kt.mkdir(e,{recursive:!0})}let o=le.join(e,t);Kg(e,o);for(let s of i){let a=le.join(o,s.entryName);Kg(o,a)}r.extractAllTo(o,!0)}async function Ad(n){let e=Ht();if(!e[n])throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(e).join(", ")}`);let r=ge[n];try{return await Kt.access(r),!0}catch{return!1}}function Td(n){return Ht()[n].path}function Rd(n,e){let r=Ht()[e],i="projectPath"in r?r.projectPath:le.join("."+e,"skills");return le.join(n,i)}async function JD(n,e,t){Id(e);let r=le.join(n,e);try{if(await Kt.access(r),t)await Kt.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 kd(n,e,t){await YD(n,e,t),console.log(`Skill ${t} installed to ${le.join(e,t)}.`)}async function xd(n,e,t){let r=le.join(e,t);await Kt.mkdir(r,{recursive:!0});let i=le.join(r,le.basename(n));await Kt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Qg(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(GD(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function Wr(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await JD(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Qg(n,i,"Installation failed")}}async function Nd(n,e){try{Id(n);let t=await e(),r=le.join(t,n);try{await Kt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Kt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Qg(n,t,"Removal failed")}}async function eh(n,e,t,r=!1){return Wr(n,()=>Td(e),i=>kd(t,i,n),r)}async function th(n,e,t,r=!1){return Wr(n,()=>t,i=>kd(e,i,n),r)}async function nh(n,e,t,r,i=!1){return Wr(n,()=>Rd(t,r),o=>kd(e,o,n),i)}async function rh(n,e,t,r=!1){return Wr(n,()=>Td(t),i=>xd(e,i,n),r)}async function ih(n,e,t,r,i=!1){return Wr(n,()=>Rd(t,r),o=>xd(e,o,n),i)}async function oh(n,e,t,r=!1){return Wr(n,()=>t,i=>xd(e,i,n),r)}async function sh(n,e){return Nd(n,()=>Td(e))}async function ah(n,e){return Nd(n,()=>e)}async function ch(n,e,t){return Nd(n,()=>Rd(e,t))}function lh(){let e=le.dirname(VD(import.meta.url));for(;;){let t=le.join(e,"SKILL.md");if(Xg.existsSync(t))return t;let r=le.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import dh from"fs";import{cyan as KD}from"colorette";async function io(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Ad(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function oo(){let n=[],e=Ht();for(let t of Object.keys(e))await Ad(t)&&n.push(t);return n}function so(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(KD("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function wn(n,e,t){if(!dh.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!dh.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function ao(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Dd(n):void 0,resolvedProject:e?Dd(e):void 0}}async function pa(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await io(n.agent)).map(a=>({project:t,agent:a})):t?i=(await oo()).map(a=>({project:t,agent:a})):n.agent?r=await io(n.agent):r=await oo(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function eA(n){let e=await da();if(n.all)return(await Pd(e)).map(r=>r.enName);{let r=(await Cd(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new or("errorCode",`Skill "${n.skill}" not found`);return[r.enName]}}async function tA(n,e,t,r){let i=[];if(t.customPath){let o=await th(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await eh(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await nh(n,e,o,s,r);i.push(a)}return i}function nA(n){if(n.all&&n.skill)throw new or("errorCode","`--all` and `--skill` cannot be specified together.");if(!n.all&&!n.skill)throw new or("errorCode","Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=ao(n.path,n.project,n.agent);return t&&wn(t,"Project directory",n.force),e&&wn(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function rA(n,e,t){let r=await pa(n,e,t);return{skillNames:await eA(n),targets:r}}async function iA(n,e,t,r){let i=[],o=0,s=n.length,a=QD(5),c=n.map(l=>a(()=>oA(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(co(`${d}: Download failed - ${w.error}`)),i.push({success:!1});continue}o+=w.buffer.length,r.stop();let v=await tA(d,w.buffer,e,t);i.push(...v)}return{results:i,diskBytes:o}}async function oA(n){try{let e=await Zg(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 sA(n){let e=new gt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=nA(n),{skillNames:i,targets:o}=await rA(n,t,r),{results:s,diskBytes:a}=await iA(i,o,n.force||!1,e);return e.stop(),so(s),{diskBytes:a,results:s}}catch(t){throw e.stop(),t}}function gh(n){let e=n.length,t=n.filter(s=>s.success&&!s.skipped).length,r=n.filter(s=>s.skipped).length,i=n.filter(s=>!s.success).length,o=[...new Set(n.filter(s=>!s.success&&typeof s.error=="string").map(s=>aA(s.error)))];return{opTotal:e,opSuccess:t,opFailed:i,opSkipped:r,...o.length>0?{failedErrors:o}:{}}}function aA(n){let e=/^([A-Za-z_][A-Za-z0-9_-]*)/.exec(n.trim());return e?e[1].slice(0,32):"error"}var or=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function cA(n){let e=n;return n instanceof or?n.code:e.code??e.name??"UnknownError"}function fa(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 ga(n,e,t){let r=Date.now(),i=!0,o=null,s={};try{s=await e()}catch(a){throw i=!1,o=cA(a),a}finally{let a={event:D.SkillOperation,subAction:n,args:t,...s};await I.track(a,{duration_ms:Date.now()-r,success:i,error_code:o})}}function lA(n){return ga("add",async()=>{let{diskBytes:e,results:t}=await sA(n);return{diskUsage:It(e),...n.skill?{skillName:n.skill}:{},...gh(t)}},fa("add",n))}function dA(n){let{resolvedPath:e,resolvedProject:t}=ao(n.path,n.project,n.agent);return t&&wn(t,"Project directory"),e&&wn(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function uA(n,e){let t=new gt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=dA(e);t.stop();let o=await pA(e,n,r,i);return t.stop(),so(o),o}catch(r){throw t.stop(),r}}function uh(n,e=""){if(n.length===0)throw new or("errorCode",`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function ma(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await sh(n,r.agent):await ch(n,r.project,r.agent);t.push(i)}return t}async function pA(n,e,t,r){if(t)return[await ah(e,t)];if(r&&n.agent){let a=(await io(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return ma(e,a)}if(r){let s=await oo();uh(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return ma(e,a)}if(n.agent){let a=(await io(n.agent)).map(c=>({type:"agent",agent:c}));return ma(e,a)}let i=await oo();uh(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return ma(e,o)}function mA(n,e){if(!e){console.log(n.enName);return}console.log(ph(n.enName)),console.log(fh(n.description));let t=Yg(n.enName);t.length>0&&console.log(ZD(`Installed for: ${t.join(", ")}`)),console.log()}async function fA(n){let e=new gt;try{e.start("Fetching skills...");let t=await da(),r=await Pd(t);if(r.length===0)return e.stop(),console.log(mh("No skills available.")),{resultTotal:0};e.succeed(`Fetched ${r.length} skills`);for(let i of r)mA(i,n.long===!0);return{resultTotal:r.length}}finally{e.stop()}}async function gA(n){let e=new gt;try{e.start("Searching skills...");let t=await da(),r=await Cd(n,t);if(r.length===0)return console.log(mh(`No skills found matching '${n}'.`)),e.stop(),{resultTotal:0,queryLen:n.length,keyword:n};e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(ph(i.enName)),console.log(fh(i.description)),console.log();return{resultTotal:r.length,queryLen:n.length,keyword:n}}finally{e.stop()}}var lo=new XD("skills").description("Manage HarmonyOS skills");lo.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async n=>{try{await ga("list",()=>fA(n),fa("list",n))}catch(e){console.error(co(e.message)),process.exit(1)}});lo.command("find <keyword>").description("Search skills by keyword").action(async n=>{try{await ga("find",()=>gA(n),fa("find"))}catch(e){console.error(co(e.message)),process.exit(1)}});lo.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 lA(n)}catch(e){console.error(co(e.message)),process.exit(1)}});lo.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 ga("remove",async()=>{let e=await uA(n.skill,n);return{skillName:n.skill,...gh(e)}},fa("remove",n))}catch(e){console.error(co(e.message)),process.exit(1)}});var hh=lo;import{Command as yA,InvalidArgumentError as ya}from"commander";import{cyan as ha}from"colorette";function sr(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Tr(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Ld=[800,1500,2500];function hA(n){return new Promise(e=>setTimeout(e,n))}function yh(){return b()?"No active devices found. Connect a physical device.":"No active devices found. Start an emulator or connect a physical device."}var Vr=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=ae.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1293
+ `)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(ha(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(ha(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(ha(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new T(`Device '${e}' not found.
1294
1294
  Available devices:
1295
- ${o}`,"Device not found.")}if(r.length===1){let i=r[0];return m(pa(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new T("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(eg());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(eg());return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),x.assertBundleNameStrict(r);let i=await se(e,["-t",t,"shell","pidof",r]),o=tr(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let i=await se(e,["-t",t,"shell","hilog","-G",r]),o=tr(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(x.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(x.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(x.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(x.assertHilogKeyword(e.keyword),r.push("-e",x.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await jm(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+Dd.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,i,o),a.exitCode===0||Pr(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Dd[c]}ms`),await XD(Dd[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{m(`Callback triggered when an error occurs during ${r}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=tr(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=x.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=x.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=tr(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=x.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=x.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=tr(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,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new T(`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,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].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 i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=tr(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return m(`Crash logs list output:
1295
+ ${o}`,"Device not found.")}if(r.length===1){let i=r[0];return m(ha(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new T("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(yh());return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error(yh());return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),x.assertBundleNameStrict(r);let i=await se(e,["-t",t,"shell","pidof",r]),o=sr(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let i=await se(e,["-t",t,"shell","hilog","-G",r]),o=sr(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(x.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(x.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(x.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(x.assertHilogKeyword(e.keyword),r.push("-e",x.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await tf(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+Ld.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,i,o),a.exitCode===0||Tr(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Ld[c]}ms`),await hA(Ld[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{m(`Callback triggered when an error occurs during ${r}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=sr(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=x.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=x.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=sr(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=x.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=x.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=sr(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,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new T(`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,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].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 i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=sr(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return m(`Crash logs list output:
1296
1296
  ${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
1297
- `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return x.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=tr(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as Ad,red as ng}from"colorette";import QD from"ora";function eA(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 tA(n){return{event:D.CommandExecuted,args:eA(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function nA(n){return n instanceof T?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function rA(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=nA(o),console.error(ng(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o).catch(()=>{})}}function iA(n){try{return x.parsePositiveInteger(n,"tail")}catch{throw new ma("`tail` must be a positive integer.")}}function tg(n,e){try{return x.parseDurationToSeconds(n,e)}catch{throw new ma(`${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 oA(n){try{return x.assertHilogLevel(n),n}catch{throw new ma("`level` must be one of: D, I, W, E, F.")}}function sA(n){try{return x.assertBundleNameStrict(n),n}catch(e){throw new ma(e.message)}}function aA(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");x.assertRelativeTimeRange(n.from,n.to)}async function cA(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function lA(n,e,t,r){let i=x.filterLogsByRelativeWindow(n,t,r);return e.tail?x.getLastLines(i,e.tail):i}var dA=new ZD("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(ng(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",oA).option("--bundle-name <bundle-name>","Filter by application bundle name",sA).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",iA).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>tg(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>tg(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await rA(tA(n),()=>uA(n))});async function uA(n){let e=QD({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{aA(n);let r=n.from,i=n.to,o=await A.new(),s=new $r(o),a=await s.selectDevice(n.device);if(!a)throw new T("No active devices found.","No active devices found.");m(Ad(`deviceId: ${a}`)),m(Ad(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Ad("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await cA(s,a,n,r,i);t(),n.crash&&c&&(c=lA(c,n,r,i)),c&&console.log(c)}finally{t()}}var rg=dA;import co from"path";import Yt from"fs";import kd from"process";import pg from"os";import{Command as CA}from"commander";import{green as cg,red as Td,cyan as IA,yellow as lg}from"colorette";import ue from"fs-extra";import H from"path";import*as og from"os";import{fileURLToPath as pA}from"url";var ig={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"}},mA=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function fA(){let n=import.meta.url,e=pA(n);if(e.includes("dist")){let o=H.dirname(e),s=H.dirname(o);return H.join(s,"templates","application")}let t=H.dirname(e),r=H.dirname(t),i=H.dirname(r);return H.join(i,"templates","application")}function sg(n,e){ue.mkdirSync(e,{recursive:!0});for(let t of ue.readdirSync(n,{withFileTypes:!0})){let r=H.join(n,t.name),i=H.join(e,t.name);if(t.isDirectory()){sg(r,i);continue}ue.existsSync(i)||(ue.mkdirSync(H.dirname(i),{recursive:!0}),ue.copyFileSync(r,i))}}function ao(n,e){let t=ue.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&ue.writeFileSync(n,r,"utf-8")}function hA(n){if(ig[n])return ig[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function gA(n,e){if(e===22)return;let t=hA(e);t&&(ao(H.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),ao(H.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),ao(H.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function yA(n){return mA.filter(t=>!ue.existsSync(H.join(n,t))).length===0}function wA(){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 vA(n){return og.platform()==="darwin"?H.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):H.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function SA(n,e){let t=vA(e);if(!ue.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[i,o]of r){let s=H.join(t,i),a=H.join(n,o);ue.existsSync(s)&&(ue.mkdirSync(H.dirname(a),{recursive:!0}),ue.copyFileSync(s,a))}return!0}function bA(n){let e=wA(),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 i=H.join(n,r);ue.mkdirSync(H.dirname(i),{recursive:!0}),ue.writeFileSync(i,e)}}function EA(n,e){e&&SA(n,e)||bA(n)}function PA(n){let e=[H.join(n,"gitignore.txt"),H.join(n,"entry","gitignore.txt")];for(let t of e)if(ue.existsSync(t)){let r=H.dirname(t);ue.renameSync(t,H.join(r,".gitignore"))}}function ag(n,e,t,r,i){let o=fA();if(!ue.existsSync(o))throw new Error(`Template directory not found: ${o}`);ue.mkdirSync(n,{recursive:!0}),sg(o,n),PA(n),EA(n,i),ao(H.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),ao(H.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),gA(n,r);let s=yA(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function DA(n){if(n.length<1||n.length>200)throw new pe("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new pe("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function mg(n){if(pg.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function dg(n){if(n.length===0)throw new pe("errorCode","Project path cannot be empty.");if(n.length>120)throw new pe("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=pg.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new pe("errorCode",`Project path can only contain ${o}.`)}let r=mg(n);if(/[\u4e00-\u9fff]/.test(r))throw new pe("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new pe("errorCode","Project path cannot end with a dot (.)")}function AA(n){let e=n,t=co.parse(n).root;for(;e!==t;){if(Yt.existsSync(e))return e;e=co.dirname(e)}return Yt.existsSync(t)?t:null}function ug(n){let e=AA(n);if(!e)throw new pe("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Yt.accessSync(e,Yt.constants.W_OK)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=co.join(e,`.deveco_write_test_${Date.now()}`);try{Yt.writeFileSync(t,"test"),Yt.unlinkSync(t)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function TA(n){return`com.example.${n.toLowerCase()}`}function RA(n,e){if(e){let i=mg(e),o=co.resolve(i);if(Yt.existsSync(o)){if(Yt.readdirSync(o).length>0)throw new pe("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else ug(o);return o}let t=kd.cwd(),r=co.join(t,n);if(Yt.existsSync(r))throw new pe("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return ug(r),r}function kA(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. No SDK detected; default supported range is API 17-${r}.`);return i}return t!==void 0?t:23}async function xA(){try{return await A.new()}catch(n){console.error(lg(`Toolchain not found: ${n.message}`)),console.log(lg("Use placeholder API level instead."));return}}var pe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function Rd(n,e,t,r){let i={event:D.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},o={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(i,o).catch(()=>{})}function NA(n){console.log(`
1298
- `+cg("Project created successfully.")),console.log(`Project root: ${n.projectRoot}`),console.log(`App name: ${n.appName}`),console.log(`Bundle name: ${n.bundleName}`),console.log(`API level: ${n.apiLevel}`),console.log(cg("Template integrity check passed."))}var LA=new CA("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 n=>{let e=Date.now();try{n.appName||(console.error(Td("Error: --app-name is required")),await Rd(e,!1,"errorCode",n),kd.exit(1));let t=n.appName;DA(t);let r=n.bundleName||TA(t);x.assertBundleNameStrict(r),n.projectPath&&dg(n.projectPath);let i=RA(t,n.projectPath);dg(i),console.log(IA("Initializing project...")),console.log(`Project path: ${i}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${r}`);let o=await xA(),s=kA(n,o);console.log(`API level: ${s}`);let a=o?.devecoStudioPath,c=ag(i,t,r,s,a);NA(c),await Rd(e,!0,null,n)}catch(t){let r=t,o=t instanceof pe?t.code:r.code??r.name??"UnknownError";console.error(Td(`
1299
- Failed to create project.`)),console.error(Td(r.message)),await Rd(e,!1,o,n),kd.exit(1)}}),fg=LA;import{Command as HA}from"commander";import{red as UA,cyan as Eg}from"colorette";import OA from"fs";import fa from"path";import{cyan as MA}from"colorette";import*as ha from"smol-toml";var Hr=OA.promises;async function _A(n){try{let e=await Hr.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function FA(n){try{let e=await Hr.readFile(n,"utf8");return e.trim()===""?{}:ha.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function jA(n,e){let t=fa.dirname(n);await Hr.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Hr.writeFile(n,r,"utf8")}async function $A(n,e){let t=fa.dirname(n);await Hr.mkdir(t,{recursive:!0});let r=ha.stringify(e);await Hr.writeFile(n,r,"utf8")}function hg(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function gg(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function yg(n,e){return n.format==="codex"?FA(e):_A(e)}async function wg(n,e,t){return n.format==="codex"?$A(e,t):jA(e,t)}async function vg(n,e,t=!1){let r=cn[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(cn).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await yg(r,r.globalConfigPath);if(hg(i,r.mcpServersKey,It)&&!t)return console.log(`MCP server ${It} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=gs(r,void 0);return gg(i,r.mcpServersKey,It,o,t),await wg(r,r.globalConfigPath,i),console.log(`MCP server ${It} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function xd(n,e,t=!1){let r=cn[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(cn).join(", ")}`};let i=fa.isAbsolute(r.projectConfigPath)?r.projectConfigPath:fa.join(e,r.projectConfigPath);try{let o=await yg(r,i);if(hg(o,r.mcpServersKey,It)&&!t)return console.log(`MCP server ${It} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=gs(r,e);return gg(o,r.mcpServersKey,It,s,t),await wg(r,i,o),console.log(`MCP server ${It} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function Sg(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(MA("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var Nd="deveco-cli";async function BA(n,e,t){if(n.customPath)return[await Bh(Nd,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Uh(Nd,e,s,a,t.force)),...n.agents.map(s=>()=>Hh(Nd,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}function WA(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function bg(n,e,t,r){await I.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function VA(n,e,t,r,i){let o={event:D.SkillConfigOperation,subAction:"install",targetType:r?"path":i?"project":"global",agents:WA(n)},s=Date.now();try{let a=await BA(n,e,t),c=a.every(l=>l.success||l.skipped);return await bg(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await bg(o,s,!1,c),a}}async function GA(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await xd(o,i,t);r.push(s)}for(let i of n.agents){let o=await xd(i,e,t);r.push(o)}return r}async function zA(n,e){let t=[];for(let r of n){if(!cn[r])continue;let o=await vg(r,process.cwd(),e);t.push(o)}return t}async function qA(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await GA(s,e,r):await zA(s.agents,r);a.length>0&&(console.log(Eg("MCP Configuration:")),Sg(a))}async function YA(n,e,t){let r={event:D.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},i=Date.now(),o=!0,s=null;try{await qA(n,e,t)}catch(a){throw o=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await I.track(r,a)}}async function JA(n){if(n.skill&&n.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}=io(n.path,n.project,n.agent);t&&fn(t,"Project directory",n.force),e&&fn(e,"Directory",n.force);let r=await ca(n,e,t);if(n.mcp){await YA(r,t,n);return}let i=zh(),o=await VA(r,i,n,e,t);console.log(),o.length>0&&(console.log(Eg("Skill Installation:")),ro(o))}var KA=new HA("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 n=>{try{await JA(n)}catch(e){console.error(UA(e.message)),process.exit(1)}}),Pg=KA;import{Command as VT}from"commander";import{McpServer as AT}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as TT}from"@modelcontextprotocol/sdk/server/stdio.js";import*as bn from"path";import*as jg from"fs";import{z as me}from"zod";var ga=class{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:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>r(i)))}};function Ld(){return new ga}import*as vt from"fs";import*as Fe from"path";import{z as Md}from"zod";function Cg(n){return"method"in n&&!("id"in n)}import{spawn as XA}from"child_process";import{EventEmitter as ZA}from"events";import*as Ur from"fs";import*as Ig from"path";var hn=class extends ZA{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Ig.join(this.config.logPath,"lspLog");return Ur.existsSync(t)||Ur.mkdirSync(t,{recursive:!0}),Ur.existsSync(this.config.indexingDataLocation)||Ur.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let i=z(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=this.config.nodePath;f.info(`[LspClient] nodePath: ${s}`),this.process=XA(s,o,{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,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let i=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${i}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${i}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1297
+ `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return x.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=sr(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as Od,red as vh}from"colorette";import wA from"ora";function vA(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 SA(n){return{event:D.CommandExecuted,args:vA(n),logType:n.crash?"crash":"common",level:n.level??"ALL",bundleName:n.bundleName??"ALL"}}function bA(n){return n instanceof T?n.traceMessage:n instanceof Error?n.code??n.name:"UnknownError"}async function EA(n,e){let t=Date.now(),r=!0,i=null;try{await e()}catch(o){r=!1,i=bA(o),console.error(vh(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(n,o).catch(()=>{})}}function PA(n){try{return x.parsePositiveInteger(n,"tail")}catch{throw new ya("`tail` must be a positive integer.")}}function wh(n,e){try{return x.parseDurationToSeconds(n,e)}catch{throw new ya(`${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 CA(n){try{return x.assertHilogLevel(n),n}catch{throw new ya("`level` must be one of: D, I, W, E, F.")}}function IA(n){try{return x.assertBundleNameStrict(n),n}catch(e){throw new ya(e.message)}}function DA(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.");x.assertRelativeTimeRange(n.from,n.to)}async function AA(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function TA(n,e,t,r){let i=x.filterLogsByRelativeWindow(n,t,r);return e.tail?x.getLastLines(i,e.tail):i}var RA=new yA("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(vh(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",CA).option("--bundle-name <bundle-name>","Filter by application bundle name",IA).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",PA).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>wh(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",n=>wh(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await EA(SA(n),()=>kA(n))});async function kA(n){let e=wA({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};e.start();try{DA(n);let r=n.from,i=n.to,o=await A.new(),s=new Vr(o),a=await s.selectDevice(n.device);if(!a)throw new T("No active devices found.","No active devices found.");m(Od(`deviceId: ${a}`)),m(Od(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(Od("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await AA(s,a,n,r,i);t(),n.crash&&c&&(c=TA(c,n,r,i)),c&&console.log(c)}finally{t()}}var Sh=RA;import po from"path";import Xt from"fs";import Fd from"process";import Rh from"os";import{Command as WA}from"commander";import{green as Ih,red as Md,cyan as VA,yellow as Dh}from"colorette";import ue from"fs-extra";import H from"path";import*as Eh from"os";import{fileURLToPath as xA}from"url";var bh={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"}},NA=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function LA(){let n=import.meta.url,e=xA(n);if(e.includes("dist")){let o=H.dirname(e),s=H.dirname(o);return H.join(s,"templates","application")}let t=H.dirname(e),r=H.dirname(t),i=H.dirname(r);return H.join(i,"templates","application")}function Ph(n,e){ue.mkdirSync(e,{recursive:!0});for(let t of ue.readdirSync(n,{withFileTypes:!0})){let r=H.join(n,t.name),i=H.join(e,t.name);if(t.isDirectory()){Ph(r,i);continue}ue.existsSync(i)||(ue.mkdirSync(H.dirname(i),{recursive:!0}),ue.copyFileSync(r,i))}}function uo(n,e){let t=ue.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&ue.writeFileSync(n,r,"utf-8")}function OA(n){if(bh[n])return bh[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function MA(n,e){if(e===22)return;let t=OA(e);t&&(uo(H.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),uo(H.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),uo(H.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function _A(n){return NA.filter(t=>!ue.existsSync(H.join(n,t))).length===0}function FA(){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 jA(n){return Eh.platform()==="darwin"?H.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):H.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function $A(n,e){let t=jA(e);if(!ue.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[i,o]of r){let s=H.join(t,i),a=H.join(n,o);ue.existsSync(s)&&(ue.mkdirSync(H.dirname(a),{recursive:!0}),ue.copyFileSync(s,a))}return!0}function HA(n){let e=FA(),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 i=H.join(n,r);ue.mkdirSync(H.dirname(i),{recursive:!0}),ue.writeFileSync(i,e)}}function UA(n,e){e&&$A(n,e)||HA(n)}function BA(n){let e=[H.join(n,"gitignore.txt"),H.join(n,"entry","gitignore.txt")];for(let t of e)if(ue.existsSync(t)){let r=H.dirname(t);ue.renameSync(t,H.join(r,".gitignore"))}}function Ch(n,e,t,r,i){let o=LA();if(!ue.existsSync(o))throw new Error(`Template directory not found: ${o}`);ue.mkdirSync(n,{recursive:!0}),Ph(o,n),BA(n),UA(n,i),uo(H.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),uo(H.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),MA(n,r);let s=_A(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function GA(n){if(n.length<1||n.length>200)throw new pe("errorCode",`App name length must be 1-200 characters. Current: ${n.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(n))throw new pe("errorCode","Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function kh(n){if(Rh.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function Ah(n){if(n.length===0)throw new pe("errorCode","Project path cannot be empty.");if(n.length>120)throw new pe("errorCode",`Project path cannot exceed 120 characters (current: ${n.length}).`);let e=Rh.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new pe("errorCode",`Project path can only contain ${o}.`)}let r=kh(n);if(/[\u4e00-\u9fff]/.test(r))throw new pe("errorCode","Project path cannot contain Chinese characters.");if(r.endsWith("."))throw new pe("errorCode","Project path cannot end with a dot (.)")}function zA(n){let e=n,t=po.parse(n).root;for(;e!==t;){if(Xt.existsSync(e))return e;e=po.dirname(e)}return Xt.existsSync(t)?t:null}function Th(n){let e=zA(n);if(!e)throw new pe("errorCode",`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Xt.accessSync(e,Xt.constants.W_OK)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}let t=po.join(e,`.deveco_write_test_${Date.now()}`);try{Xt.writeFileSync(t,"test"),Xt.unlinkSync(t)}catch{throw new pe("errorCode",`No write permission for directory '${e}'. Cannot create project here.`)}}function qA(n){return`com.example.${n.toLowerCase()}`}function YA(n,e){if(e){let i=kh(e),o=po.resolve(i);if(Xt.existsSync(o)){if(Xt.readdirSync(o).length>0)throw new pe("errorCode",`Directory '${o}' is not empty. Cannot create project here.`)}else Th(o);return o}let t=Fd.cwd(),r=po.join(t,n);if(Xt.existsSync(r))throw new pe("errorCode",`Directory '${r}' already exists. Cannot create project here.`);return Th(r),r}function JA(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new pe("errorCode",`Invalid API version ${n.apiLevel}. No SDK detected; default supported range is API 17-${r}.`);return i}return t!==void 0?t:23}async function KA(){try{return await A.new()}catch(n){console.error(Dh(`Toolchain not found: ${n.message}`)),console.log(Dh("Use placeholder API level instead."));return}}var pe=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};async function _d(n,e,t,r){let i={event:D.CommandExecuted,args:["create"],apiLevel:r?.apiLevel??null},o={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(i,o).catch(()=>{})}function XA(n){console.log(`
1298
+ `+Ih("Project created successfully.")),console.log(`Project root: ${n.projectRoot}`),console.log(`App name: ${n.appName}`),console.log(`Bundle name: ${n.bundleName}`),console.log(`API level: ${n.apiLevel}`),console.log(Ih("Template integrity check passed."))}var ZA=new WA("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 n=>{let e=Date.now();try{n.appName||(console.error(Md("Error: --app-name is required")),await _d(e,!1,"errorCode",n),Fd.exit(1));let t=n.appName;GA(t);let r=n.bundleName||qA(t);x.assertBundleNameStrict(r),n.projectPath&&Ah(n.projectPath);let i=YA(t,n.projectPath);Ah(i),console.log(VA("Initializing project...")),console.log(`Project path: ${i}`),console.log(`App name: ${t}`),console.log(`Bundle name: ${r}`);let o=await KA(),s=JA(n,o);console.log(`API level: ${s}`);let a=o?.devecoStudioPath,c=Ch(i,t,r,s,a);XA(c),await _d(e,!0,null,n)}catch(t){let r=t,o=t instanceof pe?t.code:r.code??r.name??"UnknownError";console.error(Md(`
1299
+ Failed to create project.`)),console.error(Md(r.message)),await _d(e,!1,o,n),Fd.exit(1)}}),xh=ZA;import{Command as oT}from"commander";import{red as sT,cyan as $h}from"colorette";import QA from"fs";import wa from"path";import{cyan as eT}from"colorette";import*as va from"smol-toml";var Gr=QA.promises;async function tT(n){try{let e=await Gr.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function nT(n){try{let e=await Gr.readFile(n,"utf8");return e.trim()===""?{}:va.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function rT(n,e){let t=wa.dirname(n);await Gr.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await Gr.writeFile(n,r,"utf8")}async function iT(n,e){let t=wa.dirname(n);await Gr.mkdir(t,{recursive:!0});let r=va.stringify(e);await Gr.writeFile(n,r,"utf8")}function Nh(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function Lh(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function Oh(n,e){return n.format==="codex"?nT(e):tT(e)}async function Mh(n,e,t){return n.format==="codex"?iT(e,t):rT(e,t)}async function _h(n,e,t=!1){let r=pn[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(pn).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await Oh(r,r.globalConfigPath);if(Nh(i,r.mcpServersKey,Ct)&&!t)return console.log(`MCP server ${Ct} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Ss(r,void 0);return Lh(i,r.mcpServersKey,Ct,o,t),await Mh(r,r.globalConfigPath,i),console.log(`MCP server ${Ct} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function jd(n,e,t=!1){let r=pn[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(pn).join(", ")}`};let i=wa.isAbsolute(r.projectConfigPath)?r.projectConfigPath:wa.join(e,r.projectConfigPath);try{let o=await Oh(r,i);if(Nh(o,r.mcpServersKey,Ct)&&!t)return console.log(`MCP server ${Ct} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Ss(r,e);return Lh(o,r.mcpServersKey,Ct,s,t),await Mh(r,i,o),console.log(`MCP server ${Ct} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function Fh(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(eT("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var $d="deveco-cli";async function aT(n,e,t){if(n.customPath)return[await oh($d,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>ih($d,e,s,a,t.force)),...n.agents.map(s=>()=>rh($d,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}function cT(n){return[...new Set([...n.agents,...n.projectAgents.map(({agent:e})=>e)])]}async function jh(n,e,t,r){await I.track(n,{duration_ms:Date.now()-e,success:t,error_code:r}).catch(()=>{})}async function lT(n,e,t,r,i){let o={event:D.SkillConfigOperation,subAction:"install",targetType:r?"path":i?"project":"global",agents:cT(n)},s=Date.now();try{let a=await aT(n,e,t),c=a.every(l=>l.success||l.skipped);return await jh(o,s,c,c?null:"SKILL_INSTALL_FAILED"),a}catch(a){let c=a instanceof Error?a.code??a.name:"UnknownError";throw await jh(o,s,!1,c),a}}async function dT(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await jd(o,i,t);r.push(s)}for(let i of n.agents){let o=await jd(i,e,t);r.push(o)}return r}async function uT(n,e){let t=[];for(let r of n){if(!pn[r])continue;let o=await _h(r,process.cwd(),e);t.push(o)}return t}async function pT(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await dT(s,e,r):await uT(s.agents,r);a.length>0&&(console.log($h("MCP Configuration:")),Fh(a))}async function mT(n,e,t){let r={event:D.Init,subAction:"install",targetType:e?"project":"global",agentName:t.agent},i=Date.now(),o=!0,s=null;try{await pT(n,e,t)}catch(a){throw o=!1,s=a instanceof Error?a.code??a.name:"UnknownError",a}finally{let a={duration_ms:Date.now()-i,success:o,error_code:s};await I.track(r,a)}}async function fT(n){if(n.skill&&n.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}=ao(n.path,n.project,n.agent);t&&wn(t,"Project directory",n.force),e&&wn(e,"Directory",n.force);let r=await pa(n,e,t);if(n.mcp){await mT(r,t,n);return}let i=lh(),o=await lT(r,i,n,e,t);console.log(),o.length>0&&(console.log($h("Skill Installation:")),so(o))}var gT=new oT("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 n=>{try{await fT(n)}catch(e){console.error(sT(e.message)),process.exit(1)}}),Hh=gT;import{Command as lR}from"commander";import{McpServer as zT}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as qT}from"@modelcontextprotocol/sdk/server/stdio.js";import*as In from"path";import*as ty from"fs";import{z as me}from"zod";var Sa=class{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:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>r(i)))}};function Hd(){return new Sa}import*as yt from"fs";import*as _e from"path";import{z as Bd}from"zod";function Uh(n){return"method"in n&&!("id"in n)}import{spawn as hT}from"child_process";import{EventEmitter as yT}from"events";import*as zr from"fs";import*as Bh from"path";var vn=class extends yT{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Bh.join(this.config.logPath,"lspLog");return zr.existsSync(t)||zr.mkdirSync(t,{recursive:!0}),zr.existsSync(this.config.indexingDataLocation)||zr.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let i=z(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=this.config.nodePath;f.info(`[LspClient] nodePath: ${s}`),this.process=hT(s,o,{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,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let i=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${i}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${i}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1300
1300
  \r
1301
1301
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
1302
1302
  \r
1303
- `);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),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){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 r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){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 gn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,r),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),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 ya=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Br=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function R(n){return typeof n=="object"&&n!==null}var Dg=20*1e3,QA=30*1e3,wa=class{client;nextRequestId=1;stopOnce=null;callbacks=new Br;requestCallbacks=new gn;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new hn(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(300),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++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,et);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(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,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=QA){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(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 i=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)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,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){R(e)&&this.broadcastToClients({jsonrpc:N,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Dg,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Dg}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:N,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var va=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)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Od(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)}},Od=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var eT={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"},tT={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"},L={...eT,...tT},yn={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"},Ag=new Set([1e3,2e3,3e3,3001]);function nT(n){if(!R(n))return!1;let e=n.textDocument;return R(e)&&typeof e.uri=="string"}function rT(n){return R(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function iT(n){return R(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 Sa=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Br;requestCallbacks=new gn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new hn(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:N,method:L.EXIT,params:{}}),yn.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(L.BROADCAST),this.callbacks.register(L.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(L.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(L.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(L.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:N,method:L.INITIALIZED,params:{editors:e}}),yn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:N,id:0,result:{}}),yn.EMPTY)}sendAsyncRequest(e,t,r,i){if(!R(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!nT(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=pt(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!rT(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),L.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!R(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:N,method:L.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),yn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=pt(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new va(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,L.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),yn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=pt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,L.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),yn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=pt(e);f.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.DID_CLOSE,params:{textDocument:{uri:r}}}),yn.DID_CLOSE)}getDiagnosticMessage(e){let t=pt(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);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,L.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:N,method:L.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 L.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(L.MODULE_INIT_FINISH),this.callbacks.unregister(L.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case L.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${iT(t.params)}`),this.callbacks.invoke(L.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case L.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case L.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case L.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case L.ON_ASYNC_HOVER:this.handleAsyncResponse(t,L.HOVER);return;case L.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,L.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case L.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,L.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;R(t)&&R(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,r={jsonrpc:N,method:L.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!R(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,L.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(Ag)&&this.finalizeDiagnostic(t,L.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import fo from"path";import*as Aa 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 Pa=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Ca=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ia=class{typeSetting=new Pa;parameterNames=new Ca};var Da=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=z(Aa.dirname(t)),this.indexingDataLocation=z(i),this.loggerPath=z(Aa.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new ba;gutterIconsSetting=new Ea;inlayHintsSetting=new Ia;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Tg from"path";var lo=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(z(Tg.join(e,"src","main","resources")))}};var oT="OS",Wr=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${oT}`;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 lo(e)):this.buildProfileParam=new lo}toString(){return JSON.stringify(this)}};var Vr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Re from"path";import*as qr from"fs";var Ta=class{modulePath;dependencies={};dynamicDependencies={}};var nr=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 Gr=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 Jt from"path";import*as Ra from"fs";var zr=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:ut.OH_PACKAGE_JSON5},uo=`${_.HVIGOR_CACHE}/${_.DEPENDENCY}`,rr=`${_.DEPENDENCY}${_.JSON5}`,aq=ut.SYNC_OUTPUT_PATH;var po=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Jt.join(this.dependencyPath,_.OH_PACKAGE_JSON5),r=qe(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(!R(e))return r;let i=e[t];if(!R(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){f.error(`${o} package dependency value is not String ${t}`);continue}let a=new zr;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=Jt.normalize(Jt.join(this.modulePath,_.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Jt.isAbsolute(s)){r.dependencyPath=o;return}i||(o=Jt.resolve(this.modulePath,s)),Ra.existsSync(o)&&Ra.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as mo from"fs";import*as wn from"path";import sT from"json5";var ka=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";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 wn.join(this.projectPath,_.OH_MODULES_PATH,_.OHPM_PATH,_.LOCK_JSON5_FILE)}readLockFile(e){if(!mo.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=mo.readFileSync(e,"utf8"),r=sT.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!R(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 r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.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(!R(e))return t;for(let[r,i]of Object.entries(e)){if(!R(i)){f.error(`${r} value is not json object`);continue}typeof i.storePath=="string"&&t.set(r,i.storePath)}return t}getDependencyList(e,t,r){if(!R(e))return[];for(let[i,o]of Object.entries(e))if(R(o)){let s=typeof o.name=="string"?o.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!R(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!R(s))return[];for(let[a,c]of Object.entries(s)){if(!R(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new zr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),o.push(h)}return o}parseDependencyPath(e,t,r,i,o){let s=wn.resolve(this.projectPath,wn.join(t,_.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=wn.isAbsolute(a)?a:wn.resolve(this.projectPath,a);mo.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Rg(n){return R(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var ir=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Ht(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Re.join(t,uo),i=Re.join(r,rr);if(!qr.existsSync(r)||!qr.existsSync(i)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new Gr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);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];Rg(l)&&(this.parseSingleModule(l,r,o,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=[],r=this.projectPath,i=Re.join(r,uo),o=Re.join(i,rr);if(!qr.existsSync(i)||!qr.existsSync(o))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 Gr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,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(!Rg(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=Re.resolve(this.projectPath,l.srcPath),w=Re.join(i,d),v=z(h),k=this.buildModuleDependencies(d,v,w,a);k.moduleName=d,t.push(k)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=Re.resolve(this.projectPath,e.srcPath),a=Re.join(t,o),c=z(s),l=new Wr(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new Vr(h),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Gr(this.projectPath,e,t);po.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Ta;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new nr(o);for(let o of e.finalDynamicDependencies)i[o.name]=new nr(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=Re.join(e,_.OH_PACKAGE_JSON5);if(!qr.existsSync(r))return;po.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 ka(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Re.join(e,"src","main","module.json5"),i=qe(r);if(!R(i)||!R(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(R(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)R(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Re.join(e,"src","main","resources","base","profile","main_pages.json"),r=qe(t);return!R(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!R(t)||!R(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=Re.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=qe(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!R(t)||!R(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!R(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Re.join(this.projectPath,"build-profile.json5");this.buildProfileCache=qe(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!R(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 Yr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var kg=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(kg||{}),xg=()=>Object.values(kg).filter(n=>typeof n=="number");var Na=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var La=class{applyEdit=!0;workspaceEdit=new Na;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new xa(xg());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Yr;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 Ng=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(Ng||{}),Lg=()=>Object.values(Ng).filter(n=>typeof n=="number");var Fa=class{completionItemKind=new Ma(Lg());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 Yr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var $a=class{workspace=new La;textDocument=new ja;notebookDocument=null;window=null;general=null;experimental=null};var Ha=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Ua=class{messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?fo.resolve(fo.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=bm(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new wa(t):new Sa(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let i=pt(this.rootUri),o=new Da(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new ir(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=As(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Ha(i,o,new $a),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,et),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:N,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),f.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:N,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",et),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=R(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:N,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(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 ir(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),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(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,h)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new nr({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Wr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Vr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=Er(fo.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Er(fo.join(t,"default/openharmony/ets/api")),o=Er(fo.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Cg(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 _e from"path";import{createHash as cT}from"crypto";import{EventEmitter as lT}from"events";var Ba=class extends lT{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 i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),f.info(`[ConfigFileWatcher] Stopped watching: ${i}`));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,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=_e.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=_e.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=_e.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=_e.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,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,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=qe(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.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);Kt.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=_e.resolve(this.projectRoot,o.srcPath),a=_e.join(s,_.OH_PACKAGE_JSON5);Kt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return _e.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Kt.readFileSync(t,"utf-8");return cT("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Kt.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),f.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,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as vn from"fs";import*as wt from"path";import{createHash as dT}from"crypto";import{EventEmitter as uT}from"events";var Wa=class extends uT{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=wt.join(t,uo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!vn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=vn.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),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 z(wt.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===_.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===rr)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=wt.join(this.depMapDir,r);vn.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=wt.join(this.depMapDir,_.OH_PACKAGE_JSON5),r=wt.join(this.depMapDir,rr),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:wt.join(this.depMapDir,s.name,_.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!vn.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=wt.join(this.depMapDir,rr);try{let r=qe(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.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 i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return z(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=wt.join(this.depMapDir,a.name,_.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=wt.join(this.depMapDir,o,_.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=vn.readFileSync(t,"utf-8");return dT("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as pT}from"child_process";var mT=["install","--all"];async function fT(n,e,t,r){return new Promise(i=>{let o=pT(n,e,{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1303
+ `);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),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){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 r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){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 Sn=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)i(t,r),this.callbacks.delete(e);else{let o=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),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 ba=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var qr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function R(n){return typeof n=="object"&&n!==null}var Wh=20*1e3,wT=30*1e3,Ea=class{client;nextRequestId=1;stopOnce=null;callbacks=new qr;requestCallbacks=new Sn;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new vn(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(300),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++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,Qe);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new ba(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=wT){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(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 i=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)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,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){R(e)&&this.broadcastToClients({jsonrpc:N,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Wh,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Wh}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:N,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Pa=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)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new Ud(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)}},Ud=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var vT={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"},ST={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"},L={...vT,...ST},bn={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"},Vh=new Set([1e3,2e3,3e3,3001]);function bT(n){if(!R(n))return!1;let e=n.textDocument;return R(e)&&typeof e.uri=="string"}function ET(n){return R(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function PT(n){return R(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 Ca=class n{client;isInitialized=!1;stopOnce=null;callbacks=new qr;requestCallbacks=new Sn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new vn(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:N,method:L.EXIT,params:{}}),bn.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(L.BROADCAST),this.callbacks.register(L.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(L.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(L.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(L.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:N,method:L.INITIALIZED,params:{editors:e}}),bn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:N,id:0,result:{}}),bn.EMPTY)}sendAsyncRequest(e,t,r,i){if(!R(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!bT(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=dt(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!ET(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),L.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!R(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:N,method:L.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),bn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=dt(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Pa(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,L.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),bn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=dt(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,L.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),bn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=dt(e);f.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:N,method:L.DID_CLOSE,params:{textDocument:{uri:r}}}),bn.DID_CLOSE)}getDiagnosticMessage(e){let t=dt(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);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,L.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:N,method:L.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 L.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(L.MODULE_INIT_FINISH),this.callbacks.unregister(L.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case L.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${PT(t.params)}`),this.callbacks.invoke(L.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case L.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case L.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case L.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case L.ON_ASYNC_HOVER:this.handleAsyncResponse(t,L.HOVER);return;case L.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,L.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case L.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,L.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;R(t)&&R(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,r={jsonrpc:N,method:L.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!R(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,L.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(Vh)&&this.finalizeDiagnostic(t,L.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import yo from"path";import*as xa from"path";var Ia=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Da=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Aa=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Ta=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ra=class{typeSetting=new Aa;parameterNames=new Ta};var ka=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=z(xa.dirname(t)),this.indexingDataLocation=z(i),this.loggerPath=z(xa.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Ia;gutterIconsSetting=new Da;inlayHintsSetting=new Ra;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Gh from"path";var mo=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(z(Gh.join(e,"src","main","resources")))}};var CT="OS",Yr=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${CT}`;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 mo(e)):this.buildProfileParam=new mo}toString(){return JSON.stringify(this)}};var Jr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Re from"path";import*as Zr from"fs";var Na=class{modulePath;dependencies={};dynamicDependencies={}};var ar=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 Kr=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 Zt from"path";import*as La from"fs";var Xr=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:lt.OH_PACKAGE_JSON5},fo=`${_.HVIGOR_CACHE}/${_.DEPENDENCY}`,cr=`${_.DEPENDENCY}${_.JSON5}`,Rq=lt.SYNC_OUTPUT_PATH;var go=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Zt.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(!R(e))return r;let i=e[t];if(!R(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){f.error(`${o} package dependency value is not String ${t}`);continue}let a=new Xr;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=Zt.normalize(Zt.join(this.modulePath,_.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Zt.isAbsolute(s)){r.dependencyPath=o;return}i||(o=Zt.resolve(this.modulePath,s)),La.existsSync(o)&&La.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as ho from"fs";import*as En from"path";import IT from"json5";var Oa=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";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 En.join(this.projectPath,_.OH_MODULES_PATH,_.OHPM_PATH,_.LOCK_JSON5_FILE)}readLockFile(e){if(!ho.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=ho.readFileSync(e,"utf8"),r=IT.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!R(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 r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.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(!R(e))return t;for(let[r,i]of Object.entries(e)){if(!R(i)){f.error(`${r} value is not json object`);continue}typeof i.storePath=="string"&&t.set(r,i.storePath)}return t}getDependencyList(e,t,r){if(!R(e))return[];for(let[i,o]of Object.entries(e))if(R(o)){let s=typeof o.name=="string"?o.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!R(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!R(s))return[];for(let[a,c]of Object.entries(s)){if(!R(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",g=new Xr;g.name=a,g.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(g,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(g.storePath=this.storePathMap.get(w)||""),o.push(g)}return o}parseDependencyPath(e,t,r,i,o){let s=En.resolve(this.projectPath,En.join(t,_.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=En.isAbsolute(a)?a:En.resolve(this.projectPath,a);ho.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function zh(n){return R(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var lr=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Wt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Re.join(t,fo),i=Re.join(r,cr);if(!Zr.existsSync(r)||!Zr.existsSync(i)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new Kr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);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];zh(l)&&(this.parseSingleModule(l,r,o,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=[],r=this.projectPath,i=Re.join(r,fo),o=Re.join(i,cr);if(!Zr.existsSync(i)||!Zr.existsSync(o))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 Kr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,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(!zh(l))continue;let d=l.name;if(s&&!s.has(d))continue;let g=Re.resolve(this.projectPath,l.srcPath),w=Re.join(i,d),v=z(g),k=this.buildModuleDependencies(d,v,w,a);k.moduleName=d,t.push(k)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=Re.resolve(this.projectPath,e.srcPath),a=Re.join(t,o),c=z(s),l=new Yr(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new Jr(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new Kr(this.projectPath,e,t);go.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Na;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new ar(o);for(let o of e.finalDynamicDependencies)i[o.name]=new ar(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=Re.join(e,_.OH_PACKAGE_JSON5);if(!Zr.existsSync(r))return;go.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 Oa(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Re.join(e,"src","main","module.json5"),i=ze(r);if(!R(i)||!R(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(R(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)R(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Re.join(e,"src","main","resources","base","profile","main_pages.json"),r=ze(t);return!R(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!R(t)||!R(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=Re.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=ze(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!R(t)||!R(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!R(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Re.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),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!R(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 Qr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var qh=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(qh||{}),Yh=()=>Object.values(qh).filter(n=>typeof n=="number");var _a=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Fa=class{applyEdit=!0;workspaceEdit=new _a;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ma(Yh());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Qr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var ja=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var $a=class{constructor(e=[]){this.valueSet=e}valueSet};var Ha=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Jh=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(Jh||{}),Kh=()=>Object.values(Jh).filter(n=>typeof n=="number");var Ua=class{completionItemKind=new $a(Kh());completionItem=new Ha;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Ba=class{synchronization=new ja;completion=new Ua;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 Qr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Wa=class{workspace=new Fa;textDocument=new Ba;notebookDocument=null;window=null;general=null;experimental=null};var Va=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Ga=class{messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?yo.resolve(yo.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=jm(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new Ea(t):new Ca(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let i=dt(this.rootUri),o=new ka(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new lr(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=xs(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Va(i,o,new Wa),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Qe),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:N,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),f.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:N,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Qe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=R(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:N,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(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 lr(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),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(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new ar({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Yr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Jr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=Ar(yo.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Ar(yo.join(t,"default/openharmony/ets/api")),o=Ar(yo.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,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:N,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:N,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!Uh(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 Qt from"fs";import*as Me from"path";import{createHash as AT}from"crypto";import{EventEmitter as TT}from"events";var za=class extends TT{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 i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),f.info(`[ConfigFileWatcher] Stopped watching: ${i}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Qt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Qt.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=Me.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=Me.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=Me.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=Me.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,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,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=ze(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Me.join(this.projectRoot,_.OH_PACKAGE_JSON5);Qt.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=Me.resolve(this.projectRoot,o.srcPath),a=Me.join(s,_.OH_PACKAGE_JSON5);Qt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Me.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Qt.readFileSync(t,"utf-8");return AT("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Qt.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Me.basename(t),relativePath:Me.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as Pn from"fs";import*as ht from"path";import{createHash as RT}from"crypto";import{EventEmitter as kT}from"events";var qa=class extends kT{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ht.join(t,fo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Pn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Pn.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),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 z(ht.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===_.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===cr)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=ht.join(this.depMapDir,r);Pn.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=ht.join(this.depMapDir,_.OH_PACKAGE_JSON5),r=ht.join(this.depMapDir,cr),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:ht.join(this.depMapDir,s.name,_.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Pn.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=ht.join(this.depMapDir,cr);try{let r=ze(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.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 i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return z(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=ht.join(this.depMapDir,a.name,_.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=ht.join(this.depMapDir,o,_.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=Pn.readFileSync(t,"utf-8");return RT("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as xT}from"child_process";var NT=["install","--all"];async function LT(n,e,t,r){return new Promise(i=>{let o=xT(n,e,{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
1304
1304
  `);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
1305
1305
  `);i({exitCode:-1,output:l+`
1306
- `+c.message})})})}function hT(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Og(n,e){try{let{exitCode:t,output:r}=await fT(e.nodePath,[e.ohpmJsPath,...mT],n,e.sdkPath);return hT(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Mg={UNINITIALIZED:-32099,UNKNOWN:-32e3},ho=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Mg.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Mg.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Jr=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=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,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let i=r?.skipHvigorSync===!0,o=await bs(e,async()=>await Og(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Tm(e,t)?(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 o.acquired?o.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);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:N,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?ho.uninitialized(t):ho.unknown();this.onMessage({jsonrpc:N,method:y.ARKTS_INITIALIZATION_FAILED,params:r.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:N,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 r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:N,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var gT=10080*60*1e3,yT=7200*60*1e3,wT=120*1e3,Kr=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;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){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}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:Md.object({files:Md.array(Md.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,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=fe(e),{logPath:s,indexPath:a}=Hp(o);setImmediate(()=>{a&&al(a,gT,"[ArkTS-Check]"),s&&al(s,yT,"[ArkTS-Check]")}),Is(s??"auto");let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;g.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new Jr({sdkPath:d,arktsLangServerPath:r,workspaceRoot:z(o),indexLogPath:a??"auto",nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,useStandardProtocol:i}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(et),this.manager.start([]).catch(v=>{let k=v instanceof Error?v:new Error(String(v));this.failInit(k)})})}resolveProjectAndDeveco(){let e=Ot(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";g.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let i=Fe.resolve(Fe.dirname(r),"standardIndex","index.js"),o=vt.existsSync(i);return g.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}}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=Wn(e),i=await vt.promises.readFile(e,"utf8"),s=`deveco.apptool.${Fe.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{g.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return vT(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},wT);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1307
- `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return g.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();g.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return g.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],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 g.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};g.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return g.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};g.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return g.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],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};g.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}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};g.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}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};g.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=[];for(let d of a){let h=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(h)?l.push(...h):h&&l.push(h)}return{items:a,results:l}});return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();g.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 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 i=(await vt.promises.readFile(t,"utf8")).split(`
1308
- `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}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 r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return g.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Wn(e),i=await vt.promises.readFile(e,"utf8"),s=`deveco.apptool.${Fe.extname(e).replace(/^\./,"")||"plaintext"}`;g.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:++this.documentVersion}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=Fe.isAbsolute(e)?e:Fe.join(this.projectPath,e);return!vt.existsSync(t)||!vt.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 r=this.projectPath,i=[];for(let o of e){let s=Fe.resolve(Fe.isAbsolute(o)?o:Fe.join(r,o));if(!vt.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!vt.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await $p(500);try{let o=await this.checkFile(i);r.push(ST(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1306
+ `+c.message})})})}function OT(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Xh(n,e){try{let{exitCode:t,output:r}=await LT(e.nodePath,[e.ohpmJsPath,...NT],n,e.sdkPath);return OT(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Zh={UNINITIALIZED:-32099,UNKNOWN:-32e3},wo=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Zh.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Zh.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var ei=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=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,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let i=r?.skipHvigorSync===!0,o=await Is(e,async()=>await Xh(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Gm(e,t)?(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 o.acquired?o.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 Ga(this.config);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:N,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?wo.uninitialized(t):wo.unknown();this.onMessage({jsonrpc:N,method:y.ARKTS_INITIALIZATION_FAILED,params:r.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:N,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new za(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new qa(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:N,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var MT=10080*60*1e3,_T=7200*60*1e3,FT=120*1e3,ti=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;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){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}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:Bd.object({files:Bd.array(Bd.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,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}=this.resolveProjectAndDeveco();this.useStandardProtocol=i;let o=fe(e),{logPath:s,indexPath:a}=rm(o);setImmediate(()=>{a&&fl(a,MT,"[ArkTS-Check]"),s&&fl(s,_T,"[ArkTS-Check]")}),Rs(s??"auto");let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;h.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new ei({sdkPath:d,arktsLangServerPath:r,workspaceRoot:z(o),indexLogPath:a??"auto",nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,useStandardProtocol:i}),this.manager.setOnMessage(g=>this.handleLspMessage(g)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((g,w)=>{this.initResolve=g,this.initReject=w,this.armInitTimer(Qe),this.manager.start([]).catch(v=>{let k=v instanceof Error?v:new Error(String(v));this.failInit(k)})})}resolveProjectAndDeveco(){let e=Ft(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";h.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let i=_e.resolve(_e.dirname(r),"standardIndex","index.js"),o=yt.existsSync(i);return h.info(`ArktsCheck protocol: ${o?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${o})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}}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=Yn(e),i=await yt.promises.readFile(e,"utf8"),s=`deveco.apptool.${_e.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:++this.documentVersion}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return jT(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},FT);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1307
+ `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);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 r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],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 r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\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 r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?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(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],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 r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}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 r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}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 r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=e.direction==="supertypes"?y.SUPERTYPES:y.SUBTYPES,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,results:l}});return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}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 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 i=(await yt.promises.readFile(t,"utf8")).split(`
1308
+ `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}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 r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Yn(e),i=await yt.promises.readFile(e,"utf8"),s=`deveco.apptool.${_e.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:++this.documentVersion}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=_e.isAbsolute(e)?e:_e.join(this.projectPath,e);return!yt.existsSync(t)||!yt.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 r=this.projectPath,i=[];for(let o of e){let s=_e.resolve(_e.isAbsolute(o)?o:_e.join(r,o));if(!yt.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!yt.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await nm(500);try{let o=await this.checkFile(i);r.push($T(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1309
1309
  `)),t.length>0&&r.push(t.join(`
1310
1310
  `));let i=r.join(`
1311
- `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){g.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(et),g.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{g.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";g.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":g.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 r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){g.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;g.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}};function vT(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function ST(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)}`}import*as Sn from"fs";import*as Qr from"path";import{z as _d}from"zod";function Xr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Va(n,e){let t=e instanceof Error?e.message:String(e);return g.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var bT=500,Zr=class{manager;toolProvider;constructor(e,t){this.manager=e,this.toolProvider=t}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:_d.object({files:_d.array(_d.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Xr();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1312
- `):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of i){await PT(bT);try{let l=await this.checkFile(c);r.push(ET(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
1311
+ `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){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,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Qe),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));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 r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}};function jT(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function $T(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)}`}import*as Cn from"fs";import*as ii from"path";import{z as Wd}from"zod";function ni(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function Ya(n,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var HT=500,ri=class{manager;toolProvider;constructor(e,t){this.manager=e,this.toolProvider=t}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:Wd.object({files:Wd.array(Wd.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return ni();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1312
+ `):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of i){await BT(HT);try{let l=await this.checkFile(c);r.push(UT(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
1313
1313
  `)),r.length>0&&s.push(r.join(`
1314
1314
  `));let a=s.join(`
1315
- `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Wn(e),r=await Sn.promises.readFile(e,"utf8"),i=os(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,i=[];for(let o of e){let s=Qr.resolve(Qr.isAbsolute(o)?o:Qr.join(r,o));if(!Sn.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Sn.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Bn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Sn.realpathSync(s))}catch{i.push(s)}}return i}};function ET(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 PT(n){return new Promise(e=>setTimeout(e,n))}import*as ti from"fs";import*as Ga from"path";var ei=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 Xr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Va(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Xr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Va("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Xr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Va("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}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Wn(e),i=await ti.promises.readFile(e,"utf8"),o=os(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Ga.isAbsolute(e)?e:Ga.join(this.manager.projectRoot,e);return!ti.existsSync(t)||!ti.statSync(t).isFile()||!Bn(t)?null:t}};import{spawn as CT}from"child_process";import*as qa from"fs";import*as _g from"path";var IT=30*1e3,DT=30*1e3,za=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new gn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new hn(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,i,et),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},DT);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(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=${z(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=CT(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=Er(this.config.workspaceRoot),t=pt(e),r=_g.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.12-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=IT){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:N,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:N,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:N,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{qa.existsSync(this.config.logPath)||qa.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),pt(r)}}catch{}return e}};import*as Ya from"path";import*as Xt from"fs";var go=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===A.OPENHARMONY_STUDIO_ROOT)return;let e=wr(this.projectRoot);if(!Xt.existsSync(e))return;let t=Xt.readFileSync(e,"utf8");if(!t.includes(Ds))return;let r=t.replaceAll(Ds,this.config.toolProvider.sdkPath);Xt.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Ds} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(zn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await bs(e,async()=>{try{return await xm(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return i.acquired?i.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(et);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Ot(this.config.workspaceRoot);this.resolvedRoot=e?fe(e):fe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Is(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=Ya.dirname(wr(this.resolvedRoot));try{Xt.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new za({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t,nodePath:this.config.toolProvider.nodePath});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(i);break;case y.DID_CHANGE:this.proxy.sendDidChange(i);break;case y.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){let e=`${Date.now()}${process.hrtime.bigint()%1000000n}`;return sl(t=>{let r=Ya.join(t,"CppCheck","lsp-log",e);return Xt.mkdirSync(r,{recursive:!0}),fe(r)})??"auto"}};function Fg(n){let e=Ps(n);return f.info(`[SyncGuard] ${e.reason}`),e}var $d=(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))($d||{}),$g=(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))($g||{}),xt=3,Fd=600*1e3,jd=100,Ja=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e){this.config=e,Vn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=Ot(t);g.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new AT({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Ld(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:me.object({target:me.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:me.object({files:me.array(me.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=me.object({file:me.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:me.number().describe("Line number (0-based)"),character:me.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:me.object({query:me.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:me.object({file:me.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:me.object({file:me.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:me.number().describe("Line number (0-based)"),character:me.number().describe("Character offset in the line (0-based)"),direction:me.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=bn.join(bn.dirname(e),"standardIndex","index.js"),r=jg.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=x.isPathContainedWithSymlink(o,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1316
- `)}],isError:!0}:null}let r=e.filter(i=>bn.isAbsolute(i));return r.length>0?(g.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
1317
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>jd)return g.warn(`check tool called with ${t.length} files (max: ${jd})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${jd}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=RT(t);o.length>0&&g.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
1315
+ `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Yn(e),r=await Cn.promises.readFile(e,"utf8"),i=ls(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,i=[];for(let o of e){let s=ii.resolve(ii.isAbsolute(o)?o:ii.join(r,o));if(!Cn.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Cn.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!qn(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Cn.realpathSync(s))}catch{i.push(s)}}return i}};function UT(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 BT(n){return new Promise(e=>setTimeout(e,n))}import*as si from"fs";import*as Ja from"path";var oi=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 ni();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Ya(e,o)}}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 ni();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ya("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return ni();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Ya("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}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Yn(e),i=await si.promises.readFile(e,"utf8"),o=ls(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Ja.isAbsolute(e)?e:Ja.join(this.manager.projectRoot,e);return!si.existsSync(t)||!si.statSync(t).isFile()||!qn(t)?null:t}};import{spawn as WT}from"child_process";import*as Xa from"fs";import*as Qh from"path";var VT=30*1e3,GT=30*1e3,Ka=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Sn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new vn(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,i,Qe),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},GT);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(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=${z(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=WT(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=Ar(this.config.workspaceRoot),t=dt(e),r=Qh.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.13-23.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=VT){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:N,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:N,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:N,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Xa.existsSync(this.config.logPath)||Xa.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)),dt(r)}}catch{}return e}};import*as Za from"path";import*as en from"fs";var vo=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b()||this.config.toolProvider.sourceType==="studio"||process.env.COMMAND_LINE_TOOL_PATH?.trim()===A.OPENHARMONY_STUDIO_ROOT)return;let e=Pr(this.projectRoot);if(!en.existsSync(e))return;let t=en.readFileSync(e,"utf8");if(!t.includes(ks))return;let r=t.replaceAll(ks,this.config.toolProvider.sdkPath);en.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${ks} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(Xn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await Is(e,async()=>{try{return await Ym(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return i.acquired?i.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Qe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Ft(this.config.workspaceRoot);this.resolvedRoot=e?fe(e):fe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();Rs(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=Za.dirname(Pr(this.resolvedRoot));try{en.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Ka({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t,nodePath:this.config.toolProvider.nodePath});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(i);break;case y.DID_CHANGE:this.proxy.sendDidChange(i);break;case y.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){let e=`${Date.now()}${process.hrtime.bigint()%1000000n}`;return ml(t=>{let r=Za.join(t,"CppCheck","lsp-log",e);return en.mkdirSync(r,{recursive:!0}),fe(r)})??"auto"}};function ey(n){let e=As(n);return f.info(`[SyncGuard] ${e.reason}`),e}var zd=(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))(zd||{}),ny=(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))(ny||{}),kt=3,Vd=600*1e3,Gd=100,Qa=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e){this.config=e,Jn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=Ft(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new zT({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Hd(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:me.object({target:me.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:me.object({files:me.array(me.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=me.object({file:me.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:me.number().describe("Line number (0-based)"),character:me.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:me.object({query:me.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:me.object({file:me.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:me.object({file:me.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:me.number().describe("Line number (0-based)"),character:me.number().describe("Character offset in the line (0-based)"),direction:me.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=In.join(In.dirname(e),"standardIndex","index.js"),r=ty.existsSync(t);return h.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=x.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1316
+ `)}],isError:!0}:null}let r=e.filter(i=>In.isAbsolute(i));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
1317
+ `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Gd)return h.warn(`check tool called with ${t.length} files (max: ${Gd})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Gd}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=YT(t);o.length>0&&h.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
1318
1318
  `),s.join(`
1319
1319
  `)].filter(d=>d.trim().length>0).join(`
1320
- `).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${$d[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.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 g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;return typeof r!="string"||typeof i!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return g.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}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}/${xt})`;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}/${xt})`;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,i=e.character,o=e.direction;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:o!=="incoming"&&o!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i})):{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:i}=this.extractPositionArgs(e),o=e.newName;return!t||typeof o!="string"||o.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:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;return t?o!=="supertypes"&&o!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o})):{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,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS ${e} rejected: project is ${$d[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.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 g.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],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"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=xt?(g.error(`Init retry limit reached (${this.initRetryCount}/${xt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${xt}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${xt})`),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 g.warn(`C++ ${e} rejected: C++ project is ${$g[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.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};default:return g.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):Bn(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",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=xt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${xt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${xt}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${xt})`),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 i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1321
- `);i&&(e.isError?t.push(i):r.push(i))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return 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){g.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>g.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.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=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new TT;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Vp();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Ot(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.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=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Ot(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Ot(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new Kr(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Fg(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await Jr.handleSyncProject(e,this.config.toolProvider,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 i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=Fd?(g.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${Fd/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=zn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new go({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new Zr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new ei(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await go.handleSyncCppProject(e,this.config.toolProvider);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(r/1e3);return r>=Fd?(g.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),Wp(),Bp()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function RT(n){let e=[],t=[],r=[];for(let i of n)bn.extname(i).toLowerCase()===".ets"?e.push(i):Bn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function Hd(n){return new Ja(n)}import*as Ud from"fs";import*as En from"path";import{spawn as kT}from"child_process";async function Hg(n){Vn(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:i}=await LT(n),o=_T(e,t,r,n.toolProvider,i);g.info("ace-server started, bridging stdio (initialize is left to the client)"),jT(o),await NT(o.pid??null,xT("--arkts",n))}function xT(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function NT(n,e){let t="unknown";if(n!==null){let i=await Ni(n);i!==null&&(t=Dt(Number(i)*1024))}let r={event:D.ServeLsp,args:e,lspMemory:t};await I.track(r)}async function LT(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=fe(En.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=is(process.cwd());e=fe(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=fe(process.cwd()),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let i=En.resolve(En.dirname(r),"standardIndex","index.js"),o=En.join(Ii(),"lsp-server",String(Date.now()));Ud.mkdirSync(o,{recursive:!0});let s=OT(e,t);return g.info(`projectPath=${e}, sdkPath=${t}, serverPath=${i}, logPath=${o}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:i,logPath:o,serverMaxSize:s}}function OT(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=MT(n,e),s=As(o,i);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function MT(n,e){try{let t=[];return new ir(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Ht(n).getAllModuleInfo().length}catch{return 0}}function _T(n,e,t,r,i){let o=En.join(e,"lspLog");Ud.mkdirSync(o,{recursive:!0});let s=FT(n,o,t,r.sdkPath,i),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),kT(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function FT(n,e,t,r,i){let o=z(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${z(t)}`,`--sdkPath=${z(r)}`]}function jT(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as Ug from"fs";import*as or from"path";import{spawn as $T}from"child_process";async function Bg(n){Vn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await HT(n),i=or.join(t,"compile_commands.json");Ug.existsSync(i)||g.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=UT(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),WT(o)}async function HT(n){let e;if(n.projectPath)e=fe(or.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let o=is(process.cwd());e=fe(o??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${o??"null, fallback to cwd"}`)}else e=fe(or.resolve(process.cwd())),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=wr(e),i=or.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${i}`),{projectPath:e,clangdPath:t,compileCommandsDir:i}}function UT(n,e,t){let r=BT(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),$T(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function BT(n){return[`--compile-commands-dir=${z(n)}`,"--log=info","--pch-storage=memory"]}function WT(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function GT(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await A.new();b()||r.require({clt:!1});let o=Hd({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await o.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await o.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Bd=new VT("serve").description("Host bundled auxiliary protocol servers");Bd.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await GT()});Bd.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));let e=await A.new();n.arkts?await Hg({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Bg({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Wg=Bd;import{Command as qx,InvalidArgumentError as Nu}from"commander";import{red as Yx,dim as Jx}from"colorette";import*as je from"fs";import*as fi from"path";import Lx from"proper-lockfile";import Kw from"ora";import*as St from"fs";import*as Do from"path";var Pn=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],sr={"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"};var ni="1.9.1",P5=48*1024*1024,Vg=280,Gg=6,zg=100,qg=3,Yg=28,Wd=10,Jg=/API参考|APIReference/i,yo=200,Kg=12,Xg=4,Vd=8,Zg=6,Ka=700,Gd=250,zd=400,Qg=1320,ey=120,ty=450,ny=250,ry=500,iy=480,oy=80,sy=200,ay=60,cy=200,ly=40,dy=200,uy=200,py=40,ri=500,my=Object.fromEntries(Pn.map((n,e)=>[sr[n],e])),Cn=Object.fromEntries(Pn.map((n,e)=>[n,e]));import*as wo from"fs";import*as F from"path";import{fileURLToPath as yy}from"url";import*as In from"fs";import*as fy from"path";import{homedir as zT}from"os";var qT="deveco-cli",qd,ar=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function YT(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&fs(n)!==""}function hy(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":fs(n))||fy.join(zT(),".local","share",qT);try{return hs(t)}catch(r){throw new ar(r instanceof Error?r.message:String(r))}}async function gy(){let n=hy();await In.promises.mkdir(n,{recursive:!0});let e;try{e=await In.promises.realpath(n)}catch(r){throw new ar(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await In.promises.stat(e)).isDirectory())throw new ar("DEVECO_CLI_DATA_DIR must be a writable directory.");return qd=e,e}function Xa(n){let e=Zt();return YT()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Zt(){if(qd!==void 0)return qd;let n=hy();try{if(In.existsSync(n))return In.realpathSync(n)}catch{}return n}var JT="docs";function ii(){return F.join(Zt(),JT)}function re(){return F.join(ii(),".index")}function Za(){return F.join(re(),"build.lock")}function vo(){return F.join(re(),"build-status.json")}function oi(){return F.join(re(),"build-meta.json")}function cr(){return F.join(re(),"search.db")}function So(){return F.join(re(),"sqlite-backend.json")}function bo(){return F.join(re(),"jieba-backend.json")}function Qt(){return F.join(re(),".tmp")}function KT(){return F.join(Zt(),"logs")}function si(){return F.join(KT(),"doc-init.log")}function XT(n,e){let t=e;for(;!t.endsWith(`${F.sep}dist`)&&t!==F.dirname(t);)t=F.dirname(t);return t}function wy(n,e){return F.dirname(XT(n,e))}function vy(){let n=yy(import.meta.url),e=F.dirname(n);return n.includes(`${F.sep}dist${F.sep}`)?wy(n,e):F.join(e,"..","..","..")}function ZT(...n){let e=yy(import.meta.url),t=F.dirname(e);return e.includes(`${F.sep}dist${F.sep}`)?[F.join(wy(e,t),...n)]:[F.join(t,"..","..","..",...n)]}function Sy(...n){let e=vy(),t=wo.realpathSync(e);for(let r of ZT(...n))try{let i=wo.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=wo.realpathSync(r);if(!nl(o,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return o}catch(i){if(i.code!=="ENOENT")throw i}return null}function Dn(){return Sy("docs.zip")}function Yd(){return Sy("index.zip")}function by(){return F.join(vy(),"index","data")}import*as en from"fs";import*as lr from"path";var tn=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Qa=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Ey(n){return n instanceof Qa}var Jd=null;function Kd(n){Jd=n}function Xd(){if(Jd)return Jd;let n=re();if(tn.every(i=>en.existsSync(lr.join(n,i))))return n;let t=by();if(tn.every(i=>en.existsSync(lr.join(t,i))))return t;throw new Qa("Lexicon files not found. Install the documentation index first (index.zip).")}function Py(){Xd()}function dr(n){let e=lr.join(Xd(),n);return en.readFileSync(e,"utf-8")}function Cy(n,e){return en.readFileSync(lr.join(e,n),"utf-8")}async function Iy(n,e=Xd()){await en.promises.mkdir(n,{recursive:!0});for(let t of tn){let r=lr.join(e,t),i=lr.join(n,t);await en.promises.copyFile(r,i)}}import*as ec from"fs";import*as Dy from"path";import*as Ay from"yauzl";var Eo=null;function QT(n){return new Promise((e,t)=>{Ay.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function eR(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function tR(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=eR(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function nR(){Eo?.zipfile.close(),Eo=null}async function rR(n){let e=Dy.resolve(n),t=await ec.promises.stat(e),r=Eo;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;nR();let i=await QT(e),o=await tR(i);return Eo={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},Eo}function iR(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function oR(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await iR(n.zipfile,e)}finally{r()}}function sR(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 aR(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Ty(n){let e=Dn();if(!e)throw new Error("docs.zip not found");let t=await rR(e),r=aR(t.entries,sR(n));if(!r)throw new Error(`Document not found: ${n}`);return(await oR(t,r)).toString("utf-8")}function Zd(){let n=Dn();return n!==null&&ec.existsSync(n)}import*as ve from"fs";import*as nn from"path";import Ry from"adm-zip";import*as Po from"fs";import*as nc from"path";var tc=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Co(n){return n instanceof ar||n instanceof tc||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function tu(n){return new tc(n)}function cR(){return Xe(Zt())}function eu(n,e,t){let r=Un(n,e);if(r===null)throw tu(`${t} resolves outside the data directory.`);return r}async function Qd(n,e){await Po.promises.mkdir(n,{recursive:!0});let t=eu(n,e,"directory");if(!(await Po.promises.stat(t)).isDirectory())throw tu("path must be a directory.")}function Io(n){let e=cR();try{let t=eu(n,e,"file");if(!Po.statSync(t).isFile())throw tu("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){eu(nc.dirname(n),e,"file parent");return}throw t}}async function ai(n={}){let e=n.mode??"write",t=await gy();await Qd(ii(),t),await Qd(re(),t),e==="write"&&await Qd(Qt(),t);for(let r of[cr(),oi(),vo(),Za(),bo(),So(),...tn.map(i=>nc.join(re(),i))])Io(r)}var nu=["search.db","build-meta.json",...tn],lR=["corpus.json","corpus-offsets.json","orama.dpack"];async function dR(n){for(let e of lR)await ve.promises.rm(nn.join(n,e),{force:!0})}async function uR(n){let e=await ve.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await ve.promises.rm(nn.join(n,t.name),{recursive:!0,force:!0})}function ky(n){let t=new Ry(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 pR(n){let e=re();await ve.promises.mkdir(e,{recursive:!0});for(let t of nu){let r=nn.join(e,t);await ve.promises.rm(r,{force:!0}),await ve.promises.rename(nn.join(n,t),r)}await dR(e),await ve.promises.rm(Qt(),{recursive:!0,force:!0})}function xy(n){let e=Yd();if(!e)return!1;try{let t=ky(e);return t.indexVersion===ni&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Ny(n){await ai({mode:"write"});let e=Yd();if(!e)throw new Error("index.zip not found");let t=ky(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=Qt();await ve.promises.rm(r,{recursive:!0,force:!0}),await ve.promises.mkdir(r,{recursive:!0});let i=new Ry(e);for(let s of nu){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await ve.promises.writeFile(nn.join(r,s),a.getData())}let o=JSON.parse(await ve.promises.readFile(nn.join(r,"build-meta.json"),"utf-8"));if(!ve.existsSync(nn.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await pR(r),await ve.promises.mkdir(ii(),{recursive:!0}),await uR(ii()),o}async function Ly(){await ve.promises.rm(Qt(),{recursive:!0,force:!0});let n=re();for(let e of nu)await ve.promises.rm(nn.join(n,e),{force:!0})}import{createHash as Oy}from"crypto";import*as My from"fs";async function rc(n){return new Promise((e,t)=>{let r=Oy("sha256"),i=My.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function _y(n){return Oy("sha256").update(n,"utf8").digest("hex")}var ru=null;function mR(){let n=dr("harmonyos-synonyms.json");return JSON.parse(n)}function fR(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function hR(){let n=fR(mR()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function gR(){return ru||(ru=hR()),ru}function iu(n,e){let t=gR(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function Fy(n,e){let t=e?Cy(n,e):dr(n);return _y(t)}function ic(n){return Fy("harmonyos-synonyms.json",n)}function oc(n){return Fy("harmonyos-terms.txt",n)}var yR={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function sc(){try{let n=await St.promises.readFile(vo(),"utf-8");return JSON.parse(n)}catch{return{...yR}}}async function ou(n){let e=vo();await St.promises.mkdir(Do.dirname(e),{recursive:!0}),await St.promises.writeFile(e,JSON.stringify(n,null,2))}function jy(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function An(n){let t={...await sc(),...n,updatedAt:Date.now()};return await ou(t),t}async function su(){let n=Dn();return n?rc(n):null}async function au(){try{let n=await St.promises.readFile(oi(),"utf-8");return JSON.parse(n)}catch{return null}}async function ac(n=!1){if(n)return"no-index";let e=await au();if(!e||e.segmentCount===0)return"no-index";let t=await su();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==ni?"engine-upgraded":e.termsHash!==oc()?"terms-changed":e.synonymsHash!==ic()?"synonyms-changed":null}function Ao(){if(!Zd()||!St.existsSync(cr())||!St.existsSync(oi()))return!1;let n=Do.dirname(cr());if(!tn.every(e=>St.existsSync(Do.join(n,e))))return!1;try{let e=St.readFileSync(oi(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function cu(n=!1){return n?!0:Zd()?Ao()?await ac()!==null:!0:!1}async function $y(){let n=await sc();return["installing","indexing","persisting"].includes(n.state)}import*as mi from"fs";import*as kn from"path";import Sx from"adm-zip";var Hy=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),lu=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Uy=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"]),By=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 wR=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,vR=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,SR=/[A-Z][a-zA-Z0-9]{2,}/g,bR=/@[A-Z][a-zA-Z0-9]*/g,ER=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Wy=6,PR=/^[a-z][a-z0-9]{2,}$/,CR=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,IR=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,DR=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,AR=/^[A-Z][a-zA-Z0-9]+$/;function TR(n){return`"${n.replace(/"/g,'""')}"`}function Ro(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(TR).join(` ${e} `)}function To(n){return Ro(n,"OR")}function Vy(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?To([...t,...r]):`(${To(t)}) AND (${To(r)})`}function ko(n){return IR.test(n)}function Gy(n){return DR.test(n)&&n.length>=Wy}function RR(n){return AR.test(n)}function xo(n){return ko(n)||Gy(n)||RR(n)}function kR(n){let e=n.trim().toLowerCase();return By.has(e)?!1:Hy.has(e)}function xR(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function cc(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function du(n){return[...n.matchAll(wR)].map(e=>e[0])}function uu(n,e=Wy){let t=[];for(let r of n.matchAll(vR))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 i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function bt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function NR(n){let e=new Set;bt(e,n);let t=cc(n);return t&&bt(e,t),ci([...e])}function lc(n){if(ko(n))return NR(n);let e=new Set;return bt(e,n),ci([...e])}function dc(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(CR);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!PR.test(r)||Uy.has(r)||!kR(i))return null;let o=xR(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function pu(n){let e=dc(n.trim());return!e||e.second!=="manager"?null:e}function LR(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function zy(n){let e=n.trim(),t=pu(e);if(t&&lu.has(t.first))return!0;if(Gy(e)){let r=LR(e);return r!==null&&lu.has(r)}return!1}function mu(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function fu(n){let e=n.trim();if(xo(e))return lc(e);let t=new Set;for(let r of du(n)){bt(t,r);let i=cc(r);i&&bt(t,i)}for(let r of uu(n))bt(t,r);for(let r of n.matchAll(bR))t.add(r[0]);for(let r of n.matchAll(ER))t.add(r[0]);for(let r of n.matchAll(SR))r[0].length>=4&&t.add(r[0]);return ci([...t])}function qy(n){let e=n.trim();if(xo(e))return lc(e);let t=new Set,r=dc(e);r&&bt(t,r.camelCase);for(let i of fu(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return ci([...t])}function Yy(n){return xo(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 Jy(n){return te.pureApiSymbol.test(n.trim())}function No(n){let e=n.trim();return te.stageModelExact.test(e)||te.stageModelEnglishExact.test(e)}function Ky(n){let e=[];return No(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 Xy(n){return No(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var OR=[{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=>No(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!No(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 MR(n,e){for(let{catalog:t,multiplier:r}of e){let i=Cn[t];n.set(i,(n.get(i)??1)*r)}}function Zy(n,e){for(let t of OR)t.matches(n)&&MR(e,t.weights)}function Qy(n,e){if(e!==void 0)return!1;let t=n.trim();return ko(t)||te.pureApiSymbol.test(t)||zy(t)}function ew(n){let e=n.trim();if(ko(e)||te.pureApiSymbol.test(e))return"harmonyos-references";if(No(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*as li from"fs";import*as nw from"path";var uc=null,hu=null,gu=null;function _R(){return li.existsSync(bo())}function FR(n){let e=bo(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};li.mkdirSync(nw.dirname(e),{recursive:!0}),Io(e),li.writeFileSync(e,JSON.stringify(t,null,2))}function jR(){if(uc)return uc;let n=dr("harmonyos-stopwords.txt");return uc=new Set(n.split(`
1322
- `).map(e=>e.trim()).filter(Boolean)),uc}function $R(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function rw(n){let e=jR(),t=[];for(let r of $R(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function iw(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=dr("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function HR(){let{Jieba:n}=await import("@node-rs/jieba");return iw(n)}async function tw(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return iw(n)}async function UR(){let n=await import("jieba-wasm"),e=dr("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function BR(){if(b())return UR();if(_R())return tw();try{let e=await HR();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);FR(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await tw();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function Tn(){return hu||(gu||(gu=BR().then(n=>(hu=n,n))),gu)}async function WR(n){let e=await Tn();return rw(e.cutForSearch(n,!0))}async function ow(n){let e=await Tn();return rw(e.cut(n,!0))}async function pc(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await WR(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function VR(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function mc(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?iy:Qg,i=e?sy:ty,o=e?await VR(n.apiSymbols,i):await pc(n.apiSymbols.join(" "),i),a=(await Promise.all([pc(t,e?oy:ey),Promise.resolve(o),pc(n.headingsText,e?ay:ny),pc(n.bodySample,e?cy:ry)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function GR(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,yo)}function yu(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=Kg))break}return r}function zR(n){return n.length>=2&&n.length<=Xg}function qR(n,e){let t=iu(n,Vd),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=yu(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Vy(i,o)}}function YR(n,e){let t=yu(lc(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:To(t)}}async function sw(n){let e=GR(n),t=e.trim(),r=Xy(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=dc(t);if(i)return qR(e,i);if(xo(t))return YR(e,t);let o=Ky(e),s=[...fu(e),...o],c=Yy(t)?e:iu(e,Vd),l=await ow(c),d=yu(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:o.length===0&&zR(d)}}var aw=["harmonyos-releases","harmonyos-roadmap"],JR=new Set(aw.map(n=>Cn[n])),KR=aw.map(n=>`${sr[n]}/`);function XR(n){return JR.has(n)}function ZR(n){return KR.some(e=>n.startsWith(e))}function cw(n){let e=[],t=[];for(let r of n)XR(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function lw(n){let e=[],t=[];for(let r of n)ZR(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var QR=[{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 Lo(n,e,t){let r=Cn[e];n.set(r,(n.get(r)??1)*t)}function ek(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){Lo(e,"harmonyos-guides",1.45),Lo(e,"harmonyos-references",1.35);return}(i||o)&&Lo(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Lo(e,"harmonyos-references",1.75)}function dw(n){let e=new Map,t=n.trim();if(!t)return e;let r=Jy(t);ek(t,e),Zy(t,e);for(let i of QR)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Lo(e,i.catalog,i.multiplier));return e}function uw(n){return ew(n)}import*as ui from"fs";import*as vw from"path";var tk=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function pw(n,e){let t=-1;for(let r of tk){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function mw(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=pw(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function fw(n,e,t={}){let{maxLen:r=uy,contextChars:i=py,excerptTruncated:o=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return o?`${s}...`:s;let a=e.split(/\s+/).map(We=>We.trim()).filter(Boolean),c=0;for(let We of a){let ct=s.toLowerCase().indexOf(We.toLowerCase());if(ct>=0){c=ct;break}}let l=Math.max(0,c-i),d=Math.min(s.length,l+r),h=s.slice(l,d),w=pw(h,r-25);w>=0&&(d=l+w);let v=s.slice(l,d).trim(),k=l>0?"...":"",ce=d<s.length||o?"...":"";return`${k}${v}${ce}`}var nk=`
1320
+ `).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 ${zd[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,i=t.line,o=t.character;return typeof r!="string"||typeof i!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,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 i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}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}/${kt})`;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}/${kt})`;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,i=e.character,o=e.direction;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:o!=="incoming"&&o!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i})):{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:i}=this.extractPositionArgs(e),o=e.newName;return!t||typeof o!="string"||o.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:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;return t?o!=="supertypes"&&o!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o})):{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,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${zd[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.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],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>=kt?(h.error(`Init retry limit reached (${this.initRetryCount}/${kt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${kt}). 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}/${kt})`),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 ${ny[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.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};default:return h.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):qn(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>=kt?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${kt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${kt}). 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}/${kt})`),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 i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1321
+ `);i&&(e.isError?t.push(i):r.push(i))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return 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.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 qT;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=am();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=Ft(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?Ft(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Ft(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()){this.ensureCppProjectReady().catch(e=>{h.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new ti(this.config.projectPath,this.config.toolProvider,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});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ey(e),r=!t.required;return h.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await ei.handleSyncProject(e,this.config.toolProvider,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 i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=Vd?(h.error(`Sync skipped for ${o}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 ${o}s / ${Vd/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.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=Xn(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}if(this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new vo({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new ri(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new oi(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await vo.handleSyncCppProject(e,this.config.toolProvider);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(r/1e3);return r>=Vd?(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: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${t.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"),sm(),om()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function YT(n){let e=[],t=[],r=[];for(let i of n)In.extname(i).toLowerCase()===".ets"?e.push(i):qn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function qd(n){return new Qa(n)}import*as Yd from"fs";import*as Dn from"path";import{spawn as JT}from"child_process";async function ry(n){Jn(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:i}=await ZT(n),o=tR(e,t,r,n.toolProvider,i);h.info("ace-server started, bridging stdio (initialize is left to the client)"),rR(o),await XT(o.pid??null,KT("--arkts",n))}function KT(n,e){return[n,...e.projectPath?["--project-path"]:[],...e.autoDetect?["--auto-detect"]:[]]}async function XT(n,e){let t="unknown";if(n!==null){let i=await Mi(n);i!==null&&(t=It(Number(i)*1024))}let r={event:D.ServeLsp,args:e,lspMemory:t};await I.track(r)}async function ZT(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=fe(Dn.resolve(n.projectPath)),h.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=cs(process.cwd());e=fe(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=fe(process.cwd()),h.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(h.error("ace-server not found in DevEco Studio installation."),process.exit(1));let i=Dn.resolve(Dn.dirname(r),"standardIndex","index.js"),o=Dn.join(Ti(),"lsp-server",String(Date.now()));Yd.mkdirSync(o,{recursive:!0});let s=QT(e,t);return h.info(`projectPath=${e}, sdkPath=${t}, serverPath=${i}, logPath=${o}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:i,logPath:o,serverMaxSize:s}}function QT(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=eR(n,e),s=xs(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function eR(n,e){try{let t=[];return new lr(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Wt(n).getAllModuleInfo().length}catch{return 0}}function tR(n,e,t,r,i){let o=Dn.join(e,"lspLog");Yd.mkdirSync(o,{recursive:!0});let s=nR(n,o,t,r.sdkPath,i),a=r.nodePath;return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),JT(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function nR(n,e,t,r,i){let o=z(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${z(t)}`,`--sdkPath=${z(r)}`]}function rR(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),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 iy from"fs";import*as dr from"path";import{spawn as iR}from"child_process";async function oy(n){Jn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await oR(n),i=dr.join(t,"compile_commands.json");iy.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=sR(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),cR(o)}async function oR(n){let e;if(n.projectPath)e=fe(dr.resolve(n.projectPath)),h.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let o=cs(process.cwd());e=fe(o??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${o??"null, fallback to cwd"}`)}else e=fe(dr.resolve(process.cwd())),h.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(h.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=Pr(e),i=dr.dirname(r);return h.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${i}`),{projectPath:e,clangdPath:t,compileCommandsDir:i}}function sR(n,e,t){let r=aR(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),iR(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function aR(n){return[`--compile-commands-dir=${z(n)}`,"--log=info","--pch-storage=memory"]}function cR(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),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 dR(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await A.new();b()||r.require({clt:!1});let o=qd({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await o.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await o.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Jd=new lR("serve").description("Host bundled auxiliary protocol servers");Jd.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await dR()});Jd.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));let e=await A.new();n.arkts?await ry({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await oy({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var sy=Jd;import{Command as mN,InvalidArgumentError as Hu}from"commander";import{red as fN,dim as gN}from"colorette";import*as Fe from"fs";import*as vi from"path";import Qx from"proper-lockfile";import gv from"ora";import*as wt from"fs";import*as Ro from"path";var An=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],xt={"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"};var ai="1.10.0",G5=48*1024*1024,ay=280,cy=6,ly=100,dy=3,uy=28,Kd=10,py=/API参考|APIReference/i,So=200,my=12,fy=4,Xd=8,gy=6,ec=700,Zd=250,Qd=400,hy=1320,yy=120,wy=450,vy=250,Sy=500,by=480,Ey=80,Py=200,Cy=60,Iy=200,Dy=40,Ay=200,Ty=200,Ry=40,ci=500,ky=Object.fromEntries(An.map((n,e)=>[xt[n],e])),Tn=Object.fromEntries(An.map((n,e)=>[n,e])),tc="kb",nc="source",eu={guides:"harmonyos-guides","harmonyos-references":"harmonyos-references","best-practices":"best-practices",faq:"harmonyos-faqs","release-notes":"harmonyos-releases",changelogs:"harmonyos-roadmap"},xy=Object.fromEntries(Object.entries(eu).map(([n,e])=>[xt[e],n]));import*as bo from"fs";import*as F from"path";import{fileURLToPath as My}from"url";import*as Rn from"fs";import*as Ny from"path";import{homedir as uR}from"os";var pR="deveco-cli",tu,ur=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function mR(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&ws(n)!==""}function Ly(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":ws(n))||Ny.join(uR(),".local","share",pR);try{return vs(t)}catch(r){throw new ur(r instanceof Error?r.message:String(r))}}async function Oy(){let n=Ly();await Rn.promises.mkdir(n,{recursive:!0});let e;try{e=await Rn.promises.realpath(n)}catch(r){throw new ur(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await Rn.promises.stat(e)).isDirectory())throw new ur("DEVECO_CLI_DATA_DIR must be a writable directory.");return tu=e,e}function rc(n){let e=tn();return mR()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function tn(){if(tu!==void 0)return tu;let n=Ly();try{if(Rn.existsSync(n))return Rn.realpathSync(n)}catch{}return n}var fR="docs";function li(){return F.join(tn(),fR)}function re(){return F.join(li(),".index")}function ic(){return F.join(re(),"build.lock")}function Eo(){return F.join(re(),"build-status.json")}function di(){return F.join(re(),"build-meta.json")}function pr(){return F.join(re(),"search.db")}function Po(){return F.join(re(),"sqlite-backend.json")}function Co(){return F.join(re(),"jieba-backend.json")}function nn(){return F.join(re(),".tmp")}function gR(){return F.join(tn(),"logs")}function ui(){return F.join(gR(),"doc-init.log")}function hR(n,e){let t=e;for(;!t.endsWith(`${F.sep}dist`)&&t!==F.dirname(t);)t=F.dirname(t);return t}function _y(n,e){return F.dirname(hR(n,e))}function Fy(){let n=My(import.meta.url),e=F.dirname(n);return n.includes(`${F.sep}dist${F.sep}`)?_y(n,e):F.join(e,"..","..","..")}function yR(...n){let e=My(import.meta.url),t=F.dirname(e);return e.includes(`${F.sep}dist${F.sep}`)?[F.join(_y(e,t),...n)]:[F.join(t,"..","..","..",...n)]}function jy(...n){let e=Fy(),t=bo.realpathSync(e);for(let r of yR(...n))try{let i=bo.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=bo.realpathSync(r);if(!ll(o,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return o}catch(i){if(i.code!=="ENOENT")throw i}return null}function kn(){return jy("docs.zip")}function nu(){return jy("index.zip")}function $y(){return F.join(Fy(),"index","data")}import*as rn from"fs";import*as mr from"path";var on=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],oc=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function Hy(n){return n instanceof oc}var ru=null;function iu(n){ru=n}function ou(){if(ru)return ru;let n=re();if(on.every(i=>rn.existsSync(mr.join(n,i))))return n;let t=$y();if(on.every(i=>rn.existsSync(mr.join(t,i))))return t;throw new oc("Lexicon files not found. Install the documentation index first (index.zip).")}function Uy(){ou()}function fr(n){let e=mr.join(ou(),n);return rn.readFileSync(e,"utf-8")}function By(n,e){return rn.readFileSync(mr.join(e,n),"utf-8")}async function Wy(n,e=ou()){await rn.promises.mkdir(n,{recursive:!0});for(let t of on){let r=mr.join(e,t),i=mr.join(n,t);await rn.promises.copyFile(r,i)}}import*as sc from"fs";import*as Vy from"path";import*as Gy from"yauzl";var Io=null;function wR(n){return new Promise((e,t)=>{Gy.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function vR(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function SR(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=vR(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function bR(){Io?.zipfile.close(),Io=null}async function ER(n){let e=Vy.resolve(n),t=await sc.promises.stat(e),r=Io;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;bR();let i=await wR(e),o=await SR(i);return Io={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},Io}function PR(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function CR(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await PR(n.zipfile,e)}finally{r()}}function IR(n){let e=n.indexOf("/");if(e<0)return null;let t=xy[n.slice(0,e)];return t===void 0?null:`${tc}/${nc}/${t}/${n.slice(e+1)}`}function DR(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");let t=[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e],r=IR(e);return r&&t.push(`${r}.md`,r),t}function AR(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function zy(n){let e=kn();if(!e)throw new Error("docs.zip not found");let t=await ER(e),r=AR(t.entries,DR(n));if(!r)throw new Error(`Document not found: ${n}`);return(await CR(t,r)).toString("utf-8")}function su(){let n=kn();return n!==null&&sc.existsSync(n)}import*as ve from"fs";import*as sn from"path";import qy from"adm-zip";import*as Do from"fs";import*as cc from"path";var ac=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Ao(n){return n instanceof ur||n instanceof ac||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function lu(n){return new ac(n)}function TR(){return Ke(tn())}function cu(n,e,t){let r=zn(n,e);if(r===null)throw lu(`${t} resolves outside the data directory.`);return r}async function au(n,e){await Do.promises.mkdir(n,{recursive:!0});let t=cu(n,e,"directory");if(!(await Do.promises.stat(t)).isDirectory())throw lu("path must be a directory.")}function To(n){let e=TR();try{let t=cu(n,e,"file");if(!Do.statSync(t).isFile())throw lu("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){cu(cc.dirname(n),e,"file parent");return}throw t}}async function pi(n={}){let e=n.mode??"write",t=await Oy();await au(li(),t),await au(re(),t),e==="write"&&await au(nn(),t);for(let r of[pr(),di(),Eo(),ic(),Co(),Po(),...on.map(i=>cc.join(re(),i))])To(r)}var du=["search.db","build-meta.json",...on],RR=["corpus.json","corpus-offsets.json","orama.dpack"];async function kR(n){for(let e of RR)await ve.promises.rm(sn.join(n,e),{force:!0})}async function xR(n){let e=await ve.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await ve.promises.rm(sn.join(n,t.name),{recursive:!0,force:!0})}function Yy(n){let t=new qy(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 NR(n){let e=re();await ve.promises.mkdir(e,{recursive:!0});for(let t of du){let r=sn.join(e,t);await ve.promises.rm(r,{force:!0}),await ve.promises.rename(sn.join(n,t),r)}await kR(e),await ve.promises.rm(nn(),{recursive:!0,force:!0})}function Jy(n){let e=nu();if(!e)return!1;try{let t=Yy(e);return t.indexVersion===ai&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Ky(n){await pi({mode:"write"});let e=nu();if(!e)throw new Error("index.zip not found");let t=Yy(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=nn();await ve.promises.rm(r,{recursive:!0,force:!0}),await ve.promises.mkdir(r,{recursive:!0});let i=new qy(e);for(let s of du){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await ve.promises.writeFile(sn.join(r,s),a.getData())}let o=JSON.parse(await ve.promises.readFile(sn.join(r,"build-meta.json"),"utf-8"));if(!ve.existsSync(sn.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await NR(r),await ve.promises.mkdir(li(),{recursive:!0}),await xR(li()),o}async function Xy(){await ve.promises.rm(nn(),{recursive:!0,force:!0});let n=re();for(let e of du)await ve.promises.rm(sn.join(n,e),{force:!0})}import{createHash as Zy}from"crypto";import*as Qy from"fs";async function lc(n){return new Promise((e,t)=>{let r=Zy("sha256"),i=Qy.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function ew(n){return Zy("sha256").update(n,"utf8").digest("hex")}var uu=null;function LR(){let n=fr("harmonyos-synonyms.json");return JSON.parse(n)}function OR(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function MR(){let n=OR(LR()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function _R(){return uu||(uu=MR()),uu}function pu(n,e){let t=_R(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function tw(n,e){let t=e?By(n,e):fr(n);return ew(t)}function dc(n){return tw("harmonyos-synonyms.json",n)}function uc(n){return tw("harmonyos-terms.txt",n)}var FR={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function pc(){try{let n=await wt.promises.readFile(Eo(),"utf-8");return JSON.parse(n)}catch{return{...FR}}}async function mu(n){let e=Eo();await wt.promises.mkdir(Ro.dirname(e),{recursive:!0}),await wt.promises.writeFile(e,JSON.stringify(n,null,2))}function nw(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function xn(n){let t={...await pc(),...n,updatedAt:Date.now()};return await mu(t),t}async function fu(){let n=kn();return n?lc(n):null}async function gu(){try{let n=await wt.promises.readFile(di(),"utf-8");return JSON.parse(n)}catch{return null}}async function mc(n=!1){if(n)return"no-index";let e=await gu();if(!e||e.segmentCount===0)return"no-index";let t=await fu();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==ai?"engine-upgraded":e.termsHash!==uc()?"terms-changed":e.synonymsHash!==dc()?"synonyms-changed":null}function ko(){if(!su()||!wt.existsSync(pr())||!wt.existsSync(di()))return!1;let n=Ro.dirname(pr());if(!on.every(e=>wt.existsSync(Ro.join(n,e))))return!1;try{let e=wt.readFileSync(di(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function hu(n=!1){return n?!0:su()?ko()?await mc()!==null:!0:!1}async function rw(){let n=await pc();return["installing","indexing","persisting"].includes(n.state)}import*as wi from"fs";import*as On from"path";import Hx from"adm-zip";var iw=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),yu=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),ow=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"]),sw=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 jR=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,$R=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,HR=/[A-Z][a-zA-Z0-9]{2,}/g,UR=/@[A-Z][a-zA-Z0-9]*/g,BR=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,aw=6,WR=/^[a-z][a-z0-9]{2,}$/,VR=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,GR=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,zR=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,qR=/^[A-Z][a-zA-Z0-9]+$/;function YR(n){return`"${n.replace(/"/g,'""')}"`}function No(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(YR).join(` ${e} `)}function xo(n){return No(n,"OR")}function cw(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?xo([...t,...r]):`(${xo(t)}) AND (${xo(r)})`}function Lo(n){return GR.test(n)}function lw(n){return zR.test(n)&&n.length>=aw}function JR(n){return qR.test(n)}function Oo(n){return Lo(n)||lw(n)||JR(n)}function KR(n){let e=n.trim().toLowerCase();return sw.has(e)?!1:iw.has(e)}function XR(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function fc(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function wu(n){return[...n.matchAll(jR)].map(e=>e[0])}function vu(n,e=aw){let t=[];for(let r of n.matchAll($R))r[0].length>=e&&t.push(r[0]);return t}function mi(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function vt(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function ZR(n){let e=new Set;vt(e,n);let t=fc(n);return t&&vt(e,t),mi([...e])}function gc(n){if(Lo(n))return ZR(n);let e=new Set;return vt(e,n),mi([...e])}function hc(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(VR);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!WR.test(r)||ow.has(r)||!KR(i))return null;let o=XR(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function Su(n){let e=hc(n.trim());return!e||e.second!=="manager"?null:e}function QR(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function dw(n){let e=n.trim(),t=Su(e);if(t&&yu.has(t.first))return!0;if(lw(e)){let r=QR(e);return r!==null&&yu.has(r)}return!1}function bu(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function Eu(n){let e=n.trim();if(Oo(e))return gc(e);let t=new Set;for(let r of wu(n)){vt(t,r);let i=fc(r);i&&vt(t,i)}for(let r of vu(n))vt(t,r);for(let r of n.matchAll(UR))t.add(r[0]);for(let r of n.matchAll(BR))t.add(r[0]);for(let r of n.matchAll(HR))r[0].length>=4&&t.add(r[0]);return mi([...t])}function uw(n){let e=n.trim();if(Oo(e))return gc(e);let t=new Set,r=hc(e);r&&vt(t,r.camelCase);for(let i of Eu(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return mi([...t])}function pw(n){return Oo(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 mw(n){return te.pureApiSymbol.test(n.trim())}function Mo(n){let e=n.trim();return te.stageModelExact.test(e)||te.stageModelEnglishExact.test(e)}function fw(n){let e=[];return Mo(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 gw(n){return Mo(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var ek=[{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=>Mo(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Mo(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 tk(n,e){for(let{catalog:t,multiplier:r}of e){let i=Tn[t];n.set(i,(n.get(i)??1)*r)}}function hw(n,e){for(let t of ek)t.matches(n)&&tk(e,t.weights)}function yw(n,e){if(e!==void 0)return!1;let t=n.trim();return Lo(t)||te.pureApiSymbol.test(t)||dw(t)}function ww(n){let e=n.trim();if(Lo(e)||te.pureApiSymbol.test(e))return"harmonyos-references";if(Mo(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*as fi from"fs";import*as Sw from"path";var yc=null,Pu=null,Cu=null;function nk(){return fi.existsSync(Co())}function rk(n){let e=Co(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};fi.mkdirSync(Sw.dirname(e),{recursive:!0}),To(e),fi.writeFileSync(e,JSON.stringify(t,null,2))}function ik(){if(yc)return yc;let n=fr("harmonyos-stopwords.txt");return yc=new Set(n.split(`
1322
+ `).map(e=>e.trim()).filter(Boolean)),yc}function ok(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function bw(n){let e=ik(),t=[];for(let r of ok(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function Ew(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=fr("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function sk(){let{Jieba:n}=await import("@node-rs/jieba");return Ew(n)}async function vw(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return Ew(n)}async function ak(){let n=await import("jieba-wasm"),e=fr("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function ck(){if(b())return ak();if(nk())return vw();try{let e=await sk();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);rk(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await vw();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function Nn(){return Pu||(Cu||(Cu=ck().then(n=>(Pu=n,n))),Cu)}async function lk(n){let e=await Nn();return bw(e.cutForSearch(n,!0))}async function Pw(n){let e=await Nn();return bw(e.cut(n,!0))}async function wc(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await lk(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function dk(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function vc(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?by:hy,i=e?Py:wy,o=e?await dk(n.apiSymbols,i):await wc(n.apiSymbols.join(" "),i),a=(await Promise.all([wc(t,e?Ey:yy),Promise.resolve(o),wc(n.headingsText,e?Cy:vy),wc(n.bodySample,e?Iy:Sy)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function uk(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,So)}function Iu(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=my))break}return r}function pk(n){return n.length>=2&&n.length<=fy}function mk(n,e){let t=pu(n,Xd),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=Iu(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:cw(i,o)}}function fk(n,e){let t=Iu(gc(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:xo(t)}}async function Cw(n){let e=uk(n),t=e.trim(),r=gw(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=hc(t);if(i)return mk(e,i);if(Oo(t))return fk(e,t);let o=fw(e),s=[...Eu(e),...o],c=pw(t)?e:pu(e,Xd),l=await Pw(c),d=Iu(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:o.length===0&&pk(d)}}var Iw=["harmonyos-releases","harmonyos-roadmap"],gk=new Set(Iw.map(n=>Tn[n])),hk=Iw.map(n=>`${xt[n]}/`);function yk(n){return gk.has(n)}function wk(n){return hk.some(e=>n.startsWith(e))}function Dw(n){let e=[],t=[];for(let r of n)yk(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Aw(n){let e=[],t=[];for(let r of n)wk(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var vk=[{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 _o(n,e,t){let r=Tn[e];n.set(r,(n.get(r)??1)*t)}function Sk(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){_o(e,"harmonyos-guides",1.45),_o(e,"harmonyos-references",1.35);return}(i||o)&&_o(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&_o(e,"harmonyos-references",1.75)}function Tw(n){let e=new Map,t=n.trim();if(!t)return e;let r=mw(t);Sk(t,e),hw(t,e);for(let i of vk)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||_o(e,i.catalog,i.multiplier));return e}function Rw(n){return ww(n)}import*as hi from"fs";import*as Fw from"path";var bk=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function kw(n,e){let t=-1;for(let r of bk){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function xw(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=kw(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function Nw(n,e,t={}){let{maxLen:r=Ty,contextChars:i=Ry,excerptTruncated:o=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return o?`${s}...`:s;let a=e.split(/\s+/).map(Be=>Be.trim()).filter(Boolean),c=0;for(let Be of a){let st=s.toLowerCase().indexOf(Be.toLowerCase());if(st>=0){c=st;break}}let l=Math.max(0,c-i),d=Math.min(s.length,l+r),g=s.slice(l,d),w=kw(g,r-25);w>=0&&(d=l+w);let v=s.slice(l,d).trim(),k=l>0?"...":"",ce=d<s.length||o?"...":"";return`${k}${v}${ce}`}var Ek=`
1323
1323
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1324
1324
  d.catalog_id, bm25(segments_fts) AS bm25
1325
1325
  FROM segments_fts
@@ -1328,7 +1328,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1328
1328
  WHERE segments_fts MATCH ?
1329
1329
  ORDER BY bm25(segments_fts)
1330
1330
  LIMIT ?
1331
- `,rk=`
1331
+ `,Pk=`
1332
1332
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1333
1333
  d.catalog_id, bm25(segments_fts) AS bm25
1334
1334
  FROM segments_fts
@@ -1337,7 +1337,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1337
1337
  WHERE segments_fts MATCH ? AND d.catalog_id = ?
1338
1338
  ORDER BY bm25(segments_fts)
1339
1339
  LIMIT ?
1340
- `,ik=3.5,ok=1.4,sk=4,ak=1.8,ck=1.35,lk=3.5,dk=1.8,uk=120,hw=6;function vu(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function pk(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(vu).filter(e=>e.length>=2)}function mk(n,e){return e.length>1&&e.every(t=>n.includes(t))}function fk(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function hk(n,e){return n===e?lk:n.startsWith(e)||n.includes(`@ohos.${e}`)?dk:1}function gk(n,e){let t=vu(e);if(t.length<2)return 1;let r=vu(n.doc_title);if(fk(e))return hk(r,t);if(r.includes(t))return sk;if(t.length>=hw&&r.includes(t.slice(0,hw)))return ak;let i=pk(e);return mk(r,i)?ck:1}function yk(n,e){return e<=1?n:n<0?n*e:n/e}function fc(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=yk(i,gk(n,t)),r&&mu(n.doc_title,n.section_title,r)&&(i/=ik,n.catalog_id===Cn["harmonyos-references"]&&(i/=ok)),i}function wu(n,e,t,r){return n.reduce((i,o)=>fc(o,e,t,r)<fc(i,e,t,r)?o:i)}function wk(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function vk(n,e,t,r,i){if(i){let o=n.filter(s=>mu(s.doc_title,s.section_title,i));if(o.length>0)return wu(o,t,r,i)}if(e.length>0){let o=n.filter(s=>wk(s,e));if(o.length>0)return wu(o,t,r,i)}return wu(n,t,r,i)}function gw(n,e,t,r,i){let o=dw(e),s=qy(e),c=pu(e)?.camelCase,l=new Map;for(let v of n){let k=l.get(v.document_id)??[];k.push(v),l.set(v.document_id,k)}let d=[];for(let v of l.values())d.push(vk(v,s,o,t,c));let h=d.sort((v,k)=>fc(v,o,t,c)-fc(k,o,t,c));return(i?cw(h):h).slice(0,r)}function hc(n,e,t,r,i,o){let s=e?Cn[e]:void 0,a=Math.max(t,t*Zg,uk),c=s===void 0?n.all(nk,r,a):n.all(rk,r,s,a);return(s===void 0?gw(c,o,i,t,!0):gw(c,o,i,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:fw(d.lead_text,i,{excerptTruncated:!!d.excerpt_truncated})}))}var gc=`
1340
+ `,Ck=3.5,Ik=1.4,Dk=4,Ak=1.8,Tk=1.35,Rk=3.5,kk=1.8,xk=120,Lw=6;function Au(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function Nk(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Au).filter(e=>e.length>=2)}function Lk(n,e){return e.length>1&&e.every(t=>n.includes(t))}function Ok(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function Mk(n,e){return n===e?Rk:n.startsWith(e)||n.includes(`@ohos.${e}`)?kk:1}function _k(n,e){let t=Au(e);if(t.length<2)return 1;let r=Au(n.doc_title);if(Ok(e))return Mk(r,t);if(r.includes(t))return Dk;if(t.length>=Lw&&r.includes(t.slice(0,Lw)))return Ak;let i=Nk(e);return Lk(r,i)?Tk:1}function Fk(n,e){return e<=1?n:n<0?n*e:n/e}function Sc(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=Fk(i,_k(n,t)),r&&bu(n.doc_title,n.section_title,r)&&(i/=Ck,n.catalog_id===Tn["harmonyos-references"]&&(i/=Ik)),i}function Du(n,e,t,r){return n.reduce((i,o)=>Sc(o,e,t,r)<Sc(i,e,t,r)?o:i)}function jk(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function $k(n,e,t,r,i){if(i){let o=n.filter(s=>bu(s.doc_title,s.section_title,i));if(o.length>0)return Du(o,t,r,i)}if(e.length>0){let o=n.filter(s=>jk(s,e));if(o.length>0)return Du(o,t,r,i)}return Du(n,t,r,i)}function Ow(n,e,t,r,i){let o=Tw(e),s=uw(e),c=Su(e)?.camelCase,l=new Map;for(let v of n){let k=l.get(v.document_id)??[];k.push(v),l.set(v.document_id,k)}let d=[];for(let v of l.values())d.push($k(v,s,o,t,c));let g=d.sort((v,k)=>Sc(v,o,t,c)-Sc(k,o,t,c));return(i?Dw(g):g).slice(0,r)}function bc(n,e,t,r,i,o){let s=e?Tn[e]:void 0,a=Math.max(t,t*gy,xk),c=s===void 0?n.all(Ek,r,a):n.all(Pk,r,s,a);return(s===void 0?Ow(c,o,i,t,!0):Ow(c,o,i,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Nw(d.lead_text,i,{excerptTruncated:!!d.excerpt_truncated})}))}var Ec=`
1341
1341
  CREATE TABLE documents (
1342
1342
  id INTEGER PRIMARY KEY,
1343
1343
  document_id TEXT NOT NULL UNIQUE,
@@ -1375,60 +1375,60 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
1375
1375
  END;
1376
1376
 
1377
1377
  CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1378
- `;var di=null,Su=null;function Sk(){di?.close(),di=null,Su=null}function bk(n,e){if(di&&Su===e)return di;di?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return di=t,Su=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function Ek(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(gc),t}function Pk(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let o=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(o)return e.set(t.documentId,o.id),o.id;let a=n.prepare(`
1378
+ `;var gi=null,Tu=null;function Hk(){gi?.close(),gi=null,Tu=null}function Uk(n,e){if(gi&&Tu===e)return gi;gi?.close();let t=new n(e,{readonly:!0,fileMustExist:!0});return gi=t,Tu=e,t.pragma("mmap_size = 268435456"),t.pragma("cache_size = -8000"),t.pragma("query_only = ON"),t}function Bk(n,e){let t=new n(e);return t.pragma("journal_mode = OFF"),t.pragma("synchronous = OFF"),t.pragma("temp_store = MEMORY"),t.exec(Ec),t}function Wk(n,e,t){let r=e.get(t.documentId);if(r!==void 0)return r;let o=n.prepare("SELECT id FROM documents WHERE document_id = ?").get(t.documentId);if(o)return e.set(t.documentId,o.id),o.id;let a=n.prepare(`
1379
1379
  INSERT INTO documents(document_id, catalog_id, doc_title)
1380
1380
  VALUES (?, ?, ?)
1381
- `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function Ck(n,e,t,r){await Tn();let i=Ek(n,e),o=new Map,s=i.prepare(`
1381
+ `).run(t.documentId,t.catalogId,t.docTitle),c=Number(a.lastInsertRowid);return e.set(t.documentId,c),c}async function Vk(n,e,t,r){await Nn();let i=Bk(n,e),o=new Map,s=i.prepare(`
1382
1382
  INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
1383
1383
  VALUES (?, ?, ?, ?, ?)
1384
- `),a=t.length;for(let c=0;c<a;c+=ri){let l=t.slice(c,c+ri),d=await Promise.all(l.map(async w=>({source:w,searchText:await mc(w)})));i.transaction(w=>{for(let v of w){let k=Pk(i,o,v.source);s.run(k,v.source.sectionTitle,v.source.leadText,v.searchText,v.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function Ik(n,e,t,r,i,o,s){let a=bk(n,e);return hc({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function yw(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Sk,buildSearchIndex:(t,r,i)=>Ck(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(Ik(e,o,r,i,s,a,c))}}import{readFile as Dk,stat as Ak,writeFile as Tk}from"fs/promises";var bu=null,Rn=null;async function Eu(){return bu||(bu=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),bu}function Rk(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function kk(n){let e=await Ak(n);if(Rn&&Rn.dbPath===n&&Rn.mtimeMs===e.mtimeMs)return Rn.db;Rn?.db.close();let t=await Eu(),r=t.capi,i=t.wasm,o=new Uint8Array(await Dk(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,o.byteLength,o.byteLength,l),Rn={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function ww(){Rn?.db.close(),Rn=null}async function xk(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText,i.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function Nk(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);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 Lk(n,e,t){await Tn();let r=await Eu(),i=new r.oo1.DB(":memory:","c");i.exec(gc);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=Nk(i,o,s),l=e.length;for(let h=0;h<l;h+=ri){let w=e.slice(h,h+ri),v=await Promise.all(w.map(async k=>({source:k,searchText:await mc(k)})));await xk(i,a,c,v),await t?.(Math.min(h+w.length,l),l)}i.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(i);await Tk(n,d),i.close(),ww()}async function Ok(n,e,t,r,i,o){let s=await kk(n);return hc(Rk(s),e,t,r,i,o)}async function Pu(){return await Eu(),{kind:"sqlite-wasm",resetCache:ww,buildSearchIndex:Lk,searchIndex:(n,e,t,r,i,o,s)=>Ok(r,e,t,i,o,s)}}var yc=null,Cu=null;function Mk(){return ui.existsSync(So())}function _k(n){let e=So(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};ui.mkdirSync(vw.dirname(e),{recursive:!0}),Io(e),ui.writeFileSync(e,JSON.stringify(t,null,2))}async function Fk(){if(Mk())return Pu();try{let n=await yw();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);_k(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return Pu()}async function Oo(){return yc||(yc=Fk().then(n=>(Cu=n,n))),yc}function Sw(){Cu?.resetCache(),yc=null,Cu=null}async function jk(n,e,t,r,i,o,s){let a=await Oo(),c=s??cr();return a.searchIndex(n,e,t,c,r,i,o)}function pi(){Sw()}async function Ew(n,e,t){await(await Oo()).buildSearchIndex(n,e,t)}function Pw(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function wc(n,e,t,r,i,o){return jk(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function $k(n,e,t,r,i){let o=await wc(n,e,t,r,Ro(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await wc(n,e,t,r,Ro(r.tokens,"OR"),i);return Pw(o,s,t)}async function Iu(n,e,t,r,i){return r.ftsMatch?wc(n,e,t,r,r.ftsMatch,i):r.preferAnd?$k(n,e,t,r,i):wc(n,e,t,r,Ro(r.tokens,"OR"),i)}async function Hk(n,e,t,r){let i=await Iu(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Iu(n,void 0,e,t,r);return Pw(i,o,e)}function bw(n,e){return e!==void 0?n:lw(n)}async function Du(n,e,t=20,r){let i=await sw(n);if(Qy(i.rawQuery,e)){let a=await Hk(n,t,i,r);return bw(a,e)}let o=e??uw(i.rawQuery),s=await Iu(n,o,t,i,r);return bw(s,e)}import{unified as xw}from"unified";import Nw from"remark-parse";import Lw from"remark-gfm";import{toString as Sc}from"mdast-util-to-string";var Uk=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,Bk=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Wk=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Vk=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Gk=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function vc(n){let e=n.trim(),t=e.match(Vk);return t?t[1]:e}function zk(n){let e=n.match(Uk);if(!e)return;let t=vc(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function qk(n){let e=vc(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function Mo(n){let e=n.trim();return e?zk(e)??(()=>{let t=e.match(Bk);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(Wk);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??qk(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Yk(n){if(n.length<2||n.length>36||Gk.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Cw(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Yk(t))return t}return""}function Iw(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Jk=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,_o=/@[A-Z][a-zA-Z]+/g,Kk=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,Xk=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Zk=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Qk=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),ex=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),tx=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Ow(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of du(i)){bt(t,o);let s=cc(o);s&&bt(t,s)}for(let o of uu(i))bt(t,o);for(let o of i.matchAll(Jk)){let s=o[0];nx(s)&&t.add(s)}for(let o of i.matchAll(_o))t.add(o[0])}return ci([...t])}function nx(n){let e=n.trim();if(!e||_o.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return tx.has(t)?!1:/^[A-Z]/.test(t)}return Qk.has(e)?!1:ex.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Dw(n){let e=n.trim();return!!(!e||Zk.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Mw(n,e){let t=e.jsonTitle?.trim(),r=sx(n,"").trim(),i=e.fileName.trim();return t&&!Dw(t)?t:r&&!Dw(r)?r:t||r||i}function _w(n){return Kk.test(n.trim())}function Au(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=vc(e);return Xk.test(t)}function bc(n){let e=n.trim();return e?_o.test(e)||_w(e)||Au(e)?!0:!!Mo(e).symbolName:!1}function rx(n){let e=n.trim();return!(!e||_w(e)||Au(e))}function ix(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!rx(i)||e.has(i)||(e.add(i),t.push(i))}return t}function Aw(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function ox(n,e){let t=Aw(n)-Aw(e);return t!==0?t:n.localeCompare(e)}function Fw(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(ox),[...t,...i].slice(0,ly)}function Ec(n){return n.replace(/\s+/g," ").trim()}function Tw(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function sx(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let i=Tw(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return Tw(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function jw(n){let e=Ec(n.join(" "));if(e.length<=Ka)return e;let t=e.slice(0,Ka);return e.length<=Ka+Gd?t:`${t} ${e.slice(-Gd)}`}function ax(n){let e=ix(n).join(" ");return e.length<=zd?e:e.slice(0,zd)}function $w(n){let e=Ec(n),{text:t,excerptTruncated:r}=mw(e,dy);return{leadText:t,excerptTruncated:r}}function cx(n,e){let{leadText:t,excerptTruncated:r}=$w(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function Hw(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)Hw(r,e);return}let t=Ec(Sc(n));t&&e.bodyParts.push(t)}function lx(n){let e=xw().use(Nw).use(Lw).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=Sc(a).trim();if(a.depth>=4&&c&&bc(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),Hw(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function dx(n){return Jg.test(n)}function ux(n){return n.filter(e=>e.sectionTitle&&bc(e.sectionTitle)).length}function px(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function Rw(n){let e=n.trim();return!e||_o.test(e)?_o.test(e):/对象说明$|枚举说明$/.test(e)?!0:Au(e)}function mx(n){let e=n.filter(h=>!h.sectionTitle||!bc(h.sectionTitle)),t=n.filter(h=>h.sectionTitle&&bc(h.sectionTitle)),r=t.filter(h=>Rw(h.sectionTitle)),i=t.filter(h=>!Rw(h.sectionTitle)),o=Math.max(0,Yg-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(h=>kw(h.sectionTitle)),l=a.filter(h=>!kw(h.sectionTitle)),d=[];for(let h=0;h<l.length;h+=Wd)d.push(px(l.slice(h,h+Wd)));return[...e,...r,...s,...c,...d]}function fx(n,e,t){let r=n.split(/\r?\n/).length,i=ux(e);return i===0?!1:dx(t)?r>=zg&&i>=qg:r>=Vg&&i>=Gg}var hx=/^\[h2\][A-Za-z]/;function kw(n){return hx.test(n.trim())}function Uw(n){if(!n.includes(" | ")){let t=Mo(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=Mo(t.trim()).symbolName;r&&e.push(r)}return e}function gx(n,e,t,r){let i=Uw(n),o=Ow(t,r);return e.symbolName&&o.push(e.symbolName),Fw([...i,...o],i)}function yx(n,e){let t=jw(n.bodyParts),r=n.sectionTitle.trim(),i=Mo(r),o=Cw(n.bodyParts),s=Iw(r,o,i),a=Uw(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:h}=cx(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:gx(r,i,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:h}}function Bw(n,e){for(let t of n){if(t.type==="heading"){let i=Sc(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){Bw(t.children,e);continue}let r=Ec(Sc(t));r&&e.bodyParts.push(r)}}function wx(n){let e=xw().use(Nw).use(Lw).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return Bw(e.children,t),t}function vx(n,e){let t=wx(n),r=e.docTitle?.trim()||e.documentId,i=jw(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=$w(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:ax(t.headings),apiSymbols:Fw(Ow(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function Ww(n,e){let t=e.docTitle?.trim()||e.documentId,r=lx(n);return fx(n,r,e.documentId)?mx(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>yx(i,{...e,docTitle:t})):[vx(n,{...e,docTitle:t})]}function Vw(n){let e=n.split("/");if(e[0]==="docs"&&(e=e.slice(1)),e.length<2)return null;let t=my[e[0]];if(t===void 0)return null;let r=e[e.length-1].replace(/\.md$/,"");return e[e.length-1]=r,{documentId:e.join("/"),catalogId:t,docTitle:r}}function Gw(n,e,t){let r=Mw(n,{jsonTitle:e,fileName:t.docTitle});return Ww(n,{...t,docTitle:r})}function bx(n){return n.getEntries().filter(e=>e.isDirectory||!e.entryName.endsWith(".md")?!1:e.entryName.split("/").every(t=>!t.startsWith(".")))}function Ex(n,e){let t=n.getEntry(e.replace(/\.md$/,".json"));if(t)try{return JSON.parse(t.getData().toString("utf-8")).title?.trim()||void 0}catch{return}}function Px(n){let e=new Sx(n),t=[];for(let r of bx(e)){let i=Vw(r.entryName);i&&t.push(...Gw(r.getData().toString("utf-8"),Ex(e,r.entryName),i))}return t}async function Cx(n){let e=[];async function t(r){let i=await mi.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=kn.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}async function Ix(n){let e=n.replace(/\.md$/,".json");try{let t=await mi.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function Dx(n){let e=[];for(let t of await Cx(n)){let r=kn.relative(n,t).split(kn.sep).join("/"),i=Vw(r);if(!i)continue;let o=await mi.promises.readFile(t,"utf-8");e.push(...Gw(o,await Ix(t),i))}return e}async function Ax(n){return"docsZipPath"in n?Px(n.docsZipPath):Dx(n.docsDir)}async function Tx(n,e,t){let r=kn.join(e,"search.db");return await Ew(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}function Rx(n,e){return{indexVersion:ni,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function zw(n){n.lexiconDir&&Kd(n.lexiconDir);try{let e=await Ax(n);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await mi.promises.mkdir(n.tmpDir,{recursive:!0});let t=await Tx(e,n.tmpDir,n.onProgress),r=Rx(n,t);return await mi.promises.writeFile(kn.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Iy(n.tmpDir),r}finally{n.lexiconDir&&Kd(null)}}var Fo=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function kx(){let n=si(),e=re();return["Documentation search index is not installed yet.","",...Xa(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
1385
- `)}function xx(){let n=si();return[`Chinese tokenizer (${b()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...Xa(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",b()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1386
- `)}function Nx(n){let e=si();return[n,"",...Xa(e)].join(`
1387
- `)}async function qw(){try{Py()}catch(n){throw Ey(n)?new Fo(`${kx()}
1384
+ `),a=t.length;for(let c=0;c<a;c+=ci){let l=t.slice(c,c+ci),d=await Promise.all(l.map(async w=>({source:w,searchText:await vc(w)})));i.transaction(w=>{for(let v of w){let k=Wk(i,o,v.source);s.run(k,v.source.sectionTitle,v.source.leadText,v.searchText,v.source.excerptTruncated?1:0)}})(d),await r?.(Math.min(c+l.length,a),a)}i.exec("ANALYZE"),i.exec("VACUUM"),i.close()}function Gk(n,e,t,r,i,o,s){let a=Uk(n,e);return bc({all(c,...l){return a.prepare(c).all(...l)}},t,r,i,o,s)}async function Mw(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Hk,buildSearchIndex:(t,r,i)=>Vk(e,t,r,i),searchIndex:(t,r,i,o,s,a,c)=>Promise.resolve(Gk(e,o,r,i,s,a,c))}}import{readFile as zk,stat as qk,writeFile as Yk}from"fs/promises";var Ru=null,Ln=null;async function ku(){return Ru||(Ru=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Ru}function Jk(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function Kk(n){let e=await qk(n);if(Ln&&Ln.dbPath===n&&Ln.mtimeMs===e.mtimeMs)return Ln.db;Ln?.db.close();let t=await ku(),r=t.capi,i=t.wasm,o=new Uint8Array(await zk(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=a.pointer;if(c===void 0)throw new Error("sqlite3_deserialize: database pointer is undefined");let l=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(c,"main",s,o.byteLength,o.byteLength,l),Ln={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function _w(){Ln?.db.close(),Ln=null}async function Xk(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText,i.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function Zk(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);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 Qk(n,e,t){await Nn();let r=await ku(),i=new r.oo1.DB(":memory:","c");i.exec(Ec);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=Zk(i,o,s),l=e.length;for(let g=0;g<l;g+=ci){let w=e.slice(g,g+ci),v=await Promise.all(w.map(async k=>({source:k,searchText:await vc(k)})));await Xk(i,a,c,v),await t?.(Math.min(g+w.length,l),l)}i.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(i);await Yk(n,d),i.close(),_w()}async function ex(n,e,t,r,i,o){let s=await Kk(n);return bc(Jk(s),e,t,r,i,o)}async function xu(){return await ku(),{kind:"sqlite-wasm",resetCache:_w,buildSearchIndex:Qk,searchIndex:(n,e,t,r,i,o,s)=>ex(r,e,t,i,o,s)}}var Pc=null,Nu=null;function tx(){return hi.existsSync(Po())}function nx(n){let e=Po(),t={backend:"sqlite-wasm",reason:"better-sqlite3-load-failed",message:n,createdAt:new Date().toISOString()};hi.mkdirSync(Fw.dirname(e),{recursive:!0}),To(e),hi.writeFileSync(e,JSON.stringify(t,null,2))}async function rx(){if(tx())return xu();try{let n=await Mw();return m("doc-index: using better-sqlite3 SQLite backend"),n}catch(n){let e=n instanceof Error?n.message:String(n);nx(e),m(`doc-index: better-sqlite3 unavailable (${e}); falling back to sqlite-wasm`)}return xu()}async function Fo(){return Pc||(Pc=rx().then(n=>(Nu=n,n))),Pc}function jw(){Nu?.resetCache(),Pc=null,Nu=null}async function ix(n,e,t,r,i,o,s){let a=await Fo(),c=s??pr();return a.searchIndex(n,e,t,c,r,i,o)}function yi(){jw()}async function Hw(n,e,t){await(await Fo()).buildSearchIndex(n,e,t)}function Uw(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function Cc(n,e,t,r,i,o){return ix(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function ox(n,e,t,r,i){let o=await Cc(n,e,t,r,No(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await Cc(n,e,t,r,No(r.tokens,"OR"),i);return Uw(o,s,t)}async function Lu(n,e,t,r,i){return r.ftsMatch?Cc(n,e,t,r,r.ftsMatch,i):r.preferAnd?ox(n,e,t,r,i):Cc(n,e,t,r,No(r.tokens,"OR"),i)}async function sx(n,e,t,r){let i=await Lu(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await Lu(n,void 0,e,t,r);return Uw(i,o,e)}function $w(n,e){return e!==void 0?n:Aw(n)}async function Ou(n,e,t=20,r){let i=await Cw(n);if(yw(i.rawQuery,e)){let a=await sx(n,t,i,r);return $w(a,e)}let o=e??Rw(i.rawQuery),s=await Lu(n,o,t,i,r);return $w(s,e)}import{unified as Jw}from"unified";import Kw from"remark-parse";import Xw from"remark-gfm";import{toString as Dc}from"mdast-util-to-string";var ax=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,cx=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,lx=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,dx=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,ux=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function Ic(n){let e=n.trim(),t=e.match(dx);return t?t[1]:e}function px(n){let e=n.match(ax);if(!e)return;let t=Ic(e[1].trim());return{displayTitle:n,symbolName:t,searchExtras:[t,e[3]]}}function mx(n){let e=Ic(n.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:n,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(n))return{displayTitle:n,symbolName:e,searchExtras:[e]}}function jo(n){let e=n.trim();return e?px(e)??(()=>{let t=e.match(cx);if(t){let r=t[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let t=e.match(lx);if(!t)return;let r=t[1].trim(),i=t[2].trim();return{displayTitle:e,symbolName:i,searchExtras:[r,i]}})()??mx(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function fx(n){if(n.length<2||n.length>36||ux.test(n))return!1;let e=[...n.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function Bw(n){for(let e of n){let t=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(fx(t))return t}return""}function Ww(n,e,t){let r=[n,...t.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var gx=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,$o=/@[A-Z][a-zA-Z]+/g,hx=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,yx=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,wx=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,vx=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),Sx=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),bx=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Zw(n,e){let t=new Set,r=[n,...e];for(let i of r){for(let o of wu(i)){vt(t,o);let s=fc(o);s&&vt(t,s)}for(let o of vu(i))vt(t,o);for(let o of i.matchAll(gx)){let s=o[0];Ex(s)&&t.add(s)}for(let o of i.matchAll($o))t.add(o[0])}return mi([...t])}function Ex(n){let e=n.trim();if(!e||$o.test(e))return!!e;if(e.includes(".")){let t=e.split(".")[0]??"";return bx.has(t)?!1:/^[A-Z]/.test(t)}return vx.has(e)?!1:Sx.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function Vw(n){let e=n.trim();return!!(!e||wx.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function Qw(n,e){let t=e.jsonTitle?.trim(),r=Dx(n,"").trim(),i=e.fileName.trim();return t&&!Vw(t)?t:r&&!Vw(r)?r:t||r||i}function ev(n){return hx.test(n.trim())}function Mu(n){let e=n.trim().replace(/\([^)]*\)$/,""),t=Ic(e);return yx.test(t)}function Ac(n){let e=n.trim();return e?$o.test(e)||ev(e)||Mu(e)?!0:!!jo(e).symbolName:!1}function Px(n){let e=n.trim();return!(!e||ev(e)||Mu(e))}function Cx(n){let e=new Set,t=[];for(let r of n){let i=r.trim();!Px(i)||e.has(i)||(e.add(i),t.push(i))}return t}function Gw(n){if(!n.includes("."))return 0;let e=n.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Ix(n,e){let t=Gw(n)-Gw(e);return t!==0?t:n.localeCompare(e)}function tv(n,e=[]){let t=[...new Set(e.map(o=>o.trim()).filter(Boolean))],r=new Set(t),i=[...new Set(n.map(o=>o.trim()).filter(Boolean))].filter(o=>!r.has(o));return i.sort(Ix),[...t,...i].slice(0,Dy)}function Tc(n){return n.replace(/\s+/g," ").trim()}function zw(n){return n.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Dx(n,e=""){let t=n.split(/\r?\n/),r=0;for(;r<t.length&&!t[r].trim();)r+=1;if(r>=t.length)return e;let i=zw(t[r].trim()),o=i.match(/^#+\s+(.+)$/);if(o)return zw(o[1].trim());if(r+1<t.length){let s=t[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return i}return i||e}function nv(n){let e=Tc(n.join(" "));if(e.length<=ec)return e;let t=e.slice(0,ec);return e.length<=ec+Zd?t:`${t} ${e.slice(-Zd)}`}function Ax(n){let e=Cx(n).join(" ");return e.length<=Qd?e:e.slice(0,Qd)}function rv(n){let e=Tc(n),{text:t,excerptTruncated:r}=xw(e,Ay);return{leadText:t,excerptTruncated:r}}function Tx(n,e){let{leadText:t,excerptTruncated:r}=rv(n);return{leadText:t,excerptTruncated:r||!!e.trim()}}function iv(n,e){if(n.type==="code"){e.codeBlocks.push(n.value??"");return}if("children"in n&&Array.isArray(n.children)){for(let r of n.children)iv(r,e);return}let t=Tc(Dc(n));t&&e.bodyParts.push(t)}function Rx(n){let e=Jw().use(Kw).use(Xw).parse(n),t=[],r=null,i=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&t.push(r),r=null)},o=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=Dc(a).trim();if(a.depth>=4&&c&&Ac(c)){i(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}o(),c&&r.bodyParts.push(c);continue}o(),iv(s,r)}return i(),t.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:t}function kx(n){return py.test(n)}function xx(n){return n.filter(e=>e.sectionTitle&&Ac(e.sectionTitle)).length}function Nx(n){return{sectionTitle:n.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:n.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:n.flatMap(e=>e.codeBlocks).slice(0,8)}}function qw(n){let e=n.trim();return!e||$o.test(e)?$o.test(e):/对象说明$|枚举说明$/.test(e)?!0:Mu(e)}function Lx(n){let e=n.filter(g=>!g.sectionTitle||!Ac(g.sectionTitle)),t=n.filter(g=>g.sectionTitle&&Ac(g.sectionTitle)),r=t.filter(g=>qw(g.sectionTitle)),i=t.filter(g=>!qw(g.sectionTitle)),o=Math.max(0,uy-r.length),s=i.slice(0,o),a=i.slice(o),c=a.filter(g=>Yw(g.sectionTitle)),l=a.filter(g=>!Yw(g.sectionTitle)),d=[];for(let g=0;g<l.length;g+=Kd)d.push(Nx(l.slice(g,g+Kd)));return[...e,...r,...s,...c,...d]}function Ox(n,e,t){let r=n.split(/\r?\n/).length,i=xx(e);return i===0?!1:kx(t)?r>=ly&&i>=dy:r>=ay&&i>=cy}var Mx=/^\[h2\][A-Za-z]/;function Yw(n){return Mx.test(n.trim())}function ov(n){if(!n.includes(" | ")){let t=jo(n);return t.symbolName?[t.symbolName]:[]}let e=[];for(let t of n.split(" | ")){let r=jo(t.trim()).symbolName;r&&e.push(r)}return e}function _x(n,e,t,r){let i=ov(n),o=Zw(t,r);return e.symbolName&&o.push(e.symbolName),tv([...i,...o],i)}function Fx(n,e){let t=nv(n.bodyParts),r=n.sectionTitle.trim(),i=jo(r),o=Bw(n.bodyParts),s=Ww(r,o,i),a=ov(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${i.symbolName??r}`:e.docTitle,l=[e.docTitle,s,...n.bodyParts].join(" "),{leadText:d,excerptTruncated:g}=Tx(t,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:_x(r,i,l,n.codeBlocks),bodySample:t,leadText:d,excerptTruncated:g}}function sv(n,e){for(let t of n){if(t.type==="heading"){let i=Dc(t).trim();i&&e.headings.push(i);continue}if(t.type==="code"){e.codeBlocks.push(t.value??"");continue}if("children"in t&&Array.isArray(t.children)){sv(t.children,e);continue}let r=Tc(Dc(t));r&&e.bodyParts.push(r)}}function jx(n){let e=Jw().use(Kw).use(Xw).parse(n),t={headings:[],bodyParts:[],codeBlocks:[]};return sv(e.children,t),t}function $x(n,e){let t=jx(n),r=e.docTitle?.trim()||e.documentId,i=nv(t.bodyParts),o=[r,...t.headings,i].join(" "),{leadText:s,excerptTruncated:a}=rv(i);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Ax(t.headings),apiSymbols:tv(Zw(o,t.codeBlocks)),bodySample:i,leadText:s,excerptTruncated:a}}function av(n,e){let t=e.docTitle?.trim()||e.documentId,r=Rx(n);return Ox(n,r,e.documentId)?Lx(r).filter(i=>i.sectionTitle||i.bodyParts.length>0||i.codeBlocks.length>0).map(i=>Fx(i,{...e,docTitle:t})):[$x(n,{...e,docTitle:t})]}function cv(n,e){let t=ky[n];if(t===void 0||e.length<1)return null;let r=e[e.length-1].replace(/\.md$/,"");return{documentId:[n,...e.slice(0,-1),r].join("/"),catalogId:t,docTitle:r}}function lv(n){let e=n.split("/");if(e[0]==="docs"&&(e=e.slice(1)),e[0]===tc&&e[1]===nc){let t=eu[e[2]];return t===void 0?null:cv(xt[t],e.slice(3))}return cv(e[0],e.slice(1))}function dv(n,e,t){let r=Qw(n,{jsonTitle:e,fileName:t.docTitle});return av(n,{...t,docTitle:r})}function Ux(n){return n.getEntries().filter(e=>e.isDirectory||!e.entryName.endsWith(".md")?!1:e.entryName.split("/").every(t=>!t.startsWith(".")))}function Bx(n,e){let t=n.getEntry(e.replace(/\.md$/,".json"));if(t)try{return JSON.parse(t.getData().toString("utf-8")).title?.trim()||void 0}catch{return}}function Wx(n){let e=new Hx(n),t=[];for(let r of Ux(e)){let i=lv(r.entryName);i&&t.push(...dv(r.getData().toString("utf-8"),Bx(e,r.entryName),i))}return t}async function Vx(n){let e=[];async function t(r){let i=await wi.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(o.name.startsWith("."))continue;let s=On.join(r,o.name);o.isDirectory()?await t(s):o.isFile()&&o.name.endsWith(".md")&&e.push(s)}}return await t(n),e}async function Gx(n){let e=n.replace(/\.md$/,".json");try{let t=await wi.promises.readFile(e,"utf-8");return JSON.parse(t).title?.trim()||void 0}catch{return}}async function zx(n){let e=[];for(let t of await Vx(n)){let r=On.relative(n,t).split(On.sep).join("/"),i=lv(r);if(!i)continue;let o=await wi.promises.readFile(t,"utf-8");e.push(...dv(o,await Gx(t),i))}return e}async function qx(n){return"docsZipPath"in n?Wx(n.docsZipPath):zx(n.docsDir)}async function Yx(n,e,t){let r=On.join(e,"search.db");return await Hw(r,n,async(i,o)=>{await t?.({current:i,total:o,message:`Building search index\u2026 ${i.toLocaleString()} / ${o.toLocaleString()} segments`})}),n.length}function Jx(n,e){return{indexVersion:ai,docsZipSha256:n.docsZipSha256,termsHash:n.termsHash,synonymsHash:n.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:n.builtBy}}async function uv(n){n.lexiconDir&&iu(n.lexiconDir);try{let e=await qx(n);await n.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await wi.promises.mkdir(n.tmpDir,{recursive:!0});let t=await Yx(e,n.tmpDir,n.onProgress),r=Jx(n,t);return await wi.promises.writeFile(On.join(n.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Wy(n.tmpDir),r}finally{n.lexiconDir&&iu(null)}}var Ho=class extends Error{constructor(e){super(e),this.name="NativeDepsError"}};function Kx(){let n=ui(),e=re();return["Documentation search index is not installed yet.","",...rc(n),`Index directory: ${e}`,"","Try:"," 1. Wait a moment and run the docs command again (postinstall may still be running)"," 2. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 3. Check the log file above for setup errors"].join(`
1385
+ `)}function Xx(){let n=ui();return[`Chinese tokenizer (${b()?"jieba-wasm":"@node-rs/jieba"}) failed to load.`,"",`Node.js: ${process.version} (required: >=18)`,"",...rc(n),"","Try:"," 1. Reinstall: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>"," 2. Use Node.js 18 or newer",b()?" 3. Verify jieba-wasm package is installed (WASM backend for OpenHarmony)":" 3. Configure npm registry/proxy if your network blocks optional platform packages"].join(`
1386
+ `)}function Zx(n){let e=ui();return[n,"",...rc(e)].join(`
1387
+ `)}async function pv(){try{Uy()}catch(n){throw Hy(n)?new Ho(`${Kx()}
1388
1388
 
1389
- Detail: ${n.message}`):n}try{await Tn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Fo(`${xx()}
1389
+ Detail: ${n.message}`):n}try{await Nn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ho(`${Xx()}
1390
1390
 
1391
- Detail: ${e}`)}try{await Oo()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Fo(Nx(e))}}var Tu=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function Ox(n){return new Promise(e=>setTimeout(e,n))}async function Xw(n){let e=si();await je.promises.mkdir(fi.dirname(e),{recursive:!0}),await je.promises.appendFile(e,`${new Date().toISOString()} ${n}
1392
- `)}async function Mx(){await ai({mode:"write"});let n=re(),e=Qt(),t=await je.promises.readdir(e);for(let r of t){let i=fi.join(n,r);await je.promises.rm(i,{force:!0}),await je.promises.rename(fi.join(e,r),i)}await je.promises.rm(e,{recursive:!0,force:!0}),await je.promises.rm(fi.join(n,"orama.dpack"),{force:!0})}async function Yw(n,e,t){e?.start(t),await An({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Ny(n),pi(),e&&(e.text="Documentation index installed.")}async function _x(n,e){try{return await Yw(n,e,"Installing documentation index\u2026"),await Ru(e),!0}catch(t){if(Co(t))throw t}try{return await Ly(),pi(),await Yw(n,e,"Retrying documentation index install\u2026"),await Ru(e),!0}catch(t){if(Co(t))throw t;let r=t instanceof Error?t.message:String(t);return await Xw(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function Fx(n,e,t){let r=Dn();if(!r)throw new Error("docs.zip not found");let i=Qt();await je.promises.mkdir(re(),{recursive:!0}),await je.promises.rm(i,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await An({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"}),await zw({docsZipPath:r,tmpDir:i,docsZipSha256:e,termsHash:oc(),synonymsHash:ic(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await An({state:"indexing",current:o.current,total:o.total,message:o.message})}}),await An({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Mx(),pi()}async function Ru(n){await An({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function jx(n){let e=await au(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await An({state:"done",message:t,error:null})}async function $x(n,e){let t=n instanceof Error?n.message:String(n);throw await An({state:"error",error:t}),await Xw(`ERROR: ${t}`),e?.fail(t),n}async function Hx(){let n=re();await je.promises.mkdir(n,{recursive:!0});let e=Za();return je.existsSync(e)||await je.promises.writeFile(e,"","utf-8"),e}async function Ux(){let n=await Hx();return Lx.lock(n,{stale:1800*1e3})}async function Bx(){let n=Dn(),e=(n?await rc(n):null)??await su();if(!e)throw new Error("docs.zip not found");return e}async function Wx(n,e){let t=await Bx(),r=n.force||await cu(n.force),i=await ac(n.force);if(!r&&!i&&Ao()){await jx(e);return}!n.force&&xy(t)&&await _x(t,e)||(await Fx(n,t,e),await Ru(e))}var jo=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:Kw({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await ai({mode:"write"}),o=await Ux(),await ou(jy("Starting documentation setup\u2026")),await Wx(e,i)}catch(s){throw o&&await $x(s,i),s}finally{o&&await o()}}};async function Vx(n){for(;;){let e=await sc();if(e.state==="done"&&Ao())return;if(e.state==="error")throw new Tu("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 Ox(500)}}async function Jw(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await jo.run({builtBy:"doc-init",force:e,quiet:!0})}async function Gx(){let n=await ac()!==null;if(Ao()&&!n)return;let e=Kw({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await $y()){await Vx(e),e.succeed("Documentation ready.");return}if(await cu()){await Jw(e),e.succeed("Documentation ready.");return}await Jw(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function $o(){await ai({mode:"read"}),await Gx(),await qw()}function zx(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 ku=class{async search(e,t,r=20){await $o();try{return await Du(e,t,r)}catch(i){if(!zx(i))throw i;return pi(),await jo.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Du(e,t,r)}}async readDocument(e){return await $o(),Ty(e)}},xu=new ku;function Qw(...n){return e=>{if(!n.includes(e))throw new Nu(`Allowed values: ${n.join(", ")}`);return e}}function Kx(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Nu("Must be a positive integer.");return e}var Xx=Qw("json","default"),Zx=Qw("json","default");function Qx(n){let e=n instanceof Error?n.message:String(n);return Co(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}async function Lu(n,e){let t=Date.now();try{let r=await e();return await Zw(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await Zw(n,Date.now()-t,!1,i),r}}async function Zw(n,e,t,r){await I.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function Ou(n){console.error(Yx(Qx(n))),process.exitCode=1}var Pc=new qx("docs").description("Search and read HarmonyOS documentation from local docs directory");Pc.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",tN,"all").option("--format <fmt>","Output format (default, json)",Xx,"default").option("--limit <n>","Max number of results",Kx,20).action(async(n,e)=>{let t={event:D.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await Lu(t,async()=>{let r=eN(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await xu.search(r,i,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):nN(o)})}catch(r){Ou(r)}});Pc.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:D.DocOperation,subAction:"read",documentId:e};try{await Lu(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let r=await xu.readDocument(e);console.log(r)})}catch(r){Ou(r)}});Pc.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Zx,"default").action(async n=>{let e={event:D.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Lu(e,async()=>{if(await $o(),n.format==="json"){let t=Pn.map(r=>({name:r,title:sr[r]}));console.log(JSON.stringify(t,null,2))}else for(let t of Pn)console.log(` ${t.padEnd(20)} ${Jx(sr[t])}`)})}catch(t){Ou(t)}});function eN(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>yo)throw new Error(`Query exceeds ${yo} characters.`);return e}function tN(n){if(n==="all")return"all";if(!Pn.includes(n))throw new Nu(`Invalid catalog "${n}". Allowed: all, ${Pn.join(", ")}`);return n}function nN(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 ev=Pc;import{Command as DL}from"commander";import{Command as EN,InvalidArgumentError as PN,Option as _u}from"commander";import{readFileSync as iN,unlinkSync as oN}from"fs";import{tmpdir as sN}from"os";import{join as aN}from"path";var rn=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=rN(t);return e?.all||(r=r.filter(i=>i.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`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 rN(n){let e=n.split(`
1393
- `),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]),h=Number(c[2]),w=Number(c[3]),v=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:v})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function tv(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Ho(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function nv(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 rv(n){return n.originalText||void 0}function hi(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function iv(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let w={...i,children:[]};if(a?t.push(w):o.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:h})}return t}function cN(n){let e=iN(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function lN(n){return n.attributes??{}}function Cc(n,e,t){let r=lN(n),i={id:r.id||void 0,type:r.type||void 0,text:rv(r),bounds:nv(r.bounds),clickable:Ho(r.clickable)||void 0,longClickable:Ho(r.longClickable)||void 0,scrollable:Ho(r.scrollable)||void 0,checkable:Ho(r.checkable)||void 0,hitTestBehavior:tv(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Cc(o,e,t+1))),i}function dN(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${i||"none"}`)}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 ur=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await se(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=aN(sN(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),cN(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await se(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),oN(t)}catch(o){m(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`),await se(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new rn(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=dN(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>Cc(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:Cc(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>iv(Cc(s,0,0),t))}};var ov=/^-+ (Screen|Display) ID: (\d+) -+$/,av=/\[DISPLAY INFO\][\s\S]*?\bWidth:\s*(\d+)[\s\S]*?\bHeight:\s*(\d+)/,sv="Client Screen Infos";function uN(n){let e=n.split(`
1394
- `),t=[];for(let r=0;r<e.length;r++){let i=ov.exec(e[r].trim());if(!i)continue;let o=[];for(let s=r+1;s<e.length&&!ov.test(e[s].trim());s++)o.push(e[s]);t.push({kind:i[1].toLowerCase(),id:Number(i[2]),body:o.join(`
1395
- `)})}return t}function pr(n,e){let t=n.match(e);return t?Number(t[1]):void 0}function pN(n,e){let t=[...n.matchAll(e)];return t.length?Number(t[t.length-1][1]):void 0}function mN(n){let e=new Map;for(let t of n){if(t.kind!=="screen")continue;let r=pr(t.body,/\bDisplayId:\s*(\d+)/);r===void 0||e.has(r)||e.set(r,{screenId:t.id,refreshRate:pr(t.body,/\bRefreshRate:\s*([\d.]+)/),vpr:pr(t.body,/\bVirtualPixelRatio:\s*([\d.]+)/),rotation:pN(t.body,/\bRotation:\s*(\d+)/g)})}return e}function fN(n){let e=new Map,t=new Map;for(let r of n){if(!r.body.includes(sv))continue;let i=r.kind==="display"?new Map:null;i&&t.set(r.id,i);let o=null;for(let s of r.body.split(`
1396
- `)){if(s.includes(sv)){o=null;continue}let a=pr(s,/^ScreenId:\s*(\d+)/);if(a!==void 0){o={screenId:a},e.set(a,o),i?.set(a,o);continue}if(!o)continue;let c=pr(s,/^\s*Rotation:\s*(\d+)/);if(c!==void 0){o.rotation=c;continue}let l=pr(s,/^\s*RefreshRate:\s*([\d.]+)/);if(l!==void 0){o.refreshRate=l;continue}let d=pr(s,/^\s*VirtualPixelRatio:\s*([\d.]+)/);d!==void 0&&(o.vpr=d)}}return{byScreenId:e,inDisplaySection:t}}function hN(n,e){return{screenId:e.screenId??n.screenId,refreshRate:e.refreshRate??n.refreshRate,vpr:e.vpr??n.vpr,rotation:e.rotation??n.rotation}}function gN(n,e,t){let r=e.get(n),i=t.inDisplaySection.get(n),o;return r?.screenId!==void 0?o=i?.get(r.screenId)??t.byScreenId.get(r.screenId):i?.size===1?o=[...i.values()][0]:t.byScreenId.size===1&&(o=[...t.byScreenId.values()][0]),hN(r??{},o??{})}function yN(n,e){let t=av.exec(n.body);return t?{id:n.id,width:Number(t[1]),height:Number(t[2]),...e}:null}function cv(n){let e=n.replace(/\r\n/g,`
1397
- `),t=uN(e),r=mN(t),i=fN(t),o=[];for(let a of t){if(a.kind!=="display")continue;let c=gN(a.id,r,i),l=yN(a,c);l&&o.push(l)}if(o.length>0)return o;let s=av.exec(e);return s?[{id:0,width:Number(s[1]),height:Number(s[2])}]:[]}function wN(n){return(n.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)??"").slice(0,120)}var Uo=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listDisplays(){let e=await this.fetchDump(),t=cv(e);if(t.length===0)throw new Error(`No display info in DisplayManagerService output: ${wN(e)}`);return t}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","DisplayManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await se(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query displays: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};var Ic={left:"0",right:"1",up:"2",down:"3"};function ke(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Mu(n,e){n!==void 0&&ke(n,e)}function lv(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Dc(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Bo(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 dv(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function uv(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 gi(n,e,t,r,i=!0){lv(n,e),Dc(t,"--id"),Mu(n,"x"),Mu(e,"y"),dv(r),uv(n!==void 0,!!t,!!r,i)}async function Nt(n,e){let r=await new $r(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Lt(n){let e=await A.new(),t=await Nt(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function yi(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new rn(n,e).listWindows({all:!0}),c=new ur(n);return vN(c,e,a,i,o)}async function vN(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new Error(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,i,!1);return bN(s,r)}return SN(n,e,t,r)}async function SN(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of hi([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new Error(`Node "${r}" not found.`);if(s.length>1)throw new Error(`Multiple nodes found with id "${r}".`);if(s[0].displayId!==0)throw new Error(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`);return pv(s[0].node,r)}function bN(n,e){let t=hi(n,e);if(t.length===0)throw new Error(`Node "${e}" not found.`);if(t.length>1)throw new Error(`Multiple nodes found with id "${e}".`);return pv(t[0],e)}function pv(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function ot(n,e,t){let r=["-t",e,"shell",t.join(" ")];m(`Executing: ${n} ${r.join(" ")}`);let i=await se(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import CN from"ora";function IN(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new PN("depth must be a non-negative integer");return e}function DN(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 mv(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${DN(i)}`),i.children.length>0&&t.push(...mv(i.children,e+1).split(`
1391
+ Detail: ${e}`)}try{await Fo()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ho(Zx(e))}}var _u=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function eN(n){return new Promise(e=>setTimeout(e,n))}async function hv(n){let e=ui();await Fe.promises.mkdir(vi.dirname(e),{recursive:!0}),await Fe.promises.appendFile(e,`${new Date().toISOString()} ${n}
1392
+ `)}async function tN(){await pi({mode:"write"});let n=re(),e=nn(),t=await Fe.promises.readdir(e);for(let r of t){let i=vi.join(n,r);await Fe.promises.rm(i,{force:!0}),await Fe.promises.rename(vi.join(e,r),i)}await Fe.promises.rm(e,{recursive:!0,force:!0}),await Fe.promises.rm(vi.join(n,"orama.dpack"),{force:!0})}async function mv(n,e,t){e?.start(t),await xn({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Ky(n),yi(),e&&(e.text="Documentation index installed.")}async function nN(n,e){try{return await mv(n,e,"Installing documentation index\u2026"),await Fu(e),!0}catch(t){if(Ao(t))throw t}try{return await Xy(),yi(),await mv(n,e,"Retrying documentation index install\u2026"),await Fu(e),!0}catch(t){if(Ao(t))throw t;let r=t instanceof Error?t.message:String(t);return await hv(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function rN(n,e,t){let r=kn();if(!r)throw new Error("docs.zip not found");let i=nn();await Fe.promises.mkdir(re(),{recursive:!0}),await Fe.promises.rm(i,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await xn({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"}),await uv({docsZipPath:r,tmpDir:i,docsZipSha256:e,termsHash:uc(),synonymsHash:dc(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await xn({state:"indexing",current:o.current,total:o.total,message:o.message})}}),await xn({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await tN(),yi()}async function Fu(n){await xn({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function iN(n){let e=await gu(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await xn({state:"done",message:t,error:null})}async function oN(n,e){let t=n instanceof Error?n.message:String(n);throw await xn({state:"error",error:t}),await hv(`ERROR: ${t}`),e?.fail(t),n}async function sN(){let n=re();await Fe.promises.mkdir(n,{recursive:!0});let e=ic();return Fe.existsSync(e)||await Fe.promises.writeFile(e,"","utf-8"),e}async function aN(){let n=await sN();return Qx.lock(n,{stale:1800*1e3})}async function cN(){let n=kn(),e=(n?await lc(n):null)??await fu();if(!e)throw new Error("docs.zip not found");return e}async function lN(n,e){let t=await cN(),r=n.force||await hu(n.force),i=await mc(n.force);if(!r&&!i&&ko()){await iN(e);return}!n.force&&Jy(t)&&await nN(t,e)||(await rN(n,t,e),await Fu(e))}var Uo=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:gv({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await pi({mode:"write"}),o=await aN(),await mu(nw("Starting documentation setup\u2026")),await lN(e,i)}catch(s){throw o&&await oN(s,i),s}finally{o&&await o()}}};async function dN(n){for(;;){let e=await pc();if(e.state==="done"&&ko())return;if(e.state==="error")throw new _u("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 eN(500)}}async function fv(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Uo.run({builtBy:"doc-init",force:e,quiet:!0})}async function uN(){let n=await mc()!==null;if(ko()&&!n)return;let e=gv({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await rw()){await dN(e),e.succeed("Documentation ready.");return}if(await hu()){await fv(e),e.succeed("Documentation ready.");return}await fv(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function Bo(){await pi({mode:"read"}),await uN(),await pv()}function pN(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 ju=class{async search(e,t,r=20){await Bo();try{return await Ou(e,t,r)}catch(i){if(!pN(i))throw i;return yi(),await Uo.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Ou(e,t,r)}}async readDocument(e){return await Bo(),zy(e)}},$u=new ju;function wv(...n){return e=>{if(!n.includes(e))throw new Hu(`Allowed values: ${n.join(", ")}`);return e}}function hN(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Hu("Must be a positive integer.");return e}var yN=wv("json","default"),wN=wv("json","default");function vN(n){let e=n instanceof Error?n.message:String(n);return Ao(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}async function Uu(n,e){let t=Date.now();try{let r=await e();return await yv(n,Date.now()-t,!0,null),r}catch(r){let i=r instanceof Error?r.code??r.name:"UnknownError";throw await yv(n,Date.now()-t,!1,i),r}}async function yv(n,e,t,r){await I.track(n,{duration_ms:e,success:t,error_code:r}).catch(()=>{})}function Bu(n){console.error(fN(vN(n))),process.exitCode=1}var Rc=new mN("docs").description("Search and read HarmonyOS documentation from local docs directory");Rc.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",bN,"all").option("--format <fmt>","Output format (default, json)",yN,"default").option("--limit <n>","Max number of results",hN,20).action(async(n,e)=>{let t={event:D.DocOperation,subAction:"search",keywords:n,queryLen:n.join(" ").length,catalog:e.catalog??"all"};try{await Uu(t,async()=>{let r=SN(n),i=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await $u.search(r,i,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):EN(o)})}catch(r){Bu(r)}});Rc.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{let e=n.trim(),t={event:D.DocOperation,subAction:"read",documentId:e};try{await Uu(t,async()=>{if(!e)throw new Error("Document ID cannot be empty.");let r=await $u.readDocument(e);console.log(r)})}catch(r){Bu(r)}});Rc.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",wN,"default").action(async n=>{let e={event:D.DocOperation,subAction:"catalog",fmt:n.format??"default"};try{await Uu(e,async()=>{if(await Bo(),n.format==="json"){let t=An.map(r=>({name:r,title:xt[r]}));console.log(JSON.stringify(t,null,2))}else for(let t of An)console.log(` ${t.padEnd(20)} ${gN(xt[t])}`)})}catch(t){Bu(t)}});function SN(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>So)throw new Error(`Query exceeds ${So} characters.`);return e}function bN(n){if(n==="all")return"all";if(!An.includes(n))throw new Hu(`Invalid catalog "${n}". Allowed: all, ${An.join(", ")}`);return n}function EN(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 vv=Rc;import{Command as YL}from"commander";import{Command as VN,InvalidArgumentError as GN,Option as Qu}from"commander";import{readFileSync as CN,unlinkSync as IN}from"fs";import{tmpdir as DN}from"os";import{join as AN}from"path";var St=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=PN(t);return e?.all||(r=r.filter(i=>i.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`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 PN(n){let e=n.split(`
1393
+ `),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]),v=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:d,type:v})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function Sv(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Wo(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function bv(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 Ev(n){return n.originalText||void 0}function Si(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function Pv(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let w={...i,children:[]};if(a?t.push(w):o.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:g})}return t}function TN(n){let e=CN(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function RN(n){return n.attributes??{}}function Vo(n,e,t){let r=RN(n),i={id:r.id||void 0,type:r.type||void 0,text:Ev(r),bounds:bv(r.bounds),clickable:Wo(r.clickable)||void 0,longClickable:Wo(r.longClickable)||void 0,scrollable:Wo(r.scrollable)||void 0,checkable:Wo(r.checkable)||void 0,hitTestBehavior:Sv(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>Vo(o,e,t+1))),i}function kN(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${i||"none"}`)}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 gr=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await se(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=AN(DN(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),TN(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await se(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),IN(t)}catch(o){m(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`),await se(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new St(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=kN(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>Vo(s,t,0))}async dumpFullTreeForWindow(e,t,r){let i=await this.fetchRawDump(e,String(r.id),r.displayId);return[Vo(i,t,0)]}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:Vo(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>Pv(Vo(s,0,0),t))}};var Cv=/^-+ (Screen|Display) ID: (\d+) -+$/,Dv=/\[DISPLAY INFO\][\s\S]*?\bWidth:\s*(\d+)[\s\S]*?\bHeight:\s*(\d+)/,Iv="Client Screen Infos";function xN(n){let e=n.split(`
1394
+ `),t=[];for(let r=0;r<e.length;r++){let i=Cv.exec(e[r].trim());if(!i)continue;let o=[];for(let s=r+1;s<e.length&&!Cv.test(e[s].trim());s++)o.push(e[s]);t.push({kind:i[1].toLowerCase(),id:Number(i[2]),body:o.join(`
1395
+ `)})}return t}function hr(n,e){let t=n.match(e);return t?Number(t[1]):void 0}function NN(n,e){let t=[...n.matchAll(e)];return t.length?Number(t[t.length-1][1]):void 0}function LN(n){let e=new Map;for(let t of n){if(t.kind!=="screen")continue;let r=hr(t.body,/\bDisplayId:\s*(\d+)/);r===void 0||e.has(r)||e.set(r,{screenId:t.id,refreshRate:hr(t.body,/\bRefreshRate:\s*([\d.]+)/),vpr:hr(t.body,/\bVirtualPixelRatio:\s*([\d.]+)/),rotation:NN(t.body,/\bRotation:\s*(\d+)/g)})}return e}function ON(n){let e=new Map,t=new Map;for(let r of n){if(!r.body.includes(Iv))continue;let i=r.kind==="display"?new Map:null;i&&t.set(r.id,i);let o=null;for(let s of r.body.split(`
1396
+ `)){if(s.includes(Iv)){o=null;continue}let a=hr(s,/^ScreenId:\s*(\d+)/);if(a!==void 0){o={screenId:a},e.set(a,o),i?.set(a,o);continue}if(!o)continue;let c=hr(s,/^\s*Rotation:\s*(\d+)/);if(c!==void 0){o.rotation=c;continue}let l=hr(s,/^\s*RefreshRate:\s*([\d.]+)/);if(l!==void 0){o.refreshRate=l;continue}let d=hr(s,/^\s*VirtualPixelRatio:\s*([\d.]+)/);d!==void 0&&(o.vpr=d)}}return{byScreenId:e,inDisplaySection:t}}function MN(n,e){return{screenId:e.screenId??n.screenId,refreshRate:e.refreshRate??n.refreshRate,vpr:e.vpr??n.vpr,rotation:e.rotation??n.rotation}}function _N(n,e,t){let r=e.get(n),i=t.inDisplaySection.get(n),o;return r?.screenId!==void 0?o=i?.get(r.screenId)??t.byScreenId.get(r.screenId):i?.size===1?o=[...i.values()][0]:t.byScreenId.size===1&&(o=[...t.byScreenId.values()][0]),MN(r??{},o??{})}function FN(n,e){let t=Dv.exec(n.body);return t?{id:n.id,width:Number(t[1]),height:Number(t[2]),...e}:null}function Av(n){let e=n.replace(/\r\n/g,`
1397
+ `),t=xN(e),r=LN(t),i=ON(t),o=[];for(let a of t){if(a.kind!=="display")continue;let c=_N(a.id,r,i),l=FN(a,c);l&&o.push(l)}if(o.length>0)return o;let s=Dv.exec(e);return s?[{id:0,width:Number(s[1]),height:Number(s[2])}]:[]}function jN(n){return(n.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)??"").slice(0,120)}var yr=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listDisplays(){let e=await this.fetchDump(),t=Av(e);if(t.length===0)throw new Error(`No display info in DisplayManagerService output: ${jN(e)}`);return t}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","DisplayManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await se(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query displays: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};var kc={left:"0",right:"1",up:"2",down:"3"};function an(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Wu(n,e){n!==void 0&&an(n,e)}function Tv(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function xc(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Go(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 Rv(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function kv(n,e,t,r=!0){if(t&&!e&&!n&&r)throw new Error("--window must be used with --id or coordinates");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 Nt(n,e,t,r,i=!0){Tv(n,e),xc(t,"--id"),Wu(n,"x"),Wu(e,"y"),Rv(r),kv(n!==void 0,!!t,!!r,i)}async function Lt(n,e){let r=await new Vr(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Mt(n){let e=await A.new(),t=await Lt(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function cn(n,e,t,r,i,o){if(t!==void 0&&r!==void 0){if(o===void 0)return{x:t,y:r,displayId:0};let d=await new St(n,e).listWindows({all:!0}),g=Zu(d,o);return{x:t,y:r,displayId:g.displayId}}if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new St(n,e).listWindows({all:!0}),c=new gr(n);return UN(c,e,a,i,o)}async function Nc(n,e,t){if(t===void 0)return 0;let i=await new St(n,e).listWindows({all:!0});return Zu(i,t).displayId}async function Vu(n,e,t){let r=await Nc(n,e,t);if(r===0)return;let s=(await new yr(n,e).listDisplays()).find(a=>a.id===r);if(!s)throw new Error(`Display "${r}" not found.`);return s}var Gu="600",$N=50,HN=200;function zu(n,e){return e!==0&&n.push(String(e)),n}function zo(n,e){return zu(["uitest","uiInput",n,String(e.x),String(e.y)],e.displayId)}function qu(n,e){return zu(["uitest","uiInput","inputText",String(n.x),String(n.y),e],n.displayId)}function Yu(n,e){return zu(["uitest","uiInput","text",n],e)}function Lc(n,e,t,r){let i=["uitest","uiInput",n,...e];return r.displayId===0?(t&&i.push(t),i):(i.push(t??Gu,String(r.displayId)),i)}function Ju(n,e,t){let r=["uitest","uiInput","fling",...n];if(t.displayId===0)return e&&r.push(e),r;let[i,o,s,a]=n.map(Number),c=Math.max(1,Math.floor(Math.hypot(s-i,a-o)/$N));return r.push(e??Gu,String(c),String(t.displayId)),r}function Ku(n,e){let t=["uitest","uiInput","dircFling",n];if(!e)return t;let i=n==="0"||n==="1"?e.width:e.height,o=Math.max(1,Math.floor(i/HN));return t.push(Gu,String(o),String(e.id)),t}function Xu(n){return zo("click",n)}function Zu(n,e){let t=n.find(r=>String(r.id)===e);if(!t){let r=n.map(i=>`${i.id} (${i.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${r||"none"}`)}return t}async function UN(n,e,t,r,i){if(i!==void 0){let o=Zu(t,i),s=await n.dumpFullTreeForWindow(e,0,o);return{...WN(s,r),displayId:o.displayId}}return BN(n,e,t,r)}async function BN(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of Si([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new Error(`Node "${r}" not found.`);if(s.length>1)throw new Error(`Multiple nodes found with id "${r}".`);return{...xv(s[0].node,r),displayId:s[0].displayId}}function WN(n,e){let t=Si(n,e);if(t.length===0)throw new Error(`Node "${e}" not found.`);if(t.length>1)throw new Error(`Multiple nodes found with id "${e}".`);return xv(t[0],e)}function xv(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function _t(n,e,t){let r=["-t",e,"shell",t.join(" ")];m(`Executing: ${n} ${r.join(" ")}`);let i=await se(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import zN from"ora";function qN(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new GN("depth must be a non-negative integer");return e}function YN(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 Nv(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${YN(i)}`),i.children.length>0&&t.push(...Nv(i.children,e+1).split(`
1398
1398
  `));return t.join(`
1399
- `)}function AN(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function TN(n,e){let t=hi(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));return JSON.stringify(r,null,2)}function RN(n,e){return e.id?TN(n,e.id):e.format==="json"?JSON.stringify(n,null,2):mv(n)}async function kN(n){AN(n);let e=CN({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await A.new(),o=await Nt(i,n.device),s=new ur(i.hdcPath);t=n.mode==="full"?await s.dumpFullTree(o,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(o,n.depth,n.window,n.allWindows)}catch(i){throw e.stop(),new Error(`Failed to dump layout: ${i.message}`,{cause:i})}e.stop();let r=RN(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function xN(n){return{event:D.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function NN(n){let e=xN(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await kN(n)}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var fv=new EN("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 _u("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(IN).default(0)).addOption(new _u("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new _u("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await NN(n)});import{Command as LN,Option as ON}from"commander";import{yellow as MN}from"colorette";import _N from"ora";var FN=["Id","Name","Pid","DisplayId","Focused"];function jN(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(ht(FN,t))}async function $N(n){let e=_N({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await Nt(r,n.device);t=await new rn(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(MN(" No windows found."));return}jN(t,n.format)}function HN(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:D.CommandExecuted,args:["ui","window","list",...e]}}async function UN(n){let e=HN(n),t=Date.now(),r=!0,i=null;try{await $N(n)}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var Fu=new LN("window").description("Manage device windows");Fu.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new ON("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await UN(n)});import{Command as BN,Option as WN}from"commander";import VN from"ora";var GN=["Id","Width","Height"],zN=["Id","Width","Height","ScreenId","RefreshRate","Vpr","Rotation"];function Ac(n){return n===void 0?"-":String(n)}function qN(n,e){if(e.format==="json"){let i=n.map(o=>e.all?{id:o.id,width:o.width,height:o.height,screenId:o.screenId??null,refreshRate:o.refreshRate??null,vpr:o.vpr??null,rotation:o.rotation??null}:{id:o.id,width:o.width,height:o.height});console.log(JSON.stringify(i,null,2));return}let t=e.all?zN:GN,r=n.map(i=>({cells:[String(i.id),String(i.width),String(i.height),...e.all?[Ac(i.screenId),Ac(i.refreshRate),Ac(i.vpr),Ac(i.rotation)]:[]]}));console.log(ht(t,r))}async function YN(n){let e=VN({text:"Listing displays\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await Nt(r,n.device);t=await new Uo(r.hdcPath,i).listDisplays()}catch(r){throw e.stop(),r instanceof T?new T(`Failed to list displays: ${r.message}`,r.traceMessage,{cause:r}):new Error(`Failed to list displays: ${r.message}`,{cause:r})}e.stop(),qN(t,n)}function JN(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:D.CommandExecuted,args:["ui","display","list",...e]}}async function KN(n){let e=JN(n),t=Date.now(),r=!0,i=null;try{await YN(n)}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var ju=new BN("display").description("Manage device displays");ju.command("list").description("List displays on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new WN("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show extended details (screen id, refresh rate, VPR, rotation)").action(async n=>{await KN(n)});import{Command as XN}from"commander";import $e from"fs";import st from"path";import{randomUUID as ZN}from"crypto";import{green as QN}from"colorette";function eL(n){return{event:D.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function tL(){return String(Date.now())}function hv(n){let e;try{e=$e.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{$e.accessSync(n,$e.constants.W_OK|$e.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function gv(n,e){try{throw $e.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 nL(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=st.resolve(e);try{if($e.statSync(t).isDirectory()){hv(t);let i=st.join(t,`screenshot-${tL()}.png`);return gv(i,t),i}}catch(i){if(i.code!=="ENOENT")throw i}if(st.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=st.dirname(t);return hv(r),gv(t,r),t}function yv(n){if(!$e.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=$e.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=$e.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 rL(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 iL(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function oL(n,e){try{$e.copyFileSync(n,e,$e.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}yv(e)}function sL(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 aL(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await se(n.hdcPath,e);return t.exitCode===0?sL(t.stdout):void 0}function cL(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1400
- `).trim()}function lL(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 dL(n,e){let t=rL(n,e);m(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await se(n.hdcPath,t),i=await aL(n);return{created:i!==void 0&&i>0,output:cL(r)}}async function uL(n){let e="";for(let t of[void 0,"png"]){let r=await dL(n,t);if(r.created)return;if(n.display!==void 0&&lL(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
1399
+ `)}function JN(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function KN(n,e){let t=Si(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));return JSON.stringify(r,null,2)}function XN(n,e){return e.id?KN(n,e.id):e.format==="json"?JSON.stringify(n,null,2):Nv(n)}async function ZN(n){JN(n);let e=zN({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let i=await A.new(),o=await Lt(i,n.device),s=new gr(i.hdcPath);t=n.mode==="full"?await s.dumpFullTree(o,n.depth,n.window,n.allWindows):await s.dumpCollapsedTree(o,n.depth,n.window,n.allWindows)}catch(i){throw e.stop(),new Error(`Failed to dump layout: ${i.message}`,{cause:i})}e.stop();let r=XN(t,n);return console.log(r),Buffer.byteLength(r,"utf8")}function QN(n){return{event:D.CommandExecuted,args:["ui","layout",...n.device?["--device"]:[]],mode:n.mode,outputSize:0}}async function eL(n){let e=QN(n),t=Date.now(),r=!0,i=null;try{e.outputSize=await ZN(n)}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var Lv=new VN("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 Qu("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(qN).default(0)).addOption(new Qu("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new Qu("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await eL(n)});import{Command as tL,Option as nL}from"commander";import{yellow as rL}from"colorette";import iL from"ora";var oL=["Id","Name","Pid","DisplayId","Focused"];function sL(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(mt(oL,t))}async function aL(n){let e=iL({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await Lt(r,n.device);t=await new St(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(rL(" No windows found."));return}sL(t,n.format)}function cL(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:D.CommandExecuted,args:["ui","window","list",...e]}}async function lL(n){let e=cL(n),t=Date.now(),r=!0,i=null;try{await aL(n)}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var ep=new tL("window").description("Manage device windows");ep.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new nL("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await lL(n)});import{Command as dL,Option as uL}from"commander";import pL from"ora";var mL=["Id","Width","Height"],fL=["Id","Width","Height","ScreenId","RefreshRate","Vpr","Rotation"];function Oc(n){return n===void 0?"-":String(n)}function gL(n,e){if(e.format==="json"){let i=n.map(o=>e.all?{id:o.id,width:o.width,height:o.height,screenId:o.screenId??null,refreshRate:o.refreshRate??null,vpr:o.vpr??null,rotation:o.rotation??null}:{id:o.id,width:o.width,height:o.height});console.log(JSON.stringify(i,null,2));return}let t=e.all?fL:mL,r=n.map(i=>({cells:[String(i.id),String(i.width),String(i.height),...e.all?[Oc(i.screenId),Oc(i.refreshRate),Oc(i.vpr),Oc(i.rotation)]:[]]}));console.log(mt(t,r))}async function hL(n){let e=pL({text:"Listing displays\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await Lt(r,n.device);t=await new yr(r.hdcPath,i).listDisplays()}catch(r){throw e.stop(),r instanceof T?new T(`Failed to list displays: ${r.message}`,r.traceMessage,{cause:r}):new Error(`Failed to list displays: ${r.message}`,{cause:r})}e.stop(),gL(t,n)}function yL(n){let e=[];return n.device&&e.push("--device"),n.format!=="default"&&e.push("--format"),n.all&&e.push("--all"),{event:D.CommandExecuted,args:["ui","display","list",...e]}}async function wL(n){let e=yL(n),t=Date.now(),r=!0,i=null;try{await hL(n)}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var tp=new dL("display").description("Manage device displays");tp.command("list").description("List displays on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new uL("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show extended details (screen id, refresh rate, VPR, rotation)").action(async n=>{await wL(n)});import{Command as vL}from"commander";import je from"fs";import it from"path";import{randomUUID as SL}from"crypto";import{green as bL}from"colorette";function EL(n){return{event:D.CommandExecuted,args:["ui","screenshot",...n.device?["--device"]:[]]}}function PL(){return String(Date.now())}function Ov(n){let e;try{e=je.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{je.accessSync(n,je.constants.W_OK|je.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Mv(n,e){try{throw je.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 CL(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=it.resolve(e);try{if(je.statSync(t).isDirectory()){Ov(t);let i=it.join(t,`screenshot-${PL()}.png`);return Mv(i,t),i}}catch(i){if(i.code!=="ENOENT")throw i}if(it.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=it.dirname(t);return Ov(r),Mv(t,r),t}function _v(n){if(!je.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=je.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=je.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 IL(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 DL(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function AL(n,e){try{je.copyFileSync(n,e,je.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}_v(e)}function TL(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 RL(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await se(n.hdcPath,e);return t.exitCode===0?TL(t.stdout):void 0}function kL(n){return[n.stdout,n.stderr].filter(Boolean).join(`
1400
+ `).trim()}function xL(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 NL(n,e){let t=IL(n,e);m(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await se(n.hdcPath,t),i=await RL(n);return{created:i!==void 0&&i>0,output:kL(r)}}async function LL(n){let e="";for(let t of[void 0,"png"]){let r=await NL(n,t);if(r.created)return;if(n.display!==void 0&&xL(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
1401
1401
  snapshot_display output:
1402
1402
  ${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
1403
1403
  snapshot_display output:
1404
- ${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function wv(n){try{return yv(n),!0}catch{return!1}}function vv(n){let e=[];for(let t of $e.readdirSync(n,{withFileTypes:!0})){let r=st.join(n,t.name);if(t.isDirectory()){e.push(...vv(r));continue}t.isFile()&&wv(r)&&e.push(r)}return e}function pL(n,e){let t=st.join(n,st.basename(e));if(wv(t))return t;let r=vv(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function $u(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let i=await se(n.hdcPath,r);return i.exitCode!==0&&m(`hdc file recv failed: ${i.stderr||i.stdout||`exit code ${i.exitCode}`}`),pL(e,n.remotePath)}async function mL(n){let e=$e.mkdtempSync(st.join(st.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await $u(n,e,st.join(e,st.basename(n.remotePath)))??await $u(n,e,e)??await $u(n,e,st.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);oL(t,n.localPath)}finally{$e.rmSync(e,{recursive:!0,force:!0})}}async function fL(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await se(n.hdcPath,e)}async function hL(n){try{await uL(n),await mL(n)}finally{await fL(n)}}async function gL(n){let e=eL(n),t=Date.now(),r=!0,i=null;try{let o=nL(n.path),s=n.display!==void 0?iL(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let a=await A.new(),c=await Nt(a,n.device),l=`/data/local/tmp/devecocli-${ZN()}.png`;await hL({hdcPath:a.hdcPath,serial:c,localPath:o,remotePath:l,display:s}),console.log(QN(`Screenshot saved to ${o}`))}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var Sv=new XN("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(gL);import{Command as xn}from"commander";function Nn(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:D.CommandExecuted,args:["ui",n,...t]}}function yL(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function Ln(n,e,t,r){let i=new yt;i.start(n);let o=Date.now(),s=!0,a=null;try{await r(i)}catch(c){throw i.stop(),s=!1,a=W(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await I.track(t,c)}}async function wL(n,e,t){let r=Nn("click",t);await Ln("Executing click...","click failed",r,async i=>{gi(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Lt(t.device),{x:a,y:c}=await yi(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(o,s,["uitest","uiInput","click",String(a),String(c)]),i.succeed(`click at (${a}, ${c})`)})}async function vL(n,e,t){let r=Nn("doubleclick",t);await Ln("Executing doubleclick...","doubleclick failed",r,async i=>{gi(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Lt(t.device),{x:a,y:c}=await yi(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(o,s,["uitest","uiInput","doubleClick",String(a),String(c)]),i.succeed(`doubleclick at (${a}, ${c})`)})}async function SL(n,e,t){let r=Nn("longclick",t);await Ln("Executing longclick...","longclick failed",r,async i=>{gi(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Lt(t.device),{x:a,y:c}=await yi(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await ot(o,s,["uitest","uiInput","longClick",String(a),String(c)]),i.succeed(`longclick at (${a}, ${c})`)})}async function bL(n,e,t,r,i){let o=Nn("swipe",i);await Ln("Executing swipe...","swipe failed",o,async s=>{ke(n,"x1"),ke(e,"y1"),ke(t,"x2"),ke(r,"y2");let a=Bo(i.speed),{hdcPath:c,deviceId:l}=await Lt(i.device),d=["uitest","uiInput","swipe",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function EL(n,e,t,r,i){let o=Nn("fling",i);await Ln("Executing fling...","fling failed",o,async s=>{ke(n,"x1"),ke(e,"y1"),ke(t,"x2"),ke(r,"y2");let a=Bo(i.speed),{hdcPath:c,deviceId:l}=await Lt(i.device),d=["uitest","uiInput","fling",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function PL(n,e,t,r,i){let o=Nn("drag",i);await Ln("Executing drag...","drag failed",o,async s=>{ke(n,"x1"),ke(e,"y1"),ke(t,"x2"),ke(r,"y2");let a=Bo(i.speed),{hdcPath:c,deviceId:l}=await Lt(i.device),d=["uitest","uiInput","drag",n,e,t,r];a&&d.push(a),await ot(c,l,d),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function CL(n,e){let t=Nn("dircfling",e);await Ln("Executing dircfling...","dircfling failed",t,async r=>{let i=Ic[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Ic).join(", ")}`);let{hdcPath:o,deviceId:s}=await Lt(e.device);await ot(o,s,["uitest","uiInput","dircFling",i]),r.succeed(`dircfling ${n}`)})}async function IL(n,e,t,r){let i=Nn("text",r);await Ln("Executing text input...","input failed",i,async o=>{gi(e,t,r.id,r.window,!1),Dc(n,"text");let{hdcPath:s,deviceId:a}=await Lt(r.device),c=yL(n);if(e!==void 0)await ot(s,a,["uitest","uiInput","inputText",`${e}`,`${t}`,c]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:l,y:d}=await yi(s,a,void 0,void 0,r.id,r.window);await ot(s,a,["uitest","uiInput","inputText",`${l}`,`${d}`,c]),o.succeed(`input ${n} at (${l}, ${d})`)}else await ot(s,a,["uitest","uiInput","text",c]),o.succeed(`input ${n}`)})}var bv=new xn("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(wL),Ev=new xn("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(vL),Pv=new xn("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(SL),Cv=new xn("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(bL),Iv=new xn("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(EL),Dv=new xn("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(PL),Av=new xn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(CL),Tv=new xn("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(IL);var Je=new DL("ui").description("Inspect and interact with UI on a connected device");Je.addCommand(fv);Je.addCommand(Fu);Je.addCommand(ju);Je.addCommand(Sv);Je.addCommand(bv);Je.addCommand(Ev);Je.addCommand(Pv);Je.addCommand(Cv);Je.addCommand(Iv);Je.addCommand(Dv);Je.addCommand(Av);Je.addCommand(Tv);var Rv=Je;import{Command as uM}from"commander";import{execa as YL}from"execa";import on from"fs";import*as Wu from"os";import*as q from"path";var AL=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),TL=/\r/g,RL=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,kL=/^<+\s*/,xL=/\s*>+$/,NL=[/^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\.$/];function Hu(n){if(!n)return"";let e=n.replace(AL,"").replace(TL,`
1404
+ ${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function Fv(n){try{return _v(n),!0}catch{return!1}}function jv(n){let e=[];for(let t of je.readdirSync(n,{withFileTypes:!0})){let r=it.join(n,t.name);if(t.isDirectory()){e.push(...jv(r));continue}t.isFile()&&Fv(r)&&e.push(r)}return e}function OL(n,e){let t=it.join(n,it.basename(e));if(Fv(t))return t;let r=jv(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function np(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let i=await se(n.hdcPath,r);return i.exitCode!==0&&m(`hdc file recv failed: ${i.stderr||i.stdout||`exit code ${i.exitCode}`}`),OL(e,n.remotePath)}async function ML(n){let e=je.mkdtempSync(it.join(it.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await np(n,e,it.join(e,it.basename(n.remotePath)))??await np(n,e,e)??await np(n,e,it.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);AL(t,n.localPath)}finally{je.rmSync(e,{recursive:!0,force:!0})}}async function _L(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await se(n.hdcPath,e)}async function FL(n){try{await LL(n),await ML(n)}finally{await _L(n)}}async function jL(n){let e=EL(n),t=Date.now(),r=!0,i=null;try{let o=CL(n.path),s=n.display!==void 0?DL(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let a=await A.new(),c=await Lt(a,n.device),l=`/data/local/tmp/devecocli-${SL()}.png`;await FL({hdcPath:a.hdcPath,serial:c,localPath:o,remotePath:l,display:s}),console.log(bL(`Screenshot saved to ${o}`))}catch(o){throw r=!1,i=W(o),o}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}}var $v=new vL("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(jL);import{Command as Mn}from"commander";function _n(n){return n!==0?` on display ${n}`:""}function Fn(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:D.CommandExecuted,args:["ui",n,...t]}}function $L(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function jn(n,e,t,r){let i=new gt;i.start(n);let o=Date.now(),s=!0,a=null;try{await r(i)}catch(c){throw i.stop(),s=!1,a=W(c),new Error(`${e}: ${c.message}`,{cause:c})}finally{let c={duration_ms:Date.now()-o,success:s,error_code:a};await I.track(t,c)}}async function HL(n,e,t){let r=Fn("click",t);await jn("Executing click...","click failed",r,async i=>{Nt(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Mt(t.device),a=await cn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await _t(o,s,Xu(a)),i.succeed(`click at (${a.x}, ${a.y})${_n(a.displayId)}`)})}async function UL(n,e,t){let r=Fn("doubleclick",t);await jn("Executing doubleclick...","doubleclick failed",r,async i=>{Nt(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Mt(t.device),a=await cn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await _t(o,s,zo("doubleClick",a)),i.succeed(`doubleclick at (${a.x}, ${a.y})${_n(a.displayId)}`)})}async function BL(n,e,t){let r=Fn("longclick",t);await jn("Executing longclick...","longclick failed",r,async i=>{Nt(n,e,t.id,t.window);let{hdcPath:o,deviceId:s}=await Mt(t.device),a=await cn(o,s,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await _t(o,s,zo("longClick",a)),i.succeed(`longclick at (${a.x}, ${a.y})${_n(a.displayId)}`)})}async function WL(n,e,t,r,i){let o=Fn("swipe",i);await jn("Executing swipe...","swipe failed",o,async s=>{Nt(n,e,void 0,i.window),an(t,"x2"),an(r,"y2");let a=Go(i.speed),{hdcPath:c,deviceId:l}=await Mt(i.device),d=await cn(c,l,Number(n),Number(e),void 0,i.window),g=Lc("swipe",[n,e,t,r],a,d);await _t(c,l,g),s.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})${_n(d.displayId)}`)})}async function VL(n,e,t,r,i){let o=Fn("fling",i);await jn("Executing fling...","fling failed",o,async s=>{Nt(n,e,void 0,i.window),an(t,"x2"),an(r,"y2");let a=Go(i.speed),{hdcPath:c,deviceId:l}=await Mt(i.device),d=await cn(c,l,Number(n),Number(e),void 0,i.window),g=Ju([n,e,t,r],a,d);await _t(c,l,g),s.succeed(`fling from (${n}, ${e}) to (${t}, ${r})${_n(d.displayId)}`)})}async function GL(n,e,t,r,i){let o=Fn("drag",i);await jn("Executing drag...","drag failed",o,async s=>{Nt(n,e,void 0,i.window),an(t,"x2"),an(r,"y2");let a=Go(i.speed),{hdcPath:c,deviceId:l}=await Mt(i.device),d=await cn(c,l,Number(n),Number(e),void 0,i.window),g=Lc("drag",[n,e,t,r],a,d);await _t(c,l,g),s.succeed(`drag from (${n}, ${e}) to (${t}, ${r})${_n(d.displayId)}`)})}async function zL(n,e){let t=Fn("dircfling",e);await jn("Executing dircfling...","dircfling failed",t,async r=>{let i=kc[n];if(i===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(kc).join(", ")}`);Nt(void 0,void 0,void 0,e.window,!1);let{hdcPath:o,deviceId:s}=await Mt(e.device),a=await Vu(o,s,e.window);await _t(o,s,Ku(i,a));let c=a?.id??0;r.succeed(`dircfling ${n}${_n(c)}`)})}async function qL(n,e,t,r){let i=Fn("text",r);await jn("Executing text input...","input failed",i,async o=>{Nt(e,t,r.id,r.window,!1),xc(n,"text");let{hdcPath:s,deviceId:a}=await Mt(r.device),c=$L(n),l=e!==void 0||r.id?await cn(s,a,e!==void 0?Number(e):void 0,t!==void 0?Number(t):void 0,r.id,r.window):void 0,d=l?.displayId??await Nc(s,a,r.window),g=l?qu(l,c):Yu(c,d);await _t(s,a,g);let w=l?` at (${l.x}, ${l.y})`:"";o.succeed(`input ${n}${w}${_n(d)}`)})}var Hv=new Mn("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 or coordinates)").action(HL),Uv=new Mn("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 or coordinates)").action(UL),Bv=new Mn("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 or coordinates)").action(BL),Wv=new Mn("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)").option("--window <windowId>","Target window id (resolves target display)").action(WL),Vv=new Mn("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)").option("--window <windowId>","Target window id (resolves target display)").action(VL),Gv=new Mn("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)").option("--window <windowId>","Target window id (resolves target display)").action(GL),zv=new Mn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").option("--window <windowId>","Target window id (resolves target display)").action(zL),qv=new Mn("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, coordinates, or focused input)").action(qL);var Ye=new YL("ui").description("Inspect and interact with UI on a connected device");Ye.addCommand(Lv);Ye.addCommand(ep);Ye.addCommand(tp);Ye.addCommand($v);Ye.addCommand(Hv);Ye.addCommand(Uv);Ye.addCommand(Bv);Ye.addCommand(Wv);Ye.addCommand(Vv);Ye.addCommand(Gv);Ye.addCommand(zv);Ye.addCommand(qv);var Yv=Ye;import{Command as LM}from"commander";import{execa as hO}from"execa";import ln from"fs";import*as sp from"os";import*as q from"path";var JL=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),KL=/\r/g,XL=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,ZL=/^<+\s*/,QL=/\s*>+$/,eO=[/^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\.$/];function rp(n){if(!n)return"";let e=n.replace(JL,"").replace(KL,`
1405
1405
  `).split(`
1406
- `).map(t=>t.trimEnd()).filter(t=>OL(t));return e.length>0?`${e.join(`
1406
+ `).map(t=>t.trimEnd()).filter(t=>nO(t));return e.length>0?`${e.join(`
1407
1407
  `)}
1408
- `:""}function Lv(n){let e=Hu(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Ov(e))return{jsonText:e,diagnostics:""};let t=ML(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
1408
+ `:""}function Zv(n){let e=rp(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Qv(e))return{jsonText:e,diagnostics:""};let t=rO(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
1409
1409
  `};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
1410
1410
  `);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
1411
- `:""}}function LL(n){return RL.test(n.trim())}function OL(n){let e=n.trim();return!!e&&!LL(e)&&!NL.some(t=>t.test(e))}function Ov(n){try{return JSON.parse(n),!0}catch{return!1}}function ML(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=_L(n,e);if(t)return t}}function _L(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let i=n.slice(e,t);if(Ov(i))return{start:e,end:t}}}var kv=["Error","Warning","Suggestion","Info","Off","Unknown"];function Mv(n){let e=Uu(n);return{issues:HL(e),summary:FL(n,e)}}function FL(n,e){let t=BL(e);return{filesChecked:WL(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function Uu(n,e=""){if(Array.isArray(n))return n.flatMap(o=>Uu(o,e));if(!_v(n))return[];let t=Wo(n,["filePath","file","path"])??e,r=jL(n,t);if(r.length>0)return r;let i=$L(n,t);return i?[i]:[]}function jL(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let i=n[r];if(Array.isArray(i)){let o=i.flatMap(s=>Uu(s,e));if(o.length>0)return o}}return[]}function $L(n,e){let t=Wo(n,["message","description","desc","detail"])??"",r=qL(Wo(n,["rule","ruleId","ruleName"])),i=GL(n,["severity","level"]),o=Wo(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:Nv(n,["line","reportLine"]),column:Nv(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function HL(n){return[...n].sort((e,t)=>{let r=xv(e.severity)-xv(t.severity);return r===0?UL(e,t):r})}function UL(n,e){let t=n.file.localeCompare(e.file);if(t!==0)return t;let r=(n.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return r!==0?r:(n.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function BL(n){let e=new Map;for(let t of n){let r=t.severity;e.set(r,(e.get(r)??0)+1)}return e}function WL(n){let e=new Set;return Bu(e,n,""),e}function Bu(n,e,t){if(Array.isArray(e)){for(let i of e)Bu(n,i,t);return}if(!_v(e))return;let r=Wo(e,["filePath","file","path"])??t;r&&n.add(r),VL(n,e,r)}function VL(n,e,t){let r=["messages","defects","issues","results","files"];for(let i of r){let o=e[i];if(Array.isArray(o))for(let s of o)Bu(n,s,t)}}function GL(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return zL(r)}return"Unknown"}function zL(n){let e=String(n).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 qL(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(kL,"").replace(xL,"").toLowerCase()}function xv(n){let e=kv.indexOf(n);return e===-1?kv.length:e}function Wo(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function Nv(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function _v(n){return typeof n=="object"&&n!==null}var Fv="deveco-codelinter-",jv=[".ets",".ts",".js"],Vo=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return K.discover(e).rootDir}catch{return e}}async check(e){let t=on.mkdtempSync(q.join(Wu.tmpdir(),Fv)),r=q.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r),c=await this.run(a),l=Lv(c.stdout),d=l.diagnostics+Hu(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:Mv(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?q.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=on.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=q.extname(i).toLowerCase();if(!jv.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${jv.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new Error(`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let r=e?q.resolve(this.cwd,e):q.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!on.statSync(i).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||q.relative(t.projectRoot,o)!=="")throw new Error(`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let r=t?e:q.dirname(e);try{return on.realpathSync(K.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return on.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,i){let o=["--config",r];return e.fix&&o.push("--fix"),e.incremental&&o.push("--incremental"),o.push("--product",e.product,"--format","json","--output",i,t),o}async run(e){let t=[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let i=await YL(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])try{on.mkdirSync(e,{recursive:!0})}catch(t){m(`[CodelinterAdapter] Skipping runtime directory ${e}: ${t.message}`)}}readJsonReport(e,t){let i=(on.existsSync(e)?on.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new Error("Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=q.resolve(e),r=q.resolve(Wu.tmpdir());!(t.startsWith(`${r}${q.sep}`)||t===r)||!q.basename(t).startsWith(Fv)||on.rmSync(t,{recursive:!0,force:!0})}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(q.delimiter),DEVECO_SDK_HOME:o}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(i)]),m(`[CodelinterAdapter] Selected ${a} entry: ${i}`),c}static getPathEntries(e,t){let r=[q.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(q.dirname(e.javaPath)),r}static getResultDirectory(e){return q.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as Rc,yellow as oO}from"colorette";import{Argument as sO,Command as aO,InvalidArgumentError as Mn}from"commander";import zo from"fs";import*as He from"path";import*as Go from"path";var $v="n/a",Hv=/\\/g,JL=/\|/g,KL=/\r?\n/g;function Uv(n,e){if(n.issues.length===0)return`No defects found.
1412
- ${Vu(n.summary)}
1413
- `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[ZL(t),Vu(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(XL(n.issues.length,t.length)),`${r.join(`
1411
+ `:""}}function tO(n){return XL.test(n.trim())}function nO(n){let e=n.trim();return!!e&&!tO(e)&&!eO.some(t=>t.test(e))}function Qv(n){try{return JSON.parse(n),!0}catch{return!1}}function rO(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=iO(n,e);if(t)return t}}function iO(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let i=n.slice(e,t);if(Qv(i))return{start:e,end:t}}}var Jv=["Error","Warning","Suggestion","Info","Off","Unknown"];function eS(n){let e=ip(n);return{issues:cO(e),summary:oO(n,e)}}function oO(n,e){let t=dO(e);return{filesChecked:uO(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function ip(n,e=""){if(Array.isArray(n))return n.flatMap(o=>ip(o,e));if(!tS(n))return[];let t=qo(n,["filePath","file","path"])??e,r=sO(n,t);if(r.length>0)return r;let i=aO(n,t);return i?[i]:[]}function sO(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let i=n[r];if(Array.isArray(i)){let o=i.flatMap(s=>ip(s,e));if(o.length>0)return o}}return[]}function aO(n,e){let t=qo(n,["message","description","desc","detail"])??"",r=gO(qo(n,["rule","ruleId","ruleName"])),i=mO(n,["severity","level"]),o=qo(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:Xv(n,["line","reportLine"]),column:Xv(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function cO(n){return[...n].sort((e,t)=>{let r=Kv(e.severity)-Kv(t.severity);return r===0?lO(e,t):r})}function lO(n,e){let t=n.file.localeCompare(e.file);if(t!==0)return t;let r=(n.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return r!==0?r:(n.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function dO(n){let e=new Map;for(let t of n){let r=t.severity;e.set(r,(e.get(r)??0)+1)}return e}function uO(n){let e=new Set;return op(e,n,""),e}function op(n,e,t){if(Array.isArray(e)){for(let i of e)op(n,i,t);return}if(!tS(e))return;let r=qo(e,["filePath","file","path"])??t;r&&n.add(r),pO(n,e,r)}function pO(n,e,t){let r=["messages","defects","issues","results","files"];for(let i of r){let o=e[i];if(Array.isArray(o))for(let s of o)op(n,s,t)}}function mO(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return fO(r)}return"Unknown"}function fO(n){let e=String(n).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 gO(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(ZL,"").replace(QL,"").toLowerCase()}function Kv(n){let e=Jv.indexOf(n);return e===-1?Jv.length:e}function qo(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function Xv(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function tS(n){return typeof n=="object"&&n!==null}var nS="deveco-codelinter-",rS=[".ets",".ts",".js"],Yo=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return K.discover(e).rootDir}catch{return e}}async check(e){let t=ln.mkdtempSync(q.join(sp.tmpdir(),nS)),r=q.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r),c=await this.run(a),l=Zv(c.stdout),d=l.diagnostics+rp(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:eS(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?q.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=ln.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=q.extname(i).toLowerCase();if(!rS.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${rS.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new Error(`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let r=e?q.resolve(this.cwd,e):q.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!ln.statSync(i).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||q.relative(t.projectRoot,o)!=="")throw new Error(`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let r=t?e:q.dirname(e);try{return ln.realpathSync(K.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return ln.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,i){let o=["--config",r];return e.fix&&o.push("--fix"),e.incremental&&o.push("--incremental"),o.push("--product",e.product,"--format","json","--output",i,t),o}async run(e){let t=[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let i=await hO(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])try{ln.mkdirSync(e,{recursive:!0})}catch(t){m(`[CodelinterAdapter] Skipping runtime directory ${e}: ${t.message}`)}}readJsonReport(e,t){let i=(ln.existsSync(e)?ln.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new Error("Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=q.resolve(e),r=q.resolve(sp.tmpdir());!(t.startsWith(`${r}${q.sep}`)||t===r)||!q.basename(t).startsWith(nS)||ln.rmSync(t,{recursive:!0,force:!0})}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(q.delimiter),DEVECO_SDK_HOME:o}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(i)]),m(`[CodelinterAdapter] Selected ${a} entry: ${i}`),c}static getPathEntries(e,t){let r=[q.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(q.dirname(e.javaPath)),r}static getResultDirectory(e){return q.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as _c,yellow as AO}from"colorette";import{Argument as TO,Command as RO,InvalidArgumentError as Hn}from"commander";import Ko from"fs";import*as $e from"path";import*as Jo from"path";var iS="n/a",oS=/\\/g,yO=/\|/g,wO=/\r?\n/g;function sS(n,e){if(n.issues.length===0)return`No defects found.
1412
+ ${ap(n.summary)}
1413
+ `;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[SO(t),ap(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(vO(n.issues.length,t.length)),`${r.join(`
1414
1414
  `)}
1415
- `}function Bv(n,e){return[Vu(n.summary),`Full report: ${Gu(e)}`,""].join(`
1416
- `)}function Wv(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...QL(n.issues),""),e.push("## Summary","",...tO(n.summary),""),e.join(`
1417
- `)}function Vv(n){return`${JSON.stringify(n,null,2)}
1418
- `}function Vu(n){return`Summary: Issues: ${at(n.issues)} | Errors: ${at(n.errors)} | Warnings: ${at(n.warnings)} | Suggestions: ${at(n.suggestions)} | Files checked: ${at(n.filesChecked)}`}function XL(n,e){return`Showing ${at(e)} of ${at(n)} issues. Use --output-path <path> to write all results.`}function ZL(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:rO(r,i+1)}));return["CodeLinter report","",ht(e,t)].join(`
1419
- `)}function QL(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(eO(r,t+1));return e}function eO(n,e){return`| ${[String(e),Gu(On(n.file)),Tc(n.line),Tc(n.column),On(n.severity),On(n.rule),On(n.message)].map(nO).join(" | ")} |`}function tO(n){return[`- Issues: ${at(n.issues)}`,`- Errors: ${at(n.errors)}`,`- Warnings: ${at(n.warnings)}`,`- Suggestions: ${at(n.suggestions)}`,`- Files checked: ${at(n.filesChecked)}`]}function nO(n){return n.replace(Hv,"\\\\").replace(JL,"\\|").replace(KL,"<br>")}function rO(n,e){return[String(e),Gu(On(iO(n.file))),Tc(n.line),Tc(n.column),On(n.severity),On(n.rule),On(n.message)]}function iO(n){if(!Go.isAbsolute(n))return n;let e=Go.relative(process.cwd(),n);return!e||e.startsWith("..")||Go.isAbsolute(e)?n:e}function Gu(n){return n.replace(Hv,"/")}function On(n){let e=n?.trim();return e||$v}function Tc(n){return n===void 0?$v:String(n)}function at(n){return n.toLocaleString("en-US")}var zu=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function cO(n){let e=n;return n instanceof zu?n.code:e.code??e.name??"UnknownError"}async function Gv(n,e,t,r){let i=await Ni(process.pid),o=i!==null?Dt(Number(i)*1024):"unknown",s={event:D.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var lO=/^-?\d+$/;function qu(){return new aO("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new sO("[path]","File or directory to lint").argParser(fO)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",uO).option("--product <product>","Product name defined in build-profile.json5",pO,"default").option("--format <format>","Report format (choices: default, json)",dO,"default").option("--output-path <path>","Complete report file or directory",mO).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",hO).action(async(n,e)=>{await gO(n,e)})}function dO(n){if(n==="default"||n==="json")return n;throw new Mn("Invalid --format. Expected one of: default, json.")}function uO(n){Yu(n,"--config-path");let e=He.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Mn("`--config-path` must point to a .json or .json5 file.");return n}function pO(n){return zv(n,"product"),n}function mO(n){return Yu(n,"--output-path"),n}function fO(n){return Yu(n,"path"),n}function hO(n){if(zv(n,"limit"),!lO.test(n))throw new Mn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Mn("`--limit` must be an integer greater than 0.");return e}function zv(n,e){if(n.trim().length===0||Jv(n))throw new Mn(`Invalid --${e} value.`)}function Yu(n,e){let t=`\`${e}\``;if(n.length===0||Jv(n))throw new Mn(`${t} must be a non-empty path without control characters.`)}async function gO(n,e){let t=Date.now(),r=["check","lint"];try{let i=process.cwd(),o=bO(e.outputPath,e.format,i);e.fix&&console.warn(oO("Running codelinter with --fix. Ensure your project source is trusted."));let s=await yO(n,e,i);DO(s.diagnostics),process.exitCode=vO(s,o,e.format,e.limit,i),await Gv(t,!0,null,r)}catch(i){let o=cO(i);throw await Gv(t,!1,o,r),i}}async function yO(n,e,t){let r=await A.new(),i=new Vo(r,t);return wO(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function wO(n,e){let t=new yt;process.stderr.isTTY&&t.start("Checking code...");try{let r=await n.check(e);return t.stop(),r}catch(r){throw t.fail("Code check failed"),r}}function vO(n,e,t,r,i){if(!n.report)return console.error(Rc("Failed to generate Code Linter report.")),console.error(Rc(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){SO(e,t,n.report);let o=Yv(e,i);process.stdout.write(Bv(n.report,o))}else process.stdout.write(Uv(n.report,r));return n.exitCode}catch(o){return console.error(Rc("Failed to generate Code Linter report.")),console.error(Rc(o.message)),n.exitCode===0?1:n.exitCode}}function SO(n,e,t){zo.mkdirSync(He.dirname(n),{recursive:!0});let r=e==="json"?Vv(t):Wv(t);try{zo.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:i}):i}}function bO(n,e,t){if(!n)return;let r=CO(n,t),i=PO(n,r),o=i?He.join(r,IO(e)):r;if(i||EO(n,e),zo.existsSync(o))throw new Mn(`Output file already exists: ${Yv(o,t)}`);return o}function EO(n,e){let t=qv(e);if(He.extname(n).toLowerCase()!==t)throw new Mn(`--output-path must use the ${t} extension for --format ${e}.`)}function PO(n,e){return zo.existsSync(e)?zo.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||He.extname(n)===""}function CO(n,e){return He.resolve(e,n)}function IO(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${i}${qv(n)}`}function qv(n){return n==="json"?".json":".md"}function Yv(n,e){let t=He.relative(e,n);return t&&!t.startsWith("..")&&!He.isAbsolute(t)?t:n}function DO(n){n&&process.stderr.write(n)}function Jv(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as AO,InvalidArgumentError as Qv}from"commander";import*as Y from"path";import*as Ju from"os";import{readdirSync as TO,existsSync as kc,readFileSync as RO,unlinkSync as kO,copyFileSync as eS,writeFileSync as tS}from"fs";import{execa as xO}from"execa";import{cyan as Se,yellow as nS}from"colorette";import NO from"ora";var Kv=["default","csv","json"];function rS(n){if(Kv.includes(n))return n;throw new Qv(`--format must be one of: ${Kv.join(", ")} (got "${n}")`)}function LO(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Qv(`--limit must be a positive integer (got "${n}")`);return e}function OO(n){return[...n].sort((e,t)=>{let r=Xv(e),i=Xv(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function Xv(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),i=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:i}}function iS(n){let t=TO(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return OO(t)}function MO(n){let e=process.argv;for(let t=0;t<e.length;t+=1){let r=e[t],i;if(r==="--format"&&t+1<e.length?i=e[t+1]:r.startsWith("--format=")&&(i=r.slice(9)),i!==void 0){let o=rS(i);return o==="default"?"csv":o}}return n}async function _O(n){let e=await A.new(),{apiChangeDir:t}=e.getApiscanPaths();m(Se(`[compat:versions] apiChangeDir: "${t}"`));let r=iS(t);if(n==="json")console.log(JSON.stringify({versions:r,count:r.length},null,2));else{if(r.length===0){console.log("No SDK versions available.");return}console.log(r.join(`
1420
- `))}}var Zv=new Set([".ets",".c",".cpp"]);function FO(n,e){let t=new Set(n.profile.modules.map(s=>s.name)),r=e.filter(s=>!t.has(s));if(r.length===0)return;let i=n.profile.modules.map(s=>s.name).join(", "),o=r.length>1?"are":"is";throw new Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function jO(n){for(let e of n){let t=Y.resolve(e);if(!kc(t))throw new Error(`File "${e}" does not exist.`);let r=Y.extname(t).toLowerCase();if(!Zv.has(r)){let i=Array.from(Zv).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function $O(n){let e=[],t=[];for(let r of n)Y.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function HO(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=UO(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
1421
- `?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function UO(n,e,t,r,i){return t!=='"'?{field:r+t,inQuotes:i,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:i,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function BO(n,e){return e.map(t=>{let r=i=>{let o=n.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:r("Api Definition"),language:r("Language"),changeId:r("ChangeId"),changedInSdk:r("Changed in SDK"),affectedVersions:r("Affected Versions"),title:r("Title"),codeLocation:r("Code Location"),changeType:r("Change Type")}})}function WO(n){let e=RO(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=HO(t);if(r.length<2)return[];let[i,...o]=r;return BO(i,o)}function VO(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return Y.isAbsolute(r)?r:Y.join(e,r)}function GO(n,e){let t=new Map;for(let o of n){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...r.map(([o])=>o.length));console.log(Se("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${n.length}`);for(let[o,s]of r)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function zO(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(Se(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}r>0&&console.log(nS(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function qO(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({count:n.length,records:t},null,2)),r>0&&console.log(nS(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function YO(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push(Y.resolve(n.rootDir,i.srcPath))}return t}function JO(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("source-version and target-version are required.");let i=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=$O(e),a=d=>Y.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=YO(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",Ju.tmpdir()),i}async function KO(n,e){let t=Y.dirname(e[0]);try{let i=(await xO(n.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(i),i.endsWith(`
1415
+ `}function aS(n,e){return[ap(n.summary),`Full report: ${cp(e)}`,""].join(`
1416
+ `)}function cS(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...bO(n.issues),""),e.push("## Summary","",...PO(n.summary),""),e.join(`
1417
+ `)}function lS(n){return`${JSON.stringify(n,null,2)}
1418
+ `}function ap(n){return`Summary: Issues: ${ot(n.issues)} | Errors: ${ot(n.errors)} | Warnings: ${ot(n.warnings)} | Suggestions: ${ot(n.suggestions)} | Files checked: ${ot(n.filesChecked)}`}function vO(n,e){return`Showing ${ot(e)} of ${ot(n)} issues. Use --output-path <path> to write all results.`}function SO(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:IO(r,i+1)}));return["CodeLinter report","",mt(e,t)].join(`
1419
+ `)}function bO(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(EO(r,t+1));return e}function EO(n,e){return`| ${[String(e),cp($n(n.file)),Mc(n.line),Mc(n.column),$n(n.severity),$n(n.rule),$n(n.message)].map(CO).join(" | ")} |`}function PO(n){return[`- Issues: ${ot(n.issues)}`,`- Errors: ${ot(n.errors)}`,`- Warnings: ${ot(n.warnings)}`,`- Suggestions: ${ot(n.suggestions)}`,`- Files checked: ${ot(n.filesChecked)}`]}function CO(n){return n.replace(oS,"\\\\").replace(yO,"\\|").replace(wO,"<br>")}function IO(n,e){return[String(e),cp($n(DO(n.file))),Mc(n.line),Mc(n.column),$n(n.severity),$n(n.rule),$n(n.message)]}function DO(n){if(!Jo.isAbsolute(n))return n;let e=Jo.relative(process.cwd(),n);return!e||e.startsWith("..")||Jo.isAbsolute(e)?n:e}function cp(n){return n.replace(oS,"/")}function $n(n){let e=n?.trim();return e||iS}function Mc(n){return n===void 0?iS:String(n)}function ot(n){return n.toLocaleString("en-US")}var lp=class extends Error{code;constructor(e,t){super(t),this.name="ValidationError",this.code=e}};function kO(n){let e=n;return n instanceof lp?n.code:e.code??e.name??"UnknownError"}async function dS(n,e,t,r){let i=await Mi(process.pid),o=i!==null?It(Number(i)*1024):"unknown",s={event:D.CheckCommand,args:r,mcpMemory:o,lspMemory:"unknown"},a={duration_ms:Date.now()-n,success:e,error_code:t};await I.track(s,a).catch(()=>{})}var xO=/^-?\d+$/;function dp(){return new RO("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new TO("[path]","File or directory to lint").argParser(_O)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",LO).option("--product <product>","Product name defined in build-profile.json5",OO,"default").option("--format <format>","Report format (choices: default, json)",NO,"default").option("--output-path <path>","Complete report file or directory",MO).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",FO).action(async(n,e)=>{await jO(n,e)})}function NO(n){if(n==="default"||n==="json")return n;throw new Hn("Invalid --format. Expected one of: default, json.")}function LO(n){up(n,"--config-path");let e=$e.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Hn("`--config-path` must point to a .json or .json5 file.");return n}function OO(n){return uS(n,"product"),n}function MO(n){return up(n,"--output-path"),n}function _O(n){return up(n,"path"),n}function FO(n){if(uS(n,"limit"),!xO.test(n))throw new Hn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Hn("`--limit` must be an integer greater than 0.");return e}function uS(n,e){if(n.trim().length===0||fS(n))throw new Hn(`Invalid --${e} value.`)}function up(n,e){let t=`\`${e}\``;if(n.length===0||fS(n))throw new Hn(`${t} must be a non-empty path without control characters.`)}async function jO(n,e){let t=Date.now(),r=["check","lint"];try{let i=process.cwd(),o=WO(e.outputPath,e.format,i);e.fix&&console.warn(AO("Running codelinter with --fix. Ensure your project source is trusted."));let s=await $O(n,e,i);YO(s.diagnostics),process.exitCode=UO(s,o,e.format,e.limit,i),await dS(t,!0,null,r)}catch(i){let o=kO(i);throw await dS(t,!1,o,r),i}}async function $O(n,e,t){let r=await A.new(),i=new Yo(r,t);return HO(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function HO(n,e){let t=new gt;process.stderr.isTTY&&t.start("Checking code...");try{let r=await n.check(e);return t.stop(),r}catch(r){throw t.fail("Code check failed"),r}}function UO(n,e,t,r,i){if(!n.report)return console.error(_c("Failed to generate Code Linter report.")),console.error(_c(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){BO(e,t,n.report);let o=mS(e,i);process.stdout.write(aS(n.report,o))}else process.stdout.write(sS(n.report,r));return n.exitCode}catch(o){return console.error(_c("Failed to generate Code Linter report.")),console.error(_c(o.message)),n.exitCode===0?1:n.exitCode}}function BO(n,e,t){Ko.mkdirSync($e.dirname(n),{recursive:!0});let r=e==="json"?lS(t):cS(t);try{Ko.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:i}):i}}function WO(n,e,t){if(!n)return;let r=zO(n,t),i=GO(n,r),o=i?$e.join(r,qO(e)):r;if(i||VO(n,e),Ko.existsSync(o))throw new Hn(`Output file already exists: ${mS(o,t)}`);return o}function VO(n,e){let t=pS(e);if($e.extname(n).toLowerCase()!==t)throw new Hn(`--output-path must use the ${t} extension for --format ${e}.`)}function GO(n,e){return Ko.existsSync(e)?Ko.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||$e.extname(n)===""}function zO(n,e){return $e.resolve(e,n)}function qO(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${i}${pS(n)}`}function pS(n){return n==="json"?".json":".md"}function mS(n,e){let t=$e.relative(e,n);return t&&!t.startsWith("..")&&!$e.isAbsolute(t)?t:n}function YO(n){n&&process.stderr.write(n)}function fS(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as JO,InvalidArgumentError as wS}from"commander";import*as Y from"path";import*as pp from"os";import{readdirSync as KO,existsSync as Fc,readFileSync as XO,unlinkSync as ZO,copyFileSync as vS,writeFileSync as SS}from"fs";import{execa as QO}from"execa";import{cyan as Se,yellow as bS}from"colorette";import eM from"ora";var gS=["default","csv","json"];function ES(n){if(gS.includes(n))return n;throw new wS(`--format must be one of: ${gS.join(", ")} (got "${n}")`)}function tM(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new wS(`--limit must be a positive integer (got "${n}")`);return e}function nM(n){return[...n].sort((e,t)=>{let r=hS(e),i=hS(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function hS(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),i=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:i}}function PS(n){let t=KO(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return nM(t)}function rM(n){let e=process.argv;for(let t=0;t<e.length;t+=1){let r=e[t],i;if(r==="--format"&&t+1<e.length?i=e[t+1]:r.startsWith("--format=")&&(i=r.slice(9)),i!==void 0){let o=ES(i);return o==="default"?"csv":o}}return n}async function iM(n){let e=await A.new(),{apiChangeDir:t}=e.getApiscanPaths();m(Se(`[compat:versions] apiChangeDir: "${t}"`));let r=PS(t);if(n==="json")console.log(JSON.stringify({versions:r,count:r.length},null,2));else{if(r.length===0){console.log("No SDK versions available.");return}console.log(r.join(`
1420
+ `))}}var yS=new Set([".ets",".c",".cpp"]);function oM(n,e){let t=new Set(n.profile.modules.map(s=>s.name)),r=e.filter(s=>!t.has(s));if(r.length===0)return;let i=n.profile.modules.map(s=>s.name).join(", "),o=r.length>1?"are":"is";throw new Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function sM(n){for(let e of n){let t=Y.resolve(e);if(!Fc(t))throw new Error(`File "${e}" does not exist.`);let r=Y.extname(t).toLowerCase();if(!yS.has(r)){let i=Array.from(yS).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function aM(n){let e=[],t=[];for(let r of n)Y.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function cM(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=lM(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
1421
+ `?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function lM(n,e,t,r,i){return t!=='"'?{field:r+t,inQuotes:i,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:i,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function dM(n,e){return e.map(t=>{let r=i=>{let o=n.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:r("Api Definition"),language:r("Language"),changeId:r("ChangeId"),changedInSdk:r("Changed in SDK"),affectedVersions:r("Affected Versions"),title:r("Title"),codeLocation:r("Code Location"),changeType:r("Change Type")}})}function uM(n){let e=XO(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=cM(t);if(r.length<2)return[];let[i,...o]=r;return dM(i,o)}function pM(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return Y.isAbsolute(r)?r:Y.join(e,r)}function mM(n,e){let t=new Map;for(let o of n){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...r.map(([o])=>o.length));console.log(Se("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${n.length}`);for(let[o,s]of r)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function fM(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(Se(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}r>0&&console.log(bS(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function gM(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({count:n.length,records:t},null,2)),r>0&&console.log(bS(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function hM(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push(Y.resolve(n.rootDir,i.srcPath))}return t}function yM(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("source-version and target-version are required.");let i=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=aM(e),a=d=>Y.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=hM(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",pp.tmpdir()),i}async function wM(n,e){let t=Y.dirname(e[0]);try{let i=(await QO(n.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(i),i.endsWith(`
1422
1422
  `)||process.stdout.write(`
1423
1423
  `),console.log(Se("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(Se("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
1424
1424
  `)||process.stdout.write(`
1425
1425
  `),console.log(Se("[compat:check] === end stdout ===")));let o=new Error(`Compatibility scan failed: ${i.message}`+(i.stderr?`
1426
- ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function XO(n,e){if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("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 Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function ZO(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new Error(`${t.join(" and ")} ${r} not in the available SDK version list.
1427
- Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function QO(n,e,t,r,i){i==="none"&&(t==="json"?qO(n,r):zO(n,r)),GO(n,e)}function eM(n,e){let t=Y.dirname(n),r=Y.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(Se(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function tM(n){try{kO(n),m(Se(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(Se(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var nM=[".csv",".json"];function rM(n){return nM.includes(n.toLowerCase())}function iM(n,e){if(!n)return{kind:"none"};let t=Y.extname(n).toLowerCase();if(!rM(t))return{kind:"dir",dirPath:Y.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Error(`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:Y.resolve(n),ext:t}}function oM(n){if(n.kind==="file"){if(kc(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=Y.dirname(n.filePath);if(!kc(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!kc(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function oS(n){return JSON.stringify({count:n.length,records:n},null,2)+`
1428
- `}function sM(n,e,t,r){r===".csv"?eS(n,t):tS(t,oS(e),"utf8"),m(Se(`[compat:check] saved report: "${t}"`))}function aM(n,e,t,r){if(r==="json"){let o=Y.basename(n,".csv"),s=Y.join(t,`${o}.json`);return tS(s,oS(e),"utf8"),m(Se(`[compat:check] saved report: "${s}"`)),s}let i=Y.join(t,Y.basename(n));return eS(n,i),m(Se(`[compat:check] saved report: "${i}"`)),i}async function cM(n,e){let t=new Ne(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function lM(n,e){XO(n,e);let t=K.discover(process.cwd());e.modules&&e.modules.length>0&&FO(t,e.modules),n.length>0&&jO(n);let r=await A.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(Se(`[compat:check] script: "${o}"`));let s=iS(i);ZO(e,s),e.outputPath&&m(Se(`[compat:check] outputPath: "${e.outputPath}"`));let a=iM(e.outputPath,e.format);return m(Se(`[compat:check] outputTarget: ${a.kind}`)),oM(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function dM(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await lM(n,e),s=NO({text:"Running compatibility check...",color:"cyan"}).start();try{await cM(o,e);let a=JO(r,n,t,e);eM(r,a);let c=await KO(o,a),l=VO(c,Ju.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(Se(`[compat:check] tmp csv: "${l}"`));let d=WO(l),h=null;if(i.kind==="file")sM(l,d,i.filePath,i.ext),h=i.filePath;else if(i.kind==="dir")h=aM(l,d,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);tM(l),s.stop(),QO(d,h,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Ku=new AO("compat").description("Compatibility checking utilities.");Ku.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.',rS,"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)",LO,100).action(async(n,e)=>{await dM(n,e)});Ku.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=MO("csv");await _O(n)});var sS=Ku;var aS=new uM("check").description("Run DevEco project checks").addCommand(qu());b()||aS.addCommand(sS);var cS=aS;import{Command as iF}from"commander";import{green as Pp,red as oF}from"colorette";import Cp from"fs";import qS from"path";import sF from"json5";var qo={liteWearable:"1",wearable:"2",tv:"3",phone:"4"},lS=Object.keys(qo),dS="phone",pM=/^[A-F0-9]+$/,Xu=64,mM=Object.fromEntries(Object.entries(qo).map(([n,e])=>[e,n]));function uS(n){return mM[n]??dS}function pS(n){let e=[];for(let t of n)for(let r of t.split(","))e.push({value:r.trim(),position:e.length+1});return e}function fM(n){let e=n.lastIndexOf(":");return e<0?{udid:n.trim(),type:null}:{udid:n.slice(0,e).trim(),type:n.slice(e+1).trim()}}function hM(n,e){if(!n)throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 missing UDID before ":<type>".`);let t=n.toUpperCase();if(!pM.test(t))throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 expected hexadecimal characters only.`);if(t.length!==Xu)throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 expected ${Xu} hexadecimal characters, got ${t.length}.`);return t}function gM(n,e){if(n===null)return;let t=lS.find(r=>r.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Invalid device type "${n}" in --udid value #${e.position}. Valid types: ${lS.join(", ")}.`);return t}function Zu(n){let e=[],t=new Set;for(let r of pS(n)){if(!r.value)throw new Error(`Invalid --udid value #${r.position}: empty. Provide a ${Xu}-character hexadecimal UDID.`);let{udid:i,type:o}=fM(r.value),s=hM(i,r),a=gM(o,r);if(t.has(s)){m(`[manualDevice] duplicate --udid ignored: ${s}`);continue}t.add(s),e.push({udid:s,type:a})}return e}function Qu(n){let e=new Set;for(let t of pS(n))t.value&&e.add(t.value.toUpperCase());return e.size}function Yo(n){return[...new Set(n.map(e=>e.trim().toUpperCase()).filter(Boolean))]}function ep(n,e){let t=new Map;for(let r of n){let i=r.udid.toUpperCase();!i||t.has(i)||t.set(i,{udid:i,type:r.type,source:"detected",typeInferred:!1})}for(let r of e){let i=t.get(r.udid);if(i){r.type&&r.type!==i.type&&console.log(`Note: device ${r.udid} is connected locally; its type is read from the device (${i.type}). The type given in --udid was ignored.`);continue}t.set(r.udid,{udid:r.udid,type:r.type??dS,source:"manual",typeInferred:r.type===void 0})}return[...t.values()]}import{readFileSync as WM}from"fs";import{join as yM}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"},Ue={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:yM(".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"},Et={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."},oe={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.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",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 xc(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function tp(n){let e=n.replace(Ue.TEAM_ID_INVALID_CHARS,"");return`${Ue.CERT_NAME_PREFIX}${e}.cer`}function wi(n,e,t){if(n===Et.FORBIDDEN)return e===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===Et.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(be.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(be.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=wM(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function wM(n){let e=mS(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?mS(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function mS(n){try{return JSON.parse(n)}catch{return null}}function np(n){return JSON.parse(n)}async function fS(n){let e=`${ie.BASE_URL}${ie.CERT_LIST_PATH}`,t=await O.postAllowFailure(e,{headers:xc(n)});if(t.statusCode!==200)throw wi(t.statusCode,t.statusText,t.data);return np(t.data)?.certList??[]}async function Nc(n,e){return(await fS(n)).find(r=>r.certName===e)??null}async function rp(n,e){let t=`${ie.BASE_URL}${ie.CERT_DELETE_PATH}`,r=await O.deleteAllowFailure(t,{headers:xc(n),params:{certIds:[e]}});if(r.statusCode!==200)throw wi(r.statusCode,r.statusText,r.data);return np(r.data)?.ret?.code===0}async function ip(n,e,t){let r=`${ie.BASE_URL}${ie.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Ue.CERT_TYPE_DEBUG},o=await O.postAllowFailure(r,{headers:xc(n),params:i});if(o.statusCode!==200)throw wi(o.statusCode,o.statusText,o.data);if(!o.data.includes(be.SUCCESS_MARKER))throw wi(void 0,o.statusText,o.data)}async function op(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=await O.postAllowFailure(t,{headers:xc(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw wi(r.statusCode,r.statusText,r.data);return np(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as vM,writeFileSync as SM,existsSync as bM}from"fs";import{dirname as EM}from"path";async function Jo(n,e){let{statusCode:t,statusText:r,buffer:i}=await O.getBinaryAllowFailure(n,{timeout:Ue.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===Et.FORBIDDEN&&r===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let o=EM(e);bM(o)||vM(o,{recursive:!0}),SM(e,i)}import HM from"fs/promises";import{readFileSync as UM}from"fs";import Lc from"path";import yS from"crypto";import PM from"os";import Ko from"fs/promises";var wS={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},hS=["ECC","RSA"],gS=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],CM={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},IM=8,sp=64,DM=/[\\:*?"<>|=-]/g,Pt={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function AM(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>sp)throw new Error(`The length of keyAlias cannot exceed ${sp}`);if(!hS.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${hS.join(" / ")}`);let e=CM[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function TM(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(!gS.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${gS.join(" / ")}`)}function RM(n){return yS.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function kM(n){let e=n?.trim()??"";return e&&e.replace(DM,"_").slice(0,sp)||Pt.productName}async function vS(){let n=await A.new(),e=n.javaPath;if(!e&&!b())throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=b()?"hap-sign-tool":"hap-sign-tool.jar",i=Lc.join(t,"default","openharmony","toolchains","lib",r);try{await Ko.access(i)}catch(o){throw new Error(`${r} not found: ${i}`,{cause:o})}return{javaPath:e,toolPath:i}}async function xM(n){let{javaPath:e,toolPath:t}=await vS(),r=[wS.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function NM(n){let{javaPath:e,toolPath:t}=await vS(),r=[wS.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function LM(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),AM(n);let e=await xM(n),t=await qn(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 f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function OM(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),TM(n);let e=await NM(n),t=await qn(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 f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function MM(n=IM){return yS.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function _M(){let n=PM.homedir();try{await Ko.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Lc.join(n,".ohos","config");try{await Ko.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 Ie(n,e,t){let r=kM(n),i=Lc.basename(e),o=RM(e),s=`${r}_${i}_${o}=.${t}`,a=await _M();return Lc.join(a,s)}function FM(n){let e;try{e=K.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function jM(n){try{await Ko.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function $M(n){try{await Ko.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function ap(n,e,t){let r=process.cwd(),i=FM(r);await jM(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=MM(),s=await Ie(n??"",i,"p12"),a=await Ie(n??"",i,"csr");return console.log("Start generating p12"),await LM({keyAlias:e?.keyAlias??Pt.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??Pt.keyAlg,keySize:e?.keySize??Pt.keySize,keystoreFile:s,keystorePwd:o}),await $M(s),console.log("Start generating csr"),await OM({subject:t?.subject??Pt.csrSubject,outFile:a,keyAlias:t?.keyAlias??Pt.keyAlias,keyPwd:o,signAlg:t?.signAlg??Pt.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??Pt.keyAlias}}var BM=["p12","cer","csr","p7b"];async function cp(n,e){for(let t of BM){let r=await Ie(n,e,t);await HM.rm(r,{force:!0})}}function lp(n){let e;try{e=UM(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!Ue.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function SS(n,e){return{certPath:await Ie(n,e,"cer"),csrPath:await Ie(n,e,"csr"),p12Path:await Ie(n,e,"p12"),profilePath:await Ie(n,e,"p7b")}}async function dp(n,e){let t=e??"",r=K.discover(process.cwd()).rootDir;await cp(t,r);let i=tp(n.teamId),o=await Nc(n,i);if(o&&!await rp(n,o.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await ap(e),a;try{a=WM(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await ip(n,a,i);let c=await Nc(n,i);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await op(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Ie(t,r,"cer");await Jo(l,d),lp(d);let h=await Ie(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import Wc from"crypto";import $n from"fs";import*as MS from"path";import u_ from"json5";import{execa as NS}from"execa";import LS from"node-forge";import{createCipheriv as VM,createDecipheriv as GM,pbkdf2Sync as zM,randomBytes as fp}from"crypto";import{promises as fr}from"fs";import{dirname as qM,join as Ct}from"path";var Oc=3,Xo=16,YM=1e4,bS="material",JM=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),IS="aes-128-gcm",mr=12,Mc=16,_n=4;function up(n){return new Uint8Array(fp(n))}function KM(n){return fp(n).toString("hex")}function XM(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function ES(n,e,t=YM,r=Xo){let i=[...n,JM],o=XM(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=zM(a,e,t,r,"sha256");return new Uint8Array(c)}function PS(n,e){let t=fp(mr),r=VM(IS,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(_n+mr+s.length);return c.writeUInt32BE(a,0),t.copy(c,_n),s.copy(c,_n+mr),c}function CS(n,e){if(e.length<_n+mr+Mc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(_n,_n+mr),i=e.subarray(_n+mr,_n+mr+t);if(i.length<Mc)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Mc),s=i.subarray(i.length-Mc),a=GM(IS,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function ZM(n){try{await fr.rm(n,{recursive:!0,force:!0})}catch{}}async function pp(n){let e=await fr.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 fr.readFile(Ct(n,t[0]))}async function mp(n,e){let t=KM(Xo),r=Ct(n,t);return await fr.writeFile(r,e),t}var Fn=class{static async generateMaterial(e){let t=Ct(e,bS);await ZM(t);let r=Ct(t,"ac"),i=Ct(t,"ce");await fr.mkdir(r,{recursive:!0}),await fr.mkdir(i,{recursive:!0});for(let d=0;d<Oc;d++)await fr.mkdir(Ct(t,"fd",String(d)),{recursive:!0});let o=up(Xo),s=[];for(let d=0;d<Oc;d++)s.push(up(Xo));let a=up(Xo),c=ES(s,o),l=PS(c,a);await mp(r,o),await mp(i,l);for(let d=0;d<Oc;d++){let h=Ct(t,"fd",String(d));await mp(h,s[d])}return a}static async readMaterial(e){let t=Ct(e,bS),r=Ct(t,"ac"),i=new Uint8Array(await pp(r)),o=[];for(let d=0;d<Oc;d++){let h=Ct(t,"fd",String(d)),w=await pp(h);o.push(new Uint8Array(w))}let s=Ct(t,"ce"),a=await pp(s),c=ES(o,i),l=CS(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=qM(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return PS(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return CS(r,i).toString("utf8")}};import kS from"fs";import Uc from"path";import i_ from"json5";import*as _c from"fs";import*as DS from"path";function Fc(n){let e=DS.resolve(n);if(!_c.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=_c.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as Si from"fs";import*as Be from"path";import{debuglog as vi}from"util";var AS={"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 QM(n){return Object.prototype.hasOwnProperty.call(AS,n)}function jc(n){if(QM(n))return AS[n]}var TS={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as e_}from"url";var Hc=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 $c(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function RS(n){return n==null||n.length===0}function t_(n){return!RS(n)}function hp(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function n_(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 r_(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 jn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Be.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=Be.join("lib","permissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Be.join(t.sdkPath,"default","sdk-pkg.json"),a=Fc(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Be.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Si.existsSync(e))return Si.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=e_(e);if(t.includes("dist")){let s=Be.dirname(t),a=Be.dirname(s);return Be.join(a,"src","resources")}let r=Be.dirname(t),i=Be.dirname(r),o=Be.dirname(i);return Be.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{vi("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:$c(i)?Object.values(i):[]).filter($c).map(a=>new Hc(a));s.forEach(a=>{let c=a.permissionInsteadName;t_(c)&&(a.permissionInsteadName=jc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){vi(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!$c(o))return;let s=o,a=hp(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(RS(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||hp(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||hp(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:n_(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Hc;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=r_(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Be.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Si.existsSync(t))return;let r;try{r=Si.readFileSync(t,"utf-8")}catch(s){vi(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!$c(s)){vi("json object is null");return}i=s}catch(s){vi(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){vi("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=jc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=jc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Bc(n,e){let t=new Set,r=new Set;jn.handleSpecificAclPermissions(),jn.initAclPermission(n,e);for(let i of n.profile.modules){let o=xS(i,n,e,r,Uc.join("src","main"));for(let a of o)t.add(a);let s=xS(i,n,e,r,Uc.join("src","ohosTest"));for(let a of s)t.add(a)}return o_(r),t}function o_(n){if(n.size>0)throw new Error(TS.DUPLICATE_PERMISSION)}function xS(n,e,t,r,i){let o=a_(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let w of o){if(typeof w!="object"||w===null)continue;let v=s_(w,"name");v&&s.push(v)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Uc.join(t.sdkPath,"default","sdk-pkg.json"),l=Fc(c),d=jn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let v=Number(w.minSupportApiLevel);return Number.isFinite(v)&&v<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function s_(n,e){let t=n[e];return typeof t=="string"?t:""}function a_(n,e,t){let r=Uc.join(n,e.srcPath,t,"module.json5"),i=c_(r);if(i==null)return null;let o=l_(i,"module");return o==null?null:d_(o,"requestPermissions")}function c_(n){try{if(!kS.existsSync(n))return null;let e=kS.readFileSync(n,"utf-8");return i_.parse(e)}catch{return null}}function l_(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 d_(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var yp=class{verifyStorePassword(e,t){try{let r=$n.readFileSync(e),i=LS.asn1.fromDer(r.toString("binary"));return LS.pkcs12.pkcs12FromAsn1(i,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(i=>this.formatFp(new Wc.X509Certificate(i).fingerprint256));try{return[this.formatFp(new Wc.X509Certificate($n.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=$n.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new Wc.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function p_(n){let e=$n.readFileSync(n,"utf-8"),t=m_(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:gp(i["bundle-name"]),expiryDate:f_(r?.validity?.["not-after"]),cerFingerprintInProfile:h_(gp(i["development-certificate"])),deviceUdidsInProfile:g_(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:y_(r?.acls?.["allowed-acls"]),teamIdInProfile:gp(i["developer-id"])}}function m_(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function f_(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function h_(n){if(!n)return null;try{let t=new Wc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function g_(n){return Array.isArray(n)?Yo(n.filter(e=>typeof e=="string")):[]}function y_(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 gp(n){return typeof n=="string"?n:null}var Zo=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.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=K.discover(process.cwd()),a=s.rootDir,c=Yo(e.manualUdids??[]),[l,d]=await Promise.all([w_(o,a),S_(t.hdcPath,c.length>0)]),h=null;if(OS(l).allExist)try{h=p_(l.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:l,bundleName:s.getBundleName(),deviceUdids:Yo([...d,...c]),manualUdids:c,storePassword:await v_(a,o,l.storeFile),localAclPermissions:[...Bc(s,t)].sort(),hapSignTool:new yp,profileInfo:h}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ke({force:!0})}):null}static#n(e){let t=OS(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ke({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(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:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(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:Ke({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:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=P_(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.map(i=>e.manualUdids.includes(i)?`${i} (manual)`:`${i} (detected)`).join(", ")}`,checkDetails:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return C_(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ke({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:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Ke({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:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Ke({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:Ke({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:Ke({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:Ke({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function w_(n,e){let[t,r,i,o]=await Promise.all([Ie(n,e,"p12"),Ie(n,e,"csr"),Ie(n,e,"cer"),Ie(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function v_(n,e,t){let r=MS.join(n,"build-profile.json5");if(!$n.existsSync(r))return;let i;try{i=u_.parse($n.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Fn.decryptPassword(a,t)}catch{return}}async function S_(n,e){try{return await b_(n)}catch(t){if(!e)throw t;return m(`[reGenerateSign] device detection failed, continuing with --udid only: ${t.message}`),[]}}async function b_(n){m(`Executing: ${n} list targets`);let{stdout:e}=await NS(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1429
- `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{m(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await NS(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=E_(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function E_(n){let e=n.trim();if(!e)return null;let t=e.split(`
1430
- `);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function OS(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)$n.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function P_(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function C_(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Ke(n){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 n.force?{...e,force:!0}:{...e,...n,force:!1}}import{debuglog as wp}from"util";import{execa as vp}from"execa";async function FS(n,e,t=[]){let r=await Vc(n),i=await A_(e,t.length>0),o=ep(i,t);if(o.length===0){if(r.length>0)return m("[registerDevice] no local/manual devices; reusing cloud-registered devices"),{allDeviceIds:r.map(l=>l.id),devices:r.map(l=>({udid:l.udid.toUpperCase(),type:uS(l.deviceType??""),source:"cloud",typeInferred:!l.deviceType}))};throw new Error(E.DEVICE_LIST_EMPTY)}let s=new Set(r.map(l=>l.udid.toUpperCase()));for(let l of o)s.has(l.udid)||await I_(n,l);let c=(await Vc(n)).map(l=>l.id);if(c.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return{allDeviceIds:c,devices:o}}async function I_(n,e){try{await D_(n,e.udid,qo[e.type])}catch(t){let r=e.source==="manual"?"from --udid":"detected locally";throw new Error(`${t.message} (device ${e.udid}, ${r})`,{cause:t})}}async function _S(n,e=1,t=100){let r=`${ie.BASE_URL}${ie.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=$S(n),o=await O.get(r,{headers:i});if(!o)throw wp("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw jS(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw wp("query devices failed: response list is null"),new Error(s.ret?.msg||E.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function jS(n,e,t){return n===Et.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===Et.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(be.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function Vc(n){let t=await _S(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await _S(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function D_(n,e,t){let r=`${ie.BASE_URL}${ie.DEVICE_ADD_PATH}`,i=$S(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await O.postAllowFailure(r,{headers:i,params:s});if(!a)throw wp("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw jS(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(E.DEVICE_LIMIT_REACHED):c.includes(be.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function $S(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function A_(n,e){try{return await T_(n)}catch(t){if(!e)throw t;return m(`[registerDevice] local detection failed, continuing with --udid only: ${t.message}`),[]}}async function T_(n){m(`Executing: ${n} list targets`);let{stdout:e}=await vp(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1431
- `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await R_(i,n),s=await k_(i,n);o.length>0&&r.push({udid:o,type:s})}catch{m(`Failed to get device info for ${i}, skipping`)}return r}async function R_(n,e){m(`Executing: ${e} -t ${n} shell bm get -u`);let{stdout:t}=await vp(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
1432
- `);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function k_(n,e){let t="hw_sc.build.os.deviceType";m(`Executing: ${e} -c -t ${n} shell getprop ${t}`);let{stdout:r}=await vp(e,["-c","-t",n,"shell","getprop",t],{stdio:["ignore","pipe","pipe"]});return x_(r)}function x_(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 hr from"fs";import{createHash as N_}from"crypto";import{Buffer as US}from"buffer";import{createPublicKey as L_,X509Certificate as Sp}from"crypto";import{readFileSync as O_}from"fs";import gr from"node-forge";async function BS(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${ie.BASE_URL}${ie.PROVISION_ADD_TEST_PATH}`,h=M_(t,r),w=await F_(n,d,a||[],r,s,h,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw m("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let v=w.profileInfo,ce=(await U_(n,v.provisionFileUrl)).urlList,We=w.profileInfo.id;if(ce&&ce.length>0){let ct=await SS(t,i),lt=ct.profilePath;if(!await B_(ce,lt))throw await HS(n,We),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await HS(n,We),hr.existsSync(ct.certPath)&&hr.existsSync(lt)&&hr.existsSync(ct.p12Path)){let Kc=hr.readFileSync(ct.certPath,"utf8"),Xc=hr.readFileSync(lt,"utf8");return W_(Xc,Kc,ct.p12Path,c,l)||H_(lt),lt}}throw new Error(E.ADD_PROFILE_FAIL)}function M_(n,e){let t=n?`${n}_`:"";return`${__(`${t}${e}_${e}`)}`}function __(n){return N_("sha256").update(n).digest("hex").substring(0,16)}async function F_(n,e,t,r,i,o,s){j_(r);let a=Ep(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await O.postAllowFailure(e,{headers:a,params:c});if(!l)throw m("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw bp(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw m(`add provision fail: ${l.data}`),$_(l.data,o),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:h}}}function bp(n,e,t){return n===Et.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===Et.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(be.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function j_(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Ue.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function $_(n,e){if(n.includes(be.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(be.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function HS(n,e){if(!e||e.trim().length===0)return;let t=`${ie.BASE_URL}${ie.PROVISION_DELETE_PATH}?id=${e}`,r=await O.deleteAllowFailure(t,{headers:Ep(n)});if(r.statusCode!==200)throw bp(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&m(`delete provision failed: ${r.data}`)}function H_(...n){for(let e of n)try{hr.existsSync(e)&&hr.unlinkSync(e)}catch(t){m(`delete local sign file error: ${t.message}`)}}async function U_(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=Ep(n),i={sourceUrls:e},o=await O.postAllowFailure(t,{headers:r,params:i});if(!o)throw m("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw bp(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw m("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function B_(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Jo(t,e),!0}function W_(n,e,t,r,i){return V_(n,e),r=r||Ue.TARGET_FRIENDLY_NAME,i=i||"",G_(e,t,r,i),!0}function V_(n,e){if(e.lastIndexOf(Ue.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Ue.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function G_(n,e,t,r){let i=n.matchAll(Ue.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=z_(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let v=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${v}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!Y_(e,t,r,o))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function z_(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Sp(t);let r=US.from(t,"base64");return new Sp(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function q_(n){if(n.cert){let e=gr.pki.publicKeyToPem(n.cert.publicKey);return L_(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=gr.asn1.toDer(n.asn1).getBytes(),t=US.from(e,"binary");return new Sp(t).publicKey.export({type:"spki",format:"der"})}catch(e){return m(`Failed to parse cert from asn1: ${e}`),null}return null}function Y_(n,e,t,r){try{let i=O_(n),o=gr.asn1.fromDer(gr.util.createBuffer(i)),c=gr.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:gr.pki.oids.certBag})[gr.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=q_(l);if(!h)continue;if(r.some(v=>{let k=v.publicKey.export({type:"spki",format:"der"});return h.equals(k)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return m(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Ep(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var VS="https://developer.huawei.com",J_={"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"},K_="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function X_(n){let e=J_[n];return e?`${VS}${e}`:void 0}function Z_(){return`${VS}${K_}`}var Q_={"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 WS(n,e){return(Q_[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function eF(n){return Array.from(n).join(", ")}function GS(n,e){if(n.size===0)return;let t=jn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=X_(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let i=new Set;for(let h of r)i.add(h.permissionDisplayName);let o=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;o.add(`${w} (${h.permissionHelpUrlKey})`)}let s=Z_(),a=WS("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=WS("acl.permissions.warn",[eF(i),l,c]);console.log(d)}var Gc=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=K.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(oe.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:oe.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import tF from"fs";import zS from"path";var zc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(oe.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",i=zS.join(t,"default","openharmony","toolchains","lib",r);if(!tF.existsSync(i)){let o=zS.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var qc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Te.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Te.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(oe.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(oe.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(oe.TEAM_INFO_FAILED);try{if((await mn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(oe.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(oe.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(oe.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(oe.REALNAME_REQUIRED)):{passed:!0,message:""}:e(oe.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await mn();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return m(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(oe.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(oe.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function nF(n){try{let{teamList:e}=await mn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function rF(n){let e=await Te.getUserInfo(),t=await Te.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await nF(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Vc(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Yc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t,r=!1){if(r)return m("[EnvCheck] Scenario 4 Device check: --udid provided, skipping device detection"),{passed:!0,message:""};try{let i=await rF(t);return i.length>0?(m(`[EnvCheck] Scenario 4 Device check: ${i.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""}):(m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc"),(await ae.from(this.toolProvider).listDevices()).length>0?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(oe.DEVICE_MISSING)))}catch(i){return m(`[EnvCheck] Scenario 4 Device check failed: ${i.message}`),e(oe.DEVICE_DETECT_FAILED)}}};var Jc=class{projectChecker=new Gc;toolchainChecker=null;authChecker=new qc;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await A.new();return this.toolchainChecker=new zc(e),this.deviceChecker=new Yc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(oe.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId,e.hasManualDevices??!1))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function aF(n){if(Cp.existsSync(n)){let e=Cp.readFileSync(n,"utf-8");return sF.parse(e)}return{app:{signingConfigs:[],products:[]}}}function cF(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function lF(n){if(n.keyPwd===n.storePassword){let r=await Fn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Fn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Fn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function dF(n,e,t){let r=qS.join(n,"build-profile.json5"),i=aF(r);cF(i);let o=t??"default",{keyPassword:s,storePassword:a}=await lF(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:Pt.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(h=>h.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(h=>h.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),Cp.writeFileSync(r,JSON.stringify(i,null,2),"utf-8")}async function uF(n){let e=await Te.getUserInfo(),t=await Te.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 pF(n){let e=n.product||"default",t=Zu(n.udid??[]);await new Jc().preflight({productName:e,teamId:n.teamId,hasManualDevices:t.length>0}),console.log("Executing signature generate command");let i=await uF(n),o=await A.new(),{shouldRegenerate:s}=await Zo.shouldRegenerate({force:n.force??!1,teamId:i.teamId,productName:n.product,manualUdids:t.map(a=>a.udid)},o);if(!s){console.log(Pp("Signature generation completed successfully."));return}await fF(n,i,o,t),console.log(Pp("Signature generation completed successfully."))}function mF(n){console.log(`Profile covers ${n.length} device(s):`);for(let e of n){let t=e.source==="manual"&&e.typeInferred?"manual, type inferred":e.source;console.log(` ${e.udid} ${e.type.padEnd(12)} (${t})`)}}async function fF(n,e,t,r){let i=await dp(e,n.product),o=hF(n,e,i,t),{allDeviceIds:s,devices:a}=await FS(e,t.hdcPath,r);o.allDeviceIds=s,await BS(e,o),mF(a);let c=K.discover(process.cwd()).rootDir;await dF(c,i,n.product??"default"),console.log(Pp(`Signing config written to ${qS.join(c,"build-profile.json5")}`))}function hF(n,e,t,r){let i=process.cwd(),o=K.discover(i),s=Bc(o,r);return GS(s,o),{productName:n.product||"default",bundleName:o.getBundleName(),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var YS=new iF("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.").option("--udid <udid...>",'Add device UDID(s) that are not connected. Repeatable or comma-separated; append ":<type>" to declare phone|wearable|liteWearable|tv (default: phone).').action(async n=>{let e={event:D.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[],...n.udid?["--udid",String(Qu(n.udid))]:[]]},t=Date.now(),r=!0,i=null;try{await pF(n)}catch(o){r=!1,i=W(o),console.error(oF(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}});var JS=YS;if(!Qe())try{I.init(Dp.join(Zt(),"TraceLogData")),I.startScheduler()}catch(n){g.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Qe())try{let n=await A.new();I.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?I.setCltVersion(e):I.setStudioVersion(e))}catch(n){g.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();de.name("devecocli").description(`HarmonyOS application development command line tool
1426
+ ${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function vM(n,e){if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("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 Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function SM(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new Error(`${t.join(" and ")} ${r} not in the available SDK version list.
1427
+ Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function bM(n,e,t,r,i){i==="none"&&(t==="json"?gM(n,r):fM(n,r)),mM(n,e)}function EM(n,e){let t=Y.dirname(n),r=Y.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(Se(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function PM(n){try{ZO(n),m(Se(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(Se(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var CM=[".csv",".json"];function IM(n){return CM.includes(n.toLowerCase())}function DM(n,e){if(!n)return{kind:"none"};let t=Y.extname(n).toLowerCase();if(!IM(t))return{kind:"dir",dirPath:Y.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Error(`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:Y.resolve(n),ext:t}}function AM(n){if(n.kind==="file"){if(Fc(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=Y.dirname(n.filePath);if(!Fc(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Fc(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function CS(n){return JSON.stringify({count:n.length,records:n},null,2)+`
1428
+ `}function TM(n,e,t,r){r===".csv"?vS(n,t):SS(t,CS(e),"utf8"),m(Se(`[compat:check] saved report: "${t}"`))}function RM(n,e,t,r){if(r==="json"){let o=Y.basename(n,".csv"),s=Y.join(t,`${o}.json`);return SS(s,CS(e),"utf8"),m(Se(`[compat:check] saved report: "${s}"`)),s}let i=Y.join(t,Y.basename(n));return vS(n,i),m(Se(`[compat:check] saved report: "${i}"`)),i}async function kM(n,e){let t=new xe(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function xM(n,e){vM(n,e);let t=K.discover(process.cwd());e.modules&&e.modules.length>0&&oM(t,e.modules),n.length>0&&sM(n);let r=await A.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(Se(`[compat:check] script: "${o}"`));let s=PS(i);SM(e,s),e.outputPath&&m(Se(`[compat:check] outputPath: "${e.outputPath}"`));let a=DM(e.outputPath,e.format);return m(Se(`[compat:check] outputTarget: ${a.kind}`)),AM(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function NM(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await xM(n,e),s=eM({text:"Running compatibility check...",color:"cyan"}).start();try{await kM(o,e);let a=yM(r,n,t,e);EM(r,a);let c=await wM(o,a),l=pM(c,pp.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(Se(`[compat:check] tmp csv: "${l}"`));let d=uM(l),g=null;if(i.kind==="file")TM(l,d,i.filePath,i.ext),g=i.filePath;else if(i.kind==="dir")g=RM(l,d,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);PM(l),s.stop(),bM(d,g,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var mp=new JO("compat").description("Compatibility checking utilities.");mp.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.',ES,"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)",tM,100).action(async(n,e)=>{await NM(n,e)});mp.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=rM("csv");await iM(n)});var IS=mp;var DS=new LM("check").description("Run DevEco project checks").addCommand(dp());b()||DS.addCommand(IS);var AS=DS;import{Command as DF}from"commander";import{green as Hp,red as AF}from"colorette";import Up from"fs";import pb from"path";import TF from"json5";var Xo={liteWearable:"1",wearable:"2",tv:"3",phone:"4"},TS=Object.keys(Xo),RS="phone",OM=/^[A-F0-9]+$/,fp=64,MM=Object.fromEntries(Object.entries(Xo).map(([n,e])=>[e,n]));function kS(n){return MM[n]??RS}function xS(n){let e=[];for(let t of n)for(let r of t.split(","))e.push({value:r.trim(),position:e.length+1});return e}function _M(n){let e=n.lastIndexOf(":");return e<0?{udid:n.trim(),type:null}:{udid:n.slice(0,e).trim(),type:n.slice(e+1).trim()}}function FM(n,e){if(!n)throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 missing UDID before ":<type>".`);let t=n.toUpperCase();if(!OM.test(t))throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 expected hexadecimal characters only.`);if(t.length!==fp)throw new Error(`Invalid --udid value #${e.position}: "${e.value}" \u2014 expected ${fp} hexadecimal characters, got ${t.length}.`);return t}function jM(n,e){if(n===null)return;let t=TS.find(r=>r.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Invalid device type "${n}" in --udid value #${e.position}. Valid types: ${TS.join(", ")}.`);return t}function gp(n){let e=[],t=new Set;for(let r of xS(n)){if(!r.value)throw new Error(`Invalid --udid value #${r.position}: empty. Provide a ${fp}-character hexadecimal UDID.`);let{udid:i,type:o}=_M(r.value),s=FM(i,r),a=jM(o,r);if(t.has(s)){m(`[manualDevice] duplicate --udid ignored: ${s}`);continue}t.add(s),e.push({udid:s,type:a})}return e}function hp(n){let e=new Set;for(let t of xS(n))t.value&&e.add(t.value.toUpperCase());return e.size}function Zo(n){return[...new Set(n.map(e=>e.trim().toUpperCase()).filter(Boolean))]}function yp(n,e){let t=new Map;for(let r of n){let i=r.udid.toUpperCase();!i||t.has(i)||t.set(i,{udid:i,type:r.type,source:"detected",typeInferred:!1})}for(let r of e){let i=t.get(r.udid);if(i){r.type&&r.type!==i.type&&console.log(`Note: device ${r.udid} is connected locally; its type is read from the device (${i.type}). The type given in --udid was ignored.`);continue}t.set(r.udid,{udid:r.udid,type:r.type??RS,source:"manual",typeInferred:r.type===void 0})}return[...t.values()]}import{readFileSync as u_}from"fs";import{join as $M}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"},He={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:$M(".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"},bt={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."},oe={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.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",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 jc(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function wp(n){let e=n.replace(He.TEAM_ID_INVALID_CHARS,"");return`${He.CERT_NAME_PREFIX}${e}.cer`}function bi(n,e,t){if(n===bt.FORBIDDEN)return e===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===bt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(be.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(be.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=HM(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function HM(n){let e=NS(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?NS(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function NS(n){try{return JSON.parse(n)}catch{return null}}function vp(n){return JSON.parse(n)}async function LS(n){let e=`${ie.BASE_URL}${ie.CERT_LIST_PATH}`,t=await O.postAllowFailure(e,{headers:jc(n)});if(t.statusCode!==200)throw bi(t.statusCode,t.statusText,t.data);return vp(t.data)?.certList??[]}async function $c(n,e){return(await LS(n)).find(r=>r.certName===e)??null}async function Sp(n,e){let t=`${ie.BASE_URL}${ie.CERT_DELETE_PATH}`,r=await O.deleteAllowFailure(t,{headers:jc(n),params:{certIds:[e]}});if(r.statusCode!==200)throw bi(r.statusCode,r.statusText,r.data);return vp(r.data)?.ret?.code===0}async function bp(n,e,t){let r=`${ie.BASE_URL}${ie.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:He.CERT_TYPE_DEBUG},o=await O.postAllowFailure(r,{headers:jc(n),params:i});if(o.statusCode!==200)throw bi(o.statusCode,o.statusText,o.data);if(!o.data.includes(be.SUCCESS_MARKER))throw bi(void 0,o.statusText,o.data)}async function Ep(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=await O.postAllowFailure(t,{headers:jc(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw bi(r.statusCode,r.statusText,r.data);return vp(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as UM,writeFileSync as BM,existsSync as WM}from"fs";import{dirname as VM}from"path";async function Qo(n,e){let{statusCode:t,statusText:r,buffer:i}=await O.getBinaryAllowFailure(n,{timeout:He.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===bt.FORBIDDEN&&r===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let o=VM(e);WM(o)||UM(o,{recursive:!0}),BM(e,i)}import c_ from"fs/promises";import{readFileSync as l_}from"fs";import Hc from"path";import _S from"crypto";import GM from"os";import es from"fs/promises";var FS={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},OS=["ECC","RSA"],MS=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],zM={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},qM=8,Pp=64,YM=/[\\:*?"<>|=-]/g,Et={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function JM(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>Pp)throw new Error(`The length of keyAlias cannot exceed ${Pp}`);if(!OS.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${OS.join(" / ")}`);let e=zM[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function KM(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(!MS.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${MS.join(" / ")}`)}function XM(n){return _S.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function ZM(n){let e=n?.trim()??"";return e&&e.replace(YM,"_").slice(0,Pp)||Et.productName}async function jS(){let n=await A.new(),e=n.javaPath;if(!e&&!b())throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=b()?"hap-sign-tool":"hap-sign-tool.jar",i=Hc.join(t,"default","openharmony","toolchains","lib",r);try{await es.access(i)}catch(o){throw new Error(`${r} not found: ${i}`,{cause:o})}return{javaPath:e,toolPath:i}}async function QM(n){let{javaPath:e,toolPath:t}=await jS(),r=[FS.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function e_(n){let{javaPath:e,toolPath:t}=await jS(),r=[FS.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function t_(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),JM(n);let e=await QM(n),t=await Zn(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 f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function n_(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),KM(n);let e=await e_(n),t=await Zn(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 f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function r_(n=qM){return _S.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function i_(){let n=GM.homedir();try{await es.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Hc.join(n,".ohos","config");try{await es.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 Ie(n,e,t){let r=ZM(n),i=Hc.basename(e),o=XM(e),s=`${r}_${i}_${o}=.${t}`,a=await i_();return Hc.join(a,s)}function o_(n){let e;try{e=K.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function s_(n){try{await es.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function a_(n){try{await es.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Cp(n,e,t){let r=process.cwd(),i=o_(r);await s_(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=r_(),s=await Ie(n??"",i,"p12"),a=await Ie(n??"",i,"csr");return console.log("Start generating p12"),await t_({keyAlias:e?.keyAlias??Et.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??Et.keyAlg,keySize:e?.keySize??Et.keySize,keystoreFile:s,keystorePwd:o}),await a_(s),console.log("Start generating csr"),await n_({subject:t?.subject??Et.csrSubject,outFile:a,keyAlias:t?.keyAlias??Et.keyAlias,keyPwd:o,signAlg:t?.signAlg??Et.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??Et.keyAlias}}var d_=["p12","cer","csr","p7b"];async function Ip(n,e){for(let t of d_){let r=await Ie(n,e,t);await c_.rm(r,{force:!0})}}function Dp(n){let e;try{e=l_(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!He.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function $S(n,e){return{certPath:await Ie(n,e,"cer"),csrPath:await Ie(n,e,"csr"),p12Path:await Ie(n,e,"p12"),profilePath:await Ie(n,e,"p7b")}}async function Ap(n,e){let t=e??"",r=K.discover(process.cwd()).rootDir;await Ip(t,r);let i=wp(n.teamId),o=await $c(n,i);if(o&&!await Sp(n,o.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await Cp(e),a;try{a=u_(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await bp(n,a,i);let c=await $c(n,i);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await Ep(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Ie(t,r,"cer");await Qo(l,d),Dp(d);let g=await Ie(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 Kc from"crypto";import Vn from"fs";import*as eb from"path";import L_ from"json5";import{execa as XS}from"execa";import ZS from"node-forge";import{createCipheriv as p_,createDecipheriv as m_,pbkdf2Sync as f_,randomBytes as xp}from"crypto";import{promises as vr}from"fs";import{dirname as g_,join as Pt}from"path";var Uc=3,ts=16,h_=1e4,HS="material",y_=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),VS="aes-128-gcm",wr=12,Bc=16,Un=4;function Tp(n){return new Uint8Array(xp(n))}function w_(n){return xp(n).toString("hex")}function v_(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function US(n,e,t=h_,r=ts){let i=[...n,y_],o=v_(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=f_(a,e,t,r,"sha256");return new Uint8Array(c)}function BS(n,e){let t=xp(wr),r=p_(VS,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(Un+wr+s.length);return c.writeUInt32BE(a,0),t.copy(c,Un),s.copy(c,Un+wr),c}function WS(n,e){if(e.length<Un+wr+Bc)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Un,Un+wr),i=e.subarray(Un+wr,Un+wr+t);if(i.length<Bc)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Bc),s=i.subarray(i.length-Bc),a=m_(VS,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function S_(n){try{await vr.rm(n,{recursive:!0,force:!0})}catch{}}async function Rp(n){let e=await vr.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 vr.readFile(Pt(n,t[0]))}async function kp(n,e){let t=w_(ts),r=Pt(n,t);return await vr.writeFile(r,e),t}var Bn=class{static async generateMaterial(e){let t=Pt(e,HS);await S_(t);let r=Pt(t,"ac"),i=Pt(t,"ce");await vr.mkdir(r,{recursive:!0}),await vr.mkdir(i,{recursive:!0});for(let d=0;d<Uc;d++)await vr.mkdir(Pt(t,"fd",String(d)),{recursive:!0});let o=Tp(ts),s=[];for(let d=0;d<Uc;d++)s.push(Tp(ts));let a=Tp(ts),c=US(s,o),l=BS(c,a);await kp(r,o),await kp(i,l);for(let d=0;d<Uc;d++){let g=Pt(t,"fd",String(d));await kp(g,s[d])}return a}static async readMaterial(e){let t=Pt(e,HS),r=Pt(t,"ac"),i=new Uint8Array(await Rp(r)),o=[];for(let d=0;d<Uc;d++){let g=Pt(t,"fd",String(d)),w=await Rp(g);o.push(new Uint8Array(w))}let s=Pt(t,"ce"),a=await Rp(s),c=US(o,i),l=WS(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=g_(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return BS(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return WS(r,i).toString("utf8")}};import JS from"fs";import Yc from"path";import D_ from"json5";import*as Wc from"fs";import*as GS from"path";function Vc(n){let e=GS.resolve(n);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 r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as Pi from"fs";import*as Ue from"path";import{debuglog as Ei}from"util";var zS={"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 b_(n){return Object.prototype.hasOwnProperty.call(zS,n)}function Gc(n){if(b_(n))return zS[n]}var qS={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as E_}from"url";var qc=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 zc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function YS(n){return n==null||n.length===0}function P_(n){return!YS(n)}function Np(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function C_(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 I_(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 Wn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Ue.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=Ue.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Ue.join(t.sdkPath,"default","sdk-pkg.json"),a=Vc(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Ue.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Pi.existsSync(e))return Pi.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=E_(e);if(t.includes("dist")){let s=Ue.dirname(t),a=Ue.dirname(s);return Ue.join(a,"src","resources")}let r=Ue.dirname(t),i=Ue.dirname(r),o=Ue.dirname(i);return Ue.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Ei("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:zc(i)?Object.values(i):[]).filter(zc).map(a=>new qc(a));s.forEach(a=>{let c=a.permissionInsteadName;P_(c)&&(a.permissionInsteadName=Gc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Ei(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!zc(o))return;let s=o,a=Np(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(YS(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Np(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Np(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:C_(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new qc;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=I_(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Ue.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Pi.existsSync(t))return;let r;try{r=Pi.readFileSync(t,"utf-8")}catch(s){Ei(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!zc(s)){Ei("json object is null");return}i=s}catch(s){Ei(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Ei("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Gc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Gc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Jc(n,e){let t=new Set,r=new Set;Wn.handleSpecificAclPermissions(),Wn.initAclPermission(n,e);for(let i of n.profile.modules){let o=KS(i,n,e,r,Yc.join("src","main"));for(let a of o)t.add(a);let s=KS(i,n,e,r,Yc.join("src","ohosTest"));for(let a of s)t.add(a)}return A_(r),t}function A_(n){if(n.size>0)throw new Error(qS.DUPLICATE_PERMISSION)}function KS(n,e,t,r,i){let o=R_(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let w of o){if(typeof w!="object"||w===null)continue;let v=T_(w,"name");v&&s.push(v)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Yc.join(t.sdkPath,"default","sdk-pkg.json"),l=Vc(c),d=Wn.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(w=>{let v=Number(w.minSupportApiLevel);return Number.isFinite(v)&&v<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function T_(n,e){let t=n[e];return typeof t=="string"?t:""}function R_(n,e,t){let r=Yc.join(n,e.srcPath,t,"module.json5"),i=k_(r);if(i==null)return null;let o=x_(i,"module");return o==null?null:N_(o,"requestPermissions")}function k_(n){try{if(!JS.existsSync(n))return null;let e=JS.readFileSync(n,"utf-8");return D_.parse(e)}catch{return null}}function x_(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 N_(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Op=class{verifyStorePassword(e,t){try{let r=Vn.readFileSync(e),i=ZS.asn1.fromDer(r.toString("binary"));return ZS.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=Vn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new Kc.X509Certificate(i).fingerprint256));try{return[this.formatFp(new Kc.X509Certificate(Vn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=Vn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new Kc.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function O_(n){let e=Vn.readFileSync(n,"utf-8"),t=M_(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Lp(i["bundle-name"]),expiryDate:__(r?.validity?.["not-after"]),cerFingerprintInProfile:F_(Lp(i["development-certificate"])),deviceUdidsInProfile:j_(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:$_(r?.acls?.["allowed-acls"]),teamIdInProfile:Lp(i["developer-id"])}}function M_(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function __(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function F_(n){if(!n)return null;try{let t=new Kc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function j_(n){return Array.isArray(n)?Zo(n.filter(e=>typeof e=="string")):[]}function $_(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 Lp(n){return typeof n=="string"?n:null}var ns=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.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=K.discover(process.cwd()),a=s.rootDir,c=Zo(e.manualUdids??[]),[l,d]=await Promise.all([H_(o,a),B_(t.hdcPath,c.length>0)]),g=null;if(QS(l).allExist)try{g=O_(l.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:l,bundleName:s.getBundleName(),deviceUdids:Zo([...d,...c]),manualUdids:c,storePassword:await U_(a,o,l.storeFile),localAclPermissions:[...Jc(s,t)].sort(),hapSignTool:new Op,profileInfo:g}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Je({force:!0})}):null}static#n(e){let t=QS(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Je({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(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:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(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:Je({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:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=G_(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.map(i=>e.manualUdids.includes(i)?`${i} (manual)`:`${i} (detected)`).join(", ")}`,checkDetails:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return z_(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Je({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:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Je({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:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Je({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:Je({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:Je({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:Je({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function H_(n,e){let[t,r,i,o]=await Promise.all([Ie(n,e,"p12"),Ie(n,e,"csr"),Ie(n,e,"cer"),Ie(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function U_(n,e,t){let r=eb.join(n,"build-profile.json5");if(!Vn.existsSync(r))return;let i;try{i=L_.parse(Vn.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Bn.decryptPassword(a,t)}catch{return}}async function B_(n,e){try{return await W_(n)}catch(t){if(!e)throw t;return m(`[reGenerateSign] device detection failed, continuing with --udid only: ${t.message}`),[]}}async function W_(n){m(`Executing: ${n} list targets`);let{stdout:e}=await XS(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1429
+ `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{m(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await XS(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=V_(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function V_(n){let e=n.trim();if(!e)return null;let t=e.split(`
1430
+ `);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function QS(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)Vn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function G_(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function z_(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Je(n){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 n.force?{...e,force:!0}:{...e,...n,force:!1}}import{debuglog as Mp}from"util";import{execa as _p}from"execa";async function nb(n,e,t=[]){let r=await Xc(n),i=await J_(e,t.length>0),o=yp(i,t);if(o.length===0){if(r.length>0)return m("[registerDevice] no local/manual devices; reusing cloud-registered devices"),{allDeviceIds:r.map(l=>l.id),devices:r.map(l=>({udid:l.udid.toUpperCase(),type:kS(l.deviceType??""),source:"cloud",typeInferred:!l.deviceType}))};throw new Error(E.DEVICE_LIST_EMPTY)}let s=new Set(r.map(l=>l.udid.toUpperCase()));for(let l of o)s.has(l.udid)||await q_(n,l);let c=(await Xc(n)).map(l=>l.id);if(c.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return{allDeviceIds:c,devices:o}}async function q_(n,e){try{await Y_(n,e.udid,Xo[e.type])}catch(t){let r=e.source==="manual"?"from --udid":"detected locally";throw new Error(`${t.message} (device ${e.udid}, ${r})`,{cause:t})}}async function tb(n,e=1,t=100){let r=`${ie.BASE_URL}${ie.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=ib(n),o=await O.get(r,{headers:i});if(!o)throw Mp("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw rb(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Mp("query devices failed: response list is null"),new Error(s.ret?.msg||E.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function rb(n,e,t){return n===bt.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===bt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(be.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function Xc(n){let t=await tb(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await tb(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function Y_(n,e,t){let r=`${ie.BASE_URL}${ie.DEVICE_ADD_PATH}`,i=ib(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await O.postAllowFailure(r,{headers:i,params:s});if(!a)throw Mp("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw rb(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(E.DEVICE_LIMIT_REACHED):c.includes(be.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function ib(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function J_(n,e){try{return await K_(n)}catch(t){if(!e)throw t;return m(`[registerDevice] local detection failed, continuing with --udid only: ${t.message}`),[]}}async function K_(n){m(`Executing: ${n} list targets`);let{stdout:e}=await _p(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
1431
+ `)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await X_(i,n),s=await Z_(i,n);o.length>0&&r.push({udid:o,type:s})}catch{m(`Failed to get device info for ${i}, skipping`)}return r}async function X_(n,e){m(`Executing: ${e} -t ${n} shell bm get -u`);let{stdout:t}=await _p(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
1432
+ `);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function Z_(n,e){let t="hw_sc.build.os.deviceType";m(`Executing: ${e} -c -t ${n} shell getprop ${t}`);let{stdout:r}=await _p(e,["-c","-t",n,"shell","getprop",t],{stdio:["ignore","pipe","pipe"]});return Q_(r)}function Q_(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 Sr from"fs";import{createHash as eF}from"crypto";import{Buffer as sb}from"buffer";import{createPublicKey as tF,X509Certificate as Fp}from"crypto";import{readFileSync as nF}from"fs";import br from"node-forge";async function ab(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${ie.BASE_URL}${ie.PROVISION_ADD_TEST_PATH}`,g=rF(t,r),w=await oF(n,d,a||[],r,s,g,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw m("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let v=w.profileInfo,ce=(await lF(n,v.provisionFileUrl)).urlList,Be=w.profileInfo.id;if(ce&&ce.length>0){let st=await $S(t,i),at=st.profilePath;if(!await dF(ce,at))throw await ob(n,Be),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await ob(n,Be),Sr.existsSync(st.certPath)&&Sr.existsSync(at)&&Sr.existsSync(st.p12Path)){let rl=Sr.readFileSync(st.certPath,"utf8"),il=Sr.readFileSync(at,"utf8");return uF(il,rl,st.p12Path,c,l)||cF(at),at}}throw new Error(E.ADD_PROFILE_FAIL)}function rF(n,e){let t=n?`${n}_`:"";return`${iF(`${t}${e}_${e}`)}`}function iF(n){return eF("sha256").update(n).digest("hex").substring(0,16)}async function oF(n,e,t,r,i,o,s){sF(r);let a=$p(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await O.postAllowFailure(e,{headers:a,params:c});if(!l)throw m("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw jp(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw m(`add provision fail: ${l.data}`),aF(l.data,o),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function jp(n,e,t){return n===bt.FORBIDDEN?e===be.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===bt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(be.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function sF(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!He.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function aF(n,e){if(n.includes(be.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(be.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function ob(n,e){if(!e||e.trim().length===0)return;let t=`${ie.BASE_URL}${ie.PROVISION_DELETE_PATH}?id=${e}`,r=await O.deleteAllowFailure(t,{headers:$p(n)});if(r.statusCode!==200)throw jp(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&m(`delete provision failed: ${r.data}`)}function cF(...n){for(let e of n)try{Sr.existsSync(e)&&Sr.unlinkSync(e)}catch(t){m(`delete local sign file error: ${t.message}`)}}async function lF(n,e){let t=`${ie.BASE_URL}${ie.CERT_DOWNLOAD_URL_PATH}`,r=$p(n),i={sourceUrls:e},o=await O.postAllowFailure(t,{headers:r,params:i});if(!o)throw m("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw jp(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw m("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function dF(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Qo(t,e),!0}function uF(n,e,t,r,i){return pF(n,e),r=r||He.TARGET_FRIENDLY_NAME,i=i||"",mF(e,t,r,i),!0}function pF(n,e){if(e.lastIndexOf(He.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(He.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function mF(n,e,t,r){let i=n.matchAll(He.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=fF(l),g=new Date(d.validFrom),w=new Date(d.validTo);if(s<g||s>w){let v=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${v}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!hF(e,t,r,o))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function fF(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Fp(t);let r=sb.from(t,"base64");return new Fp(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function gF(n){if(n.cert){let e=br.pki.publicKeyToPem(n.cert.publicKey);return tF(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=br.asn1.toDer(n.asn1).getBytes(),t=sb.from(e,"binary");return new Fp(t).publicKey.export({type:"spki",format:"der"})}catch(e){return m(`Failed to parse cert from asn1: ${e}`),null}return null}function hF(n,e,t,r){try{let i=nF(n),o=br.asn1.fromDer(br.util.createBuffer(i)),c=br.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:br.pki.oids.certBag})[br.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=gF(l);if(!g)continue;if(r.some(v=>{let k=v.publicKey.export({type:"spki",format:"der"});return g.equals(k)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return m(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function $p(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var lb="https://developer.huawei.com",yF={"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"},wF="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function vF(n){let e=yF[n];return e?`${lb}${e}`:void 0}function SF(){return`${lb}${wF}`}var bF={"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 cb(n,e){return(bF[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function EF(n){return Array.from(n).join(", ")}function db(n,e){if(n.size===0)return;let t=Wn.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=vF(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;o.add(`${w} (${g.permissionHelpUrlKey})`)}let s=SF(),a=cb("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=cb("acl.permissions.warn",[EF(i),l,c]);console.log(d)}var Zc=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=K.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(oe.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:oe.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import PF from"fs";import ub from"path";var Qc=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(oe.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",i=ub.join(t,"default","openharmony","toolchains","lib",r);if(!PF.existsSync(i)){let o=ub.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${o} exists.`)}return{passed:!0,message:""}}};var el=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await Te.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await Te.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(oe.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(oe.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(oe.TEAM_INFO_FAILED);try{if((await yn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(oe.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(oe.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(oe.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(oe.REALNAME_REQUIRED)):{passed:!0,message:""}:e(oe.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await yn();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return m(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(oe.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(oe.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function CF(n){try{let{teamList:e}=await yn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function IF(n){let e=await Te.getUserInfo(),t=await Te.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await CF(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Xc(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var tl=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t,r=!1){if(r)return m("[EnvCheck] Scenario 4 Device check: --udid provided, skipping device detection"),{passed:!0,message:""};try{let i=await IF(t);return i.length>0?(m(`[EnvCheck] Scenario 4 Device check: ${i.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""}):(m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc"),(await ae.from(this.toolProvider).listDevices()).length>0?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(oe.DEVICE_MISSING)))}catch(i){return m(`[EnvCheck] Scenario 4 Device check failed: ${i.message}`),e(oe.DEVICE_DETECT_FAILED)}}};var nl=class{projectChecker=new Zc;toolchainChecker=null;authChecker=new el;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkRealname(t),()=>this.authChecker.checkTeamInfo(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await A.new();return this.toolchainChecker=new Qc(e),this.deviceChecker=new tl(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(oe.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId,e.hasManualDevices??!1))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function RF(n){if(Up.existsSync(n)){let e=Up.readFileSync(n,"utf-8");return TF.parse(e)}return{app:{signingConfigs:[],products:[]}}}function kF(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function xF(n){if(n.keyPwd===n.storePassword){let r=await Bn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Bn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Bn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function NF(n,e,t){let r=pb.join(n,"build-profile.json5"),i=RF(r);kF(i);let o=t??"default",{keyPassword:s,storePassword:a}=await xF(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:Et.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(g=>g.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),Up.writeFileSync(r,JSON.stringify(i,null,2),"utf-8")}async function LF(n){let e=await Te.getUserInfo(),t=await Te.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 OF(n){let e=n.product||"default",t=gp(n.udid??[]);await new nl().preflight({productName:e,teamId:n.teamId,hasManualDevices:t.length>0}),console.log("Executing signature generate command");let i=await LF(n),o=await A.new(),{shouldRegenerate:s}=await ns.shouldRegenerate({force:n.force??!1,teamId:i.teamId,productName:n.product,manualUdids:t.map(a=>a.udid)},o);if(!s){console.log(Hp("Signature generation completed successfully."));return}await _F(n,i,o,t),console.log(Hp("Signature generation completed successfully."))}function MF(n){console.log(`Profile covers ${n.length} device(s):`);for(let e of n){let t=e.source==="manual"&&e.typeInferred?"manual, type inferred":e.source;console.log(` ${e.udid} ${e.type.padEnd(12)} (${t})`)}}async function _F(n,e,t,r){let i=await Ap(e,n.product),o=FF(n,e,i,t),{allDeviceIds:s,devices:a}=await nb(e,t.hdcPath,r);o.allDeviceIds=s,await ab(e,o),MF(a);let c=K.discover(process.cwd()).rootDir;await NF(c,i,n.product??"default"),console.log(Hp(`Signing config written to ${pb.join(c,"build-profile.json5")}`))}function FF(n,e,t,r){let i=process.cwd(),o=K.discover(i),s=Jc(o,r);return db(s,o),{productName:n.product||"default",bundleName:o.getBundleName(),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var mb=new DF("signature").description("Generate application signature.");mb.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").option("--udid <udid...>",'Add device UDID(s) that are not connected. Repeatable or comma-separated; append ":<type>" to declare phone|wearable|liteWearable|tv (default: phone).').action(async n=>{let e={event:D.CommandExecuted,args:["signature","generate",...n.force?["--force"]:[],...n.teamId?["--team-id"]:[],...n.product?["--product"]:[],...n.udid?["--udid",String(hp(n.udid))]:[]]},t=Date.now(),r=!0,i=null;try{await OF(n)}catch(o){r=!1,i=W(o),console.error(AF(o.message)),process.exitCode=1}finally{let o={duration_ms:Date.now()-t,success:r,error_code:i};await I.track(e,o)}});var fb=mb;if(!Ze())try{I.init(Wp.join(tn(),"TraceLogData")),I.startScheduler()}catch(n){h.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Ze())try{let n=await A.new();I.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?I.setCltVersion(e):I.setStudioVersion(e))}catch(n){h.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();de.name("devecocli").description(`HarmonyOS application development command line tool
1433
1433
 
1434
- Privacy: ${Ei.PRIVACY_URL}`).version("1.3.12-Test.1");de.addCommand(Mm);de.addCommand(pf);de.addCommand(gf);de.addCommand(kf);de.addCommand(Ah);de.addCommand(Qh);de.addCommand(rg);de.addCommand(fg);de.addCommand(Pg);de.addCommand(Wg);de.addCommand(ev);de.addCommand(JS);de.addCommand(cS);de.addCommand(Rv);b()||de.addCommand(ih);var Ip=process.argv.slice(2);Ip.length>=2&&Ip[Ip.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var yF=new Set(["update","auth"]);de.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==de;)t=t.parent;yF.has(t.name())||await A.checkVersion()});de.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{gl(Dp.join(Zt(),"TraceLogData"))}catch(n){g.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(gF(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1434
+ Privacy: ${Ii.PRIVACY_URL}`).version("1.3.13-23.1");de.addCommand(Zm);de.addCommand(Rf);de.addCommand(Lf);de.addCommand(qf);de.addCommand(Vg);de.addCommand(hh);de.addCommand(Sh);de.addCommand(xh);de.addCommand(Hh);de.addCommand(sy);de.addCommand(vv);de.addCommand(fb);de.addCommand(AS);de.addCommand(Yv);b()||de.addCommand(bg);var Bp=process.argv.slice(2);Bp.length>=2&&Bp[Bp.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var $F=new Set(["update","auth"]);de.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==de;)t=t.parent;$F.has(t.name())||await A.checkVersion()});de.parseAsync(process.argv).finally(()=>{I.stopScheduler();try{Pl(Wp.join(tn(),"TraceLogData"))}catch(n){h.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(jF(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});