@deveco-test/deveco-cli 0.8.0 → 1.2.0

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,43 +1,43 @@
1
1
  #!/usr/bin/env node
2
- import{bootstrap as Qu}from"global-agent";import{program as U}from"commander";import{red as ep}from"colorette";import{Command as ia}from"commander";import{green as ui,red as Kn,yellow as pi}from"colorette";import $ from"fs";import*as _ from"path";import Ae from"json5";import*as Yn from"fs";import*as L from"path";function w(r){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${r}`)}var E=class r{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let n=e.trim();if(!/^\d+$/.test(n))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(n,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
- `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported)`);let o=i[1];if((i[2]??"s")==="s")return r.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} minute value supports at most one decimal place, 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,n,i=new Date){if(!t&&!n)return e;let[o,s]=r.resolveTimeBounds(t,n,i),a=e.split(/\r?\n/),c=[],d=!1;for(let u of a){let b=r.extractTimestampFromLogLine(u,i);b&&(d=r.isWithinBounds(b,o,s)),d&&c.push(u)}return c.join(`
4
- `)}static resolveTimeBounds(e,t,n){let i=e?new Date(n.getTime()-e*1e3):null,o=t?new Date(n.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,n]:o?[null,o]:[null,null]}static isWithinBounds(e,t,n){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=n?Math.floor(n.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let n=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!n)return null;let i=t.getFullYear(),o=Number.parseInt(n[1],10)-1,s=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),c=Number.parseInt(n[4],10),d=Number.parseInt(n[5],10),u=n[6]??"0",b=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),k=new Date(i,o,s,a,c,d,b);return k.getTime()>t.getTime()+1440*60*1e3&&k.setFullYear(i-1),k}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(n=>{let i=n.charCodeAt(0);return i<=r.ASCII_CONTROL_MAX||i===r.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let n=`'${e.replace(/'/g,"'\\''")}'`;return w(`quotePosixShellArg: ${e} -> ${n}`),n}static assertCrashFilename(e){if(!/^\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(L.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=L.resolve(L.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=L.normalize(e),i=L.relative(n,t);if(i.split(L.sep)[0]===".."||L.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||L.isAbsolute(e)}static isPathContained(e,t){let n=L.resolve(t,e),i=L.relative(t,n);return r.isPathEscaping(i)?{contained:!1,reason:`Path escapes project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(L.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let n=r.isPathContained(e,t);if(!n.contained)return n;let i;try{i=Yn.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=L.resolve(i,e),s;try{s=Yn.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return r.isPathContained(s,i)}};var ke=class r{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let n=r.tryLoadProjectProfile(t);if(n)return new r(t,n);let i=_.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found)")}static tryLoadProjectProfile(e){let t=_.join(e,"build-profile.json5");if(!$.existsSync(t))return null;try{let n=$.readFileSync(t,"utf-8"),i=Ae.parse(n);return i.app?i:null}catch(n){return console.error(`Error parsing ${t}:`,n),null}}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project build-profile.json5.`);let n=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=_.join(n,"src","main","module.json5");if(!$.existsSync(i))return"entry";try{let o=$.readFileSync(i,"utf-8");return Ae.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project build-profile.json5.`);let n=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=_.join(n,"build-profile.json5");if(!$.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}`);let o=$.readFileSync(i,"utf-8");return Ae.parse(o)}getBundleName(){let e=_.join(this.rootDir,"AppScope","app.json5");if($.existsSync(e))try{let t=$.readFileSync(e,"utf-8"),n=Ae.parse(t);if(n?.app?.bundleName)return n.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5")}getMainAbility(e,t){if(t)return t;let n=this.profile.modules.find(s=>s.name===e);if(!n)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,n.srcPath),o=_.join(i,"src","main","module.json5");if(!$.existsSync(o))return"EntryAbility";try{let s=$.readFileSync(o,"utf-8"),c=Ae.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let d=c.find(u=>u.name==="EntryAbility");return d?d.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 Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(n=>n.name===e)){let n=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${n}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let n=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=_.join(n,"oh-package.json5");if(!$.existsSync(i))return[];let o=[];try{let s=$.readFileSync(i,"utf-8"),c=Ae.parse(s)?.dependencies||{};for(let d of Object.values(c)){if(typeof d!="string")continue;let u=d;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let k=_.join(t.srcPath,u),le=E.resolvePathWithinRoot(this.rootDir,k),Fe=this.profile.modules.find($e=>_.resolve(this.rootDir,$e.srcPath)===le);Fe&&o.push(Fe.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],n=[],i=new Set;for(n.push(e),i.add(e);n.length>0;){let o=n.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(n.push(c),i.add(c))}return t}findArtifactPath(e,t,n,i="default"){this.validateProduct(i);let o=this.profile.modules.find(le=>le.name===e);if(!o)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",d=this.buildOutputPath(o.srcPath,i,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!$.existsSync(d))throw new Error(`Build metadata not found for module '${e}' at ${d}. Please build the project first.`);let{packageName:u,isSigned:b}=this.parseOutputMetadata(d,c);if(!n&&!b)throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let k=this.buildOutputPath(o.srcPath,i,["outputs",t,u]);if(!$.existsSync(k))throw new Error(`Generated package file does not exist: ${k}`);return k}buildOutputPath(e,t,n){let i=E.resolvePathWithinRoot(this.rootDir,e),o=_.resolve(i,"build",t,...n);return E.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let n=$.readFileSync(e,"utf-8"),i=Ae.parse(n),o,s=!1;if(Array.isArray(i)){let a=i[0];a&&(o=a[t],s=a.isSigned===!0)}else i&&typeof i=="object"&&(o=i[t],s=i.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(o),{packageName:o,isSigned:s}}validatePackageName(e){let t=_.basename(e);if(t!==e)throw new Error(`Invalid package name: contains path characters. Expected filename only, got '${e}'`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name: must be a .hap or .hsp file. Got '${t}'`)}};import{execFileSync as Gn}from"child_process";import x,{existsSync as oi}from"fs";import*as P from"path";import*as q from"os";import Ys from"regedit";import{join as si}from"path";import{red as Gs}from"colorette";var ai="https://developer.huawei.com/consumer/cn/download/",ci="6.1.0",Jn=r=>new Promise((e,t)=>{Ys.list(r,(n,i)=>{n?t(n):e(i)})}),O=class r{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){r._verifiedPaths.has(e)||(r.verifySignature(e),r._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return r.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return r.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return r.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return r.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&r.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,n,i,o,s,a,c,d){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=n,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=d}static async checkVersion(){await r.findDevEcoStudio()}static async new(){let e=await r.findDevEcoStudio(),{nodePath:t,ohpmJsPath:n,hvigorJsPath:i,javaPath:o,sdkPath:s,hdcPath:a,emulatorPath:c}=r.resolveTools(e),d=r.getEmulatorExe(e);return new r(e,t,n,i,o,s,a,c,d??void 0)}static _cachedInstallRoot;static async findDevEcoStudio(){if(r._cachedInstallRoot!==void 0)return w(`[ToolProvider] findDevEcoStudio: cache hit -> ${r._cachedInstallRoot}`),r._cachedInstallRoot;let e=q.platform(),t=e==="win32"?await r.collectCandidatesWindows():e==="darwin"?r.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection")})();return r._cachedInstallRoot=r.pickLatestByProductInfo(t),r._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],n=(i,o)=>{if(!r.isExistingDirectory(i))return;let s=P.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),w(`[ToolProvider] Found via ${o}: ${i}`))};if(await r.addFromUninstallKey(n),await r.addFromWow64Key(n),r.addFromDefaultWindowsPath(n),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations");return t}static async addFromUninstallKey(e){try{let t="HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\DevEco Studio",i=(await Jn([t]))[t]?.values?.InstallLocation?.value;e(i,"Uninstall registry key")}catch{}}static async addFromWow64Key(e){try{let t="HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio",i=(await Jn([t]))[t]?.keys??[];if(i.length===0)return;let o=i.map(a=>`${t}\\${a}`),s=await Jn(o);for(let a of o){let c=s[a]?.values?.[""]?.value;e(c,`WOW6432Node subkey ${a}`)}}catch{}}static addFromDefaultWindowsPath(e){let t=P.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=q.homedir(),t=[P.join(e,"Applications"),"/Applications"],n=[],i=new Set;for(let o of t){if(!x.existsSync(o))continue;let s;try{s=x.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let d=P.join(o,a);r.isExistingDirectory(d)&&(i.has(d)||(i.add(d),n.push(d),w(`[ToolProvider] Found macOS candidate: ${d}`)))}}if(n.length===0)throw new Error("DevEco Studio not found in /Applications or ~/Applications");return n}static productInfoPath(e){return q.platform()==="darwin"?P.join(e,"Contents","product-info.json"):P.join(e,"product-info.json")}static macInfoPlistPath(e){return P.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!x.existsSync(e)){w(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let n=Gn("defaults",["read",e,t],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(n.length>0&&n!=="(null)")return n}catch{w(`[ToolProvider] defaults read failed for ${e} key ${t}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(n=>/^\d+$/.test(n))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let n=r.compactPrefixFromShortVersion(e),i=r.extractCompactBuildCode(t);if(n===void 0||i===void 0)return;if(!i.startsWith(n)){w(`[ToolProvider] CFBundleVersion suffix ${i} does not match short-version prefix ${n} (${e})`);return}let o=i.slice(n.length);if(!(o.length===0||!/^\d+$/.test(o)))return o}static readMacFourthSegmentFromPlist(e,t){let n=r.readMacInfoPlistKey(e,"CFBundleVersion");if(n!==void 0){let s=r.extractFourthSegmentMatchingShortVersion(t,n);if(s!==void 0)return s}let i=r.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(i===void 0)return;let o=i.match(/DS-[\d.]+/);if(o!==null)return r.extractFourthSegmentMatchingShortVersion(t,o[0])}static parseMacInfoPlistVersion(e){let t=r.macInfoPlistPath(e),n=r.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(n!==void 0){let i=r.readMacFourthSegmentFromPlist(t,n);return i!==void 0?`${n}.${i}`:n}return r.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(q.platform()==="darwin"){let n=r.parseMacInfoPlistVersion(e);if(n!==void 0)return n}let t=r.productInfoPath(e);if(!x.existsSync(t)){w(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(x.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){w(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch{w(`[ToolProvider] Failed to parse product-info.json at: ${t}`);return}}static compareVersion(e,t){let n=e.split(".").map(s=>parseInt(s,10)||0),i=t.split(".").map(s=>parseInt(s,10)||0),o=Math.max(n.length,i.length);for(let s=0;s<o;s++){let a=(n[s]??0)-(i[s]??0);if(a!==0)return a}return 0}static pickLatestByProductInfo(e){let t=r.selectHighestVersion(e);return r.assertMinVersion(t.installRoot,t.version),w(`[ToolProvider] Selected DevEco Studio ${t.version} at ${t.installRoot}`),t.installRoot}static selectHighestVersion(e){let t=[];for(let n of e){let i=r.parseProductInfoVersion(n);i!==void 0?(t.push({installRoot:n,version:i}),w(`[ToolProvider] ${n} => version ${i}`)):w(`[ToolProvider] Skipping ${n}: could not read version (Info.plist / product-info.json)`)}if(t.length===0){let n=e.join(`
5
- `),i=q.platform()==="darwin"?"Contents/Info.plist (CFBundleShortVersionString / CFBundleVersion) and Contents/product-info.json":"product-info.json";throw new Error(`Failed to determine DevEco Studio version from ${i}.
2
+ import{bootstrap as hp}from"global-agent";import{program as B}from"commander";import{red as fp}from"colorette";import{Command as ya}from"commander";import{green as vi,red as rr,yellow as wi}from"colorette";import $ from"fs";import*as _ from"path";import Ae from"json5";import*as Qn from"fs";import*as L from"path";function w(r){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${r}`)}var C=class r{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let n=e.trim();if(!/^\d+$/.test(n))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(n,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
3
+ `)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return r.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static 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,n,i=new Date){if(!t&&!n)return e;let[o,s]=r.resolveTimeBounds(t,n,i),a=e.split(/\r?\n/),c=[],d=!1;for(let u of a){let v=r.extractTimestampFromLogLine(u,i);v&&(d=r.isWithinBounds(v,o,s)),d&&c.push(u)}return c.join(`
4
+ `)}static resolveTimeBounds(e,t,n){let i=e?new Date(n.getTime()-e*1e3):null,o=t?new Date(n.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,n]:o?[null,o]:[null,null]}static isWithinBounds(e,t,n){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=n?Math.floor(n.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let n=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!n)return null;let i=t.getFullYear(),o=Number.parseInt(n[1],10)-1,s=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),c=Number.parseInt(n[4],10),d=Number.parseInt(n[5],10),u=n[6]??"0",v=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),D=new Date(i,o,s,a,c,d,v);return D.getTime()>t.getTime()+1440*60*1e3&&D.setFullYear(i-1),D}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(n=>{let i=n.charCodeAt(0);return i<=r.ASCII_CONTROL_MAX||i===r.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let n=`'${e.replace(/'/g,"'\\''")}'`;return w(`quotePosixShellArg: ${e} -> ${n}`),n}static assertCrashFilename(e){if(!/^\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(L.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=L.resolve(L.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=L.normalize(e),i=L.relative(n,t);if(i.split(L.sep)[0]===".."||L.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||L.isAbsolute(e)}static isPathContained(e,t){let n=L.resolve(t,e),i=L.relative(t,n);return r.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(L.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let n=r.isPathContained(e,t);if(!n.contained)return n;let i;try{i=Qn.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=L.resolve(i,e),s;try{s=Qn.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return r.isPathContained(s,i)}};var ke=class r{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let n=r.tryLoadProjectProfile(t);if(n)return new r(t,n);let i=_.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=_.join(e,"build-profile.json5");if(!$.existsSync(t))return null;try{let n=$.readFileSync(t,"utf-8"),i=Ae.parse(n);return i.app?i:null}catch(n){return console.error(`Error parsing ${t}:`,n),null}}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let n=C.resolvePathWithinRoot(this.rootDir,t.srcPath),i=_.join(n,"src","main","module.json5");if(!$.existsSync(i))return"entry";try{let o=$.readFileSync(i,"utf-8");return Ae.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let n=C.resolvePathWithinRoot(this.rootDir,t.srcPath),i=_.join(n,"build-profile.json5");if(!$.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=$.readFileSync(i,"utf-8");return Ae.parse(o)}getBundleName(){let e=_.join(this.rootDir,"AppScope","app.json5");if($.existsSync(e))try{let t=$.readFileSync(e,"utf-8"),n=Ae.parse(t);if(n?.app?.bundleName)return n.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}getMainAbility(e,t){if(t)return t;let n=this.profile.modules.find(s=>s.name===e);if(!n)return"EntryAbility";let i=C.resolvePathWithinRoot(this.rootDir,n.srcPath),o=_.join(i,"src","main","module.json5");if(!$.existsSync(o))return"EntryAbility";try{let s=$.readFileSync(o,"utf-8"),c=Ae.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let d=c.find(u=>u.name==="EntryAbility");return d?d.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 Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(n=>n.name===e)){let n=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${n}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let n=C.resolvePathWithinRoot(this.rootDir,t.srcPath),i=_.join(n,"oh-package.json5");if(!$.existsSync(i))return[];let o=[];try{let s=$.readFileSync(i,"utf-8"),c=Ae.parse(s)?.dependencies||{};for(let d of Object.values(c)){if(typeof d!="string")continue;let u=d;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let D=_.join(t.srcPath,u),le=C.resolvePathWithinRoot(this.rootDir,D),Fe=this.profile.modules.find($e=>_.resolve(this.rootDir,$e.srcPath)===le);Fe&&o.push(Fe.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],n=[],i=new Set;for(n.push(e),i.add(e);n.length>0;){let o=n.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(n.push(c),i.add(c))}return t}findArtifactPath(e,t,n,i="default"){this.validateProduct(i);let o=this.profile.modules.find(le=>le.name===e);if(!o)throw new Error(`Module '${e}' not found`);let a=this.getModuleType(e)==="shared",c=a?"hspName":"hapName",d=this.buildOutputPath(o.srcPath,i,["intermediates",a?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!$.existsSync(d))throw new Error(`Build metadata not found for module '${e}' at ${d}. Build the project first.`);let{packageName:u,isSigned:v}=this.parseOutputMetadata(d,c);if(!n&&!v)throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let D=this.buildOutputPath(o.srcPath,i,["outputs",t,u]);if(!$.existsSync(D))throw new Error(`Generated package file not found in ${D}.`);return D}buildOutputPath(e,t,n){let i=C.resolvePathWithinRoot(this.rootDir,e),o=_.resolve(i,"build",t,...n);return C.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let n=$.readFileSync(e,"utf-8"),i=Ae.parse(n),o,s=!1;if(Array.isArray(i)){let a=i[0];a&&(o=a[t],s=a.isSigned===!0)}else i&&typeof i=="object"&&(o=i[t],s=i.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(o),{packageName:o,isSigned:s}}validatePackageName(e){let t=_.basename(e);if(t!==e)throw new Error(`Invalid traversal name: '${e}'. It must contain path characters.`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name '${t}'.It must be a .hap or .hsp file.`)}};import{execFileSync as er}from"child_process";import R,{existsSync as pi}from"fs";import*as E from"path";import*as Y from"os";import aa from"regedit";import{join as hi}from"path";import{red as ca}from"colorette";var fi="https://developer.huawei.com/consumer/cn/download/",mi="6.1.0",_t=r=>new Promise((e,t)=>{aa.list(r,(n,i)=>{n?t(n):e(i)})}),O=class r{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){r._verifiedPaths.has(e)||(r.verifySignature(e),r._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return r.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return r.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return r.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return r.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&r.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,n,i,o,s,a,c,d){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=n,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=d}static async checkVersion(){await r.findDevEcoStudio()}static async new(){let e=await r.findDevEcoStudio(),{nodePath:t,ohpmJsPath:n,hvigorJsPath:i,javaPath:o,sdkPath:s,hdcPath:a,emulatorPath:c}=r.resolveTools(e),d=r.getEmulatorExe(e);return new r(e,t,n,i,o,s,a,c,d??void 0)}static _cachedInstallRoot;static async findDevEcoStudio(){if(r._cachedInstallRoot!==void 0)return w(`[ToolProvider] findDevEcoStudio: cache hit -> ${r._cachedInstallRoot}`),r._cachedInstallRoot;let e=Y.platform(),t=e==="win32"?await r.collectCandidatesWindows():e==="darwin"?r.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return r._cachedInstallRoot=r.pickLatestByProductInfo(t),r._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],n=(i,o)=>{if(!r.isExistingDirectory(i))return;let s=E.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),w(`[ToolProvider] Found via ${o}: ${i}`))};if(await r.addFromUninstallKey(n),await r.addFromHuaweiStudioKeys(n),r.addFromDefaultWindowsPath(n),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of r.UNINSTALL_REGISTRY_PARENTS)try{let o=((await _t([t]))[t]?.keys??[]).filter(r.isDevEcoStudioUninstallSubkey);if(o.length===0)continue;let s=o.map(c=>`${t}\\${c}`),a=await _t(s);for(let c of s){let d=a[c]?.values?.InstallLocation?.value;e(d,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,n){try{let o=(await _t([t]))[t]?.keys??[];if(o.length===0)return;let s=o.map(c=>`${t}\\${c}`),a=await _t(s);for(let c of s){let d=a[c]?.values?.[""]?.value;e(d,`${n} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of r.HUAWEI_STUDIO_REGISTRY_KEYS){let n=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await r.addFromHuaweiStudioRegistryKey(e,t,n)}}static addFromDefaultWindowsPath(e){let t=E.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=Y.homedir(),t=[E.join(e,"Applications"),"/Applications"],n=[],i=new Set;for(let o of t){if(!R.existsSync(o))continue;let s;try{s=R.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let d=E.join(o,a);r.isExistingDirectory(d)&&(i.has(d)||(i.add(d),n.push(d),w(`[ToolProvider] Found macOS candidate: ${d}`)))}}if(n.length===0)throw new Error("DevEco Studio not found in /Applications or ~/Applications.");return n}static productInfoPath(e){return Y.platform()==="darwin"?E.join(e,"Contents","product-info.json"):E.join(e,"product-info.json")}static macInfoPlistPath(e){return E.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!R.existsSync(e)){w(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let n=er("defaults",["read",e,t],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(n.length>0&&n!=="(null)")return n}catch{w(`[ToolProvider] defaults read failed for ${e} key ${t}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(n=>/^\d+$/.test(n))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let n=r.compactPrefixFromShortVersion(e),i=r.extractCompactBuildCode(t);if(n===void 0||i===void 0)return;if(!i.startsWith(n)){w(`[ToolProvider] CFBundleVersion suffix ${i} does not match short-version prefix ${n} (${e})`);return}let o=i.slice(n.length);if(!(o.length===0||!/^\d+$/.test(o)))return o}static readMacFourthSegmentFromPlist(e,t){let n=r.readMacInfoPlistKey(e,"CFBundleVersion");if(n!==void 0){let s=r.extractFourthSegmentMatchingShortVersion(t,n);if(s!==void 0)return s}let i=r.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(i===void 0)return;let o=i.match(/DS-[\d.]+/);if(o!==null)return r.extractFourthSegmentMatchingShortVersion(t,o[0])}static parseMacInfoPlistVersion(e){let t=r.macInfoPlistPath(e),n=r.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(n!==void 0){let i=r.readMacFourthSegmentFromPlist(t,n);return i!==void 0?`${n}.${i}`:n}return r.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(Y.platform()==="darwin"){let n=r.parseMacInfoPlistVersion(e);if(n!==void 0)return n}let t=r.productInfoPath(e);if(!R.existsSync(t)){w(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(R.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){w(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch{w(`[ToolProvider] Failed to parse product-info.json at: ${t}`);return}}static compareVersion(e,t){let n=e.split(".").map(s=>parseInt(s,10)||0),i=t.split(".").map(s=>parseInt(s,10)||0),o=Math.max(n.length,i.length);for(let s=0;s<o;s++){let a=(n[s]??0)-(i[s]??0);if(a!==0)return a}return 0}static pickLatestByProductInfo(e){let t=r.selectHighestVersion(e);return r.assertMinVersion(t.installRoot,t.version),w(`[ToolProvider] Selected DevEco Studio ${t.version} at ${t.installRoot}`),t.installRoot}static selectHighestVersion(e){let t=[];for(let n of e){let i=r.parseProductInfoVersion(n);i!==void 0?(t.push({installRoot:n,version:i}),w(`[ToolProvider] ${n} => version ${i}`)):w(`[ToolProvider] Skipping ${n}: could not read version (Info.plist / product-info.json).`)}if(t.length===0){let n=e.join(`
5
+ `),i=Y.platform()==="darwin"?"Contents/Info.plist (CFBundleShortVersionString / CFBundleVersion) and Contents/product-info.json":"product-info.json";throw new Error(`Failed to determine DevEco Studio version from ${i}.
6
6
  Searched locations:
7
7
  ${n}
8
8
  Please reinstall DevEco Studio or download the latest version from:
9
- `+ai)}return t.reduce((n,i)=>r.compareVersion(i.version,n.version)>0?i:n)}static assertMinVersion(e,t){r.compareVersion(t,ci)>=0||(w(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(Gs(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${ci}. Please upgrade to the latest version before using deveco-cli:`)+`
10
- `+ai),process.exit(1))}static isExistingDirectory(e){return!!e&&x.existsSync(e)&&x.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=P.join(e,"tools");return{nodePath:P.join(t,"node","node.exe"),ohpmJsPath:P.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(t,"hvigor","bin","hvigorw.js"),javaPath:P.join(e,"jbr","bin","java.exe"),sdkPath:P.join(e,"sdk")}}static resolveMacTools(e){let t=P.join(e,"Contents","tools");return{nodePath:P.join(t,"node","bin","node"),ohpmJsPath:P.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:P.join(t,"hvigor","bin","hvigorw.js"),javaPath:P.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:P.join(e,"Contents","sdk")}}static resolveTools(e){let t=q.platform(),n=t==="win32"?r.resolveWindowsTools(e):t==="darwin"?r.resolveMacTools(e):(()=>{throw new Error("Linux is not fully supported yet")})();r.verifyTools(n.nodePath,n.ohpmJsPath,n.hvigorJsPath,n.javaPath);let i=r.resolveHdcPath(n.sdkPath,t),o=r.resolveEmulatorPath(e,t);return{...n,hdcPath:i,emulatorPath:o}}static resolveHdcPath(e,t){let n=t==="win32"?".exe":"",i=[P.join(e,"default","openharmony","toolchains",`hdc${n}`),P.join(e,"toolchains",`hdc${n}`)];for(let o of i)if(x.existsSync(o))return o;throw new Error(`hdc executable not found. Searched in:
9
+ `+fi)}return t.reduce((n,i)=>r.compareVersion(i.version,n.version)>0?i:n)}static assertMinVersion(e,t){r.compareVersion(t,mi)>=0||(w(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(ca(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${mi}. Upgrade to the latest version before using deveco-cli:`)+`
10
+ `+fi),process.exit(1))}static isExistingDirectory(e){return!!e&&R.existsSync(e)&&R.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=E.join(e,"tools");return{nodePath:E.join(t,"node","node.exe"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"jbr","bin","java.exe"),sdkPath:E.join(e,"sdk")}}static resolveMacTools(e){let t=E.join(e,"Contents","tools");return{nodePath:E.join(t,"node","bin","node"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:E.join(e,"Contents","sdk")}}static resolveTools(e){let t=Y.platform(),n=t==="win32"?r.resolveWindowsTools(e):t==="darwin"?r.resolveMacTools(e):(()=>{throw new Error("Linux is not fully supported yet.")})();r.verifyTools(n.nodePath,n.ohpmJsPath,n.hvigorJsPath,n.javaPath);let i=r.resolveHdcPath(n.sdkPath,t),o=r.resolveEmulatorPath(e,t);return{...n,hdcPath:i,emulatorPath:o}}static resolveHdcPath(e,t){let n=t==="win32"?".exe":"",i=[E.join(e,"default","openharmony","toolchains",`hdc${n}`),E.join(e,"toolchains",`hdc${n}`)];for(let o of i)if(R.existsSync(o))return o;throw new Error(`hdc executable not found. Searched in:
11
11
  ${i.join(`
12
- `)}`)}static resolveEmulatorPath(e,t){let n;if(t==="win32")n=P.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=P.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!x.existsSync(n))throw new Error(`Emulator executable not found at: ${n}`);return n}static verifyTools(e,t,n,i){if(!x.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!x.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!x.existsSync(n))throw new Error(`hvigor js file not found at: ${n}`);if(!x.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=q.platform(),n;if(t==="win32")n=si(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=si(e,"Contents","tools","emulator","Emulator");else return;return oi(n)?n:void 0}static isValidApiLevel(e,t){let n=t??23;return Number.isInteger(e)&&e>=17&&e<=n}static parseApiLevelFromFile(e){if(x.existsSync(e))try{let t=x.readFileSync(e,"utf-8"),n=JSON.parse(t),i=n?.apiVersion??n?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=P.join(e,"default","sdk-pkg.json");return r.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[P.join(e,"default","openharmony","toolchains","oh-uni-package.json"),P.join(e,"default","openharmony","native","oh-uni-package.json"),P.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let n of t){let i=r.parseApiLevelFromFile(n);if(i!==void 0)return i}}getMaxApiLevel(){let e=r.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=r.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(r._powerShellPath)return r._powerShellPath;if(q.platform()!=="win32")return r._powerShellPath="",r._powerShellPath;let e=P.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return oi(e)?(w(`[ToolProvider] Found PowerShell at: ${e}`),r._powerShellPath=e,e):(r._powerShellPath="",r._powerShellPath)}static verifySignature(e){if(!x.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=q.platform();if(r.isExecutableFile(e,t)){if(t==="win32"){if(!r.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!r.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return P.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return x.accessSync(e,x.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=x.mkdtempSync(P.join(q.tmpdir(),"deveco-verify-")),t=P.join(e,"Verify-Signature.ps1");return x.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=r.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let{tmpDir:n,scriptPath:i}=r.createSignatureScript();try{let o=Gn(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(o);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(o){return w(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{x.rmSync(n,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return Gn("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Js}from"execa";import*as Ht from"path";var Te=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Ht.dirname(e.javaPath)}${Ht.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async sync(e,t){let n=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(n)}async buildProduct(e,t){let n=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(n)}async buildModules(e,t,n,i){let o=[...Array.from(i),"--mode","module","-p",`module=${n.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async runHvigor(e){let t=this.toolProvider.nodePath,n=[this.toolProvider.hvigorJsPath,...e];w(`Executing: ${t} ${n.join(" ")}`),await Js(t,n,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Ks}from"execa";var _e=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];w(`Executing: ${e} ${t.join(" ")}`),await Ks(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Zs}from"fs/promises";import{dirname as Xs,resolve as Qs}from"path";import{execa as ea}from"execa";import li from"proper-lockfile";function di(r){return Qs(r,".hvigor",".build-lock")}function ta(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function na(r){let e=Xs(di(r));if(await Zs(e,{recursive:!0}),process.platform==="win32")try{await ea("attrib",["+h",e])}catch{}}async function ra(r,e){let t=new AbortController,n=ta(e);await na(r);let i={lockfilePath:di(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await li(r,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return n(),{release:await li(r,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function ut(r,e,t){let{release:n,signal:i}=await ra(r,t);try{return await e(i)}finally{await n()}}function oa(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode&&!r.profile.app.buildModeSet.some(n=>n.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function sa(r,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=r.profile.modules,o=i.filter(s=>r.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let n=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";n.add(`${s}@${a}`)}return Array.from(n)}function Zn(r,e){let t=new Set;for(let n of e){let i=n.indexOf("@"),o=i!==-1?n.substring(0,i):n,s=r.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function pt(r,e){let t=e,n=`${r} failed`;console.error(Kn(n));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(n,{cause:e})}async function Xn(r,e,t,n,i){console.log(`
13
- [1/3] Running ohpm install...`);try{await r.installAll()}catch(o){pt("ohpm install",o)}console.log(`
14
- [2/3] Running hvigor sync...`);try{await e.sync(t,n)}catch(o){pt("hvigor sync",o)}console.log(`
15
- [3/3] Running hvigor build...`);try{i.type==="product"?await e.buildProduct(t,n):await e.buildModules(t,n,i.modulesToBuild,i.moduleTasks)}catch(o){pt("hvigor build",o)}}var hi=new ia("build").description("Build the HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async r=>{try{let e=process.cwd(),t=ke.discover(e);console.warn(pi("Please ensure the project source is trustworthy before proceeding."));let n=await O.new();oa(t,r);let i=r.product||"default",o=r.buildMode||"debug",s;if(r.product&&!r.modules)s={type:"product"};else{let d=sa(t,r),u=Zn(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:u}}let a=new _e(n,t.rootDir),c=new Te(n,t.rootDir);await ut(t.rootDir,async()=>Xn(a,c,i,o,s),()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
16
- `+ui("Build completed successfully!"))}catch(e){console.error(Kn(e.message)),process.exit(1)}});hi.command("clean").description("Clean the HarmonyOS project build outputs").action(async()=>{try{let r=process.cwd(),e=ke.discover(r);console.warn(pi("Please ensure the project source is trustworthy before proceeding."));let t=await O.new(),n=new Te(t,e.rootDir);await ut(e.rootDir,async()=>{console.log(`
17
- [1/2] Running hvigor clean...`);try{await n.clean()}catch(i){pt("hvigor clean",i)}console.log(`
18
- [2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(i){pt("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
19
- `+ui("Clean completed successfully!"))}catch(r){console.error(Kn(r.message)),process.exit(1)}});var fi=hi;import{Command as Sa}from"commander";import{green as Si,red as Pa,yellow as Ea}from"colorette";import{randomUUID as wa}from"crypto";import{execa as ba}from"execa";import{execa as va}from"execa";import{execFile as aa,spawn as ca}from"child_process";import{promisify as la}from"util";var da=la(aa);function mi(r,e,t){let i=r.replace(/\r\n/g,`
12
+ `)}`)}static resolveEmulatorPath(e,t){let n;if(t==="win32")n=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!R.existsSync(n))throw new Error(`Emulator executable not found at: ${n}`);return n}static verifyTools(e,t,n,i){if(!R.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!R.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!R.existsSync(n))throw new Error(`hvigor js file not found at: ${n}`);if(!R.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=Y.platform(),n;if(t==="win32")n=hi(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=hi(e,"Contents","tools","emulator","Emulator");else return;return pi(n)?n:void 0}static isValidApiLevel(e,t){let n=t??23;return Number.isInteger(e)&&e>=17&&e<=n}static parseApiLevelFromFile(e){if(R.existsSync(e))try{let t=R.readFileSync(e,"utf-8"),n=JSON.parse(t),i=n?.apiVersion??n?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return r.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let n of t){let i=r.parseApiLevelFromFile(n);if(i!==void 0)return i}}getMaxApiLevel(){let e=r.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=r.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(r._powerShellPath)return r._powerShellPath;if(Y.platform()!=="win32")return r._powerShellPath="",r._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return pi(e)?(w(`[ToolProvider] Found PowerShell at: ${e}`),r._powerShellPath=e,e):(r._powerShellPath="",r._powerShellPath)}static verifySignature(e){if(!R.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=Y.platform();if(r.isExecutableFile(e,t)){if(t==="win32"){if(!r.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!r.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return R.accessSync(e,R.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=R.mkdtempSync(E.join(Y.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return R.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=r.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:n,scriptPath:i}=r.createSignatureScript();try{let o=er(t,["-NoProfile","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","ignore"]}),s=JSON.parse(o);return{signed:s?.Status===0,signer:s?.SignerCertificate?.Subject??void 0}}catch(o){return w(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{R.rmSync(n,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return er("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as la}from"execa";import*as Wt from"path";var Te=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Wt.dirname(e.javaPath)}${Wt.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async sync(e,t){let n=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(n)}async buildProduct(e,t){let n=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(n)}async buildModules(e,t,n,i){let o=[...Array.from(i),"--mode","module","-p",`module=${n.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async runHvigor(e){let t=this.toolProvider.nodePath,n=[this.toolProvider.hvigorJsPath,...e];w(`Executing: ${t} ${n.join(" ")}`),await la(t,n,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as da}from"execa";var _e=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];w(`Executing: ${e} ${t.join(" ")}`),await da(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as ua}from"fs/promises";import{dirname as pa,resolve as ha}from"path";import{execa as fa}from"execa";import{lock as tr,check as qp}from"proper-lockfile";function nr(r){return ha(r,".hvigor",".build-lock")}function ma(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function gi(r){let e=pa(nr(r));if(await ua(e,{recursive:!0}),process.platform==="win32")try{await fa("attrib",["+h",e])}catch{}}async function ga(r,e){let t=new AbortController,n=ma(e);await gi(r);let i={lockfilePath:nr(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await tr(r,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return n(),{release:await tr(r,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function pt(r,e,t){let{release:n,signal:i}=await ga(r,t);try{return await e(i)}finally{await n()}}async function yi(r,e){let t=new AbortController;await gi(r);let n={lockfilePath:nr(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await tr(r,{...n,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}function va(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode&&!r.profile.app.buildModeSet.some(n=>n.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function wa(r,e){let t;if(e.modules&&e.modules.length>0)t=e.modules;else{let i=r.profile.modules,o=i.filter(s=>r.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let n=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";n.add(`${s}@${a}`)}return Array.from(n)}function ir(r,e){let t=new Set;for(let n of e){let i=n.indexOf("@"),o=i!==-1?n.substring(0,i):n,s=r.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function ht(r,e){let t=e,n=`${r} failed`;console.error(rr(n));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(n,{cause:e})}async function or(r,e,t,n,i){console.log(`
13
+ [1/3] Running ohpm install...`);try{await r.installAll()}catch(o){ht("ohpm install",o)}console.log(`
14
+ [2/3] Running hvigor sync...`);try{await e.sync(t,n)}catch(o){ht("hvigor sync",o)}console.log(`
15
+ [3/3] Running hvigor build...`);try{i.type==="product"?await e.buildProduct(t,n):await e.buildModules(t,n,i.modulesToBuild,i.moduleTasks)}catch(o){ht("hvigor build",o)}}var bi=new ya("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async r=>{try{let e=process.cwd(),t=ke.discover(e);console.warn(wi("Ensure the project source is trustworthy before proceeding."));let n=await O.new();va(t,r);let i=r.product||"default",o=r.buildMode||"debug",s;if(r.product&&!r.modules)s={type:"product"};else{let d=wa(t,r),u=ir(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:u}}let a=new _e(n,t.rootDir),c=new Te(n,t.rootDir);await pt(t.rootDir,async()=>or(a,c,i,o,s),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
16
+ `+vi("Build completed successfully"))}catch(e){console.error(rr(e.message)),process.exit(1)}});bi.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let r=process.cwd(),e=ke.discover(r);console.warn(wi("Ensure the project source is trusted before proceeding."));let t=await O.new(),n=new Te(t,e.rootDir);await pt(e.rootDir,async()=>{console.log(`
17
+ [1/2] Running hvigor clean...`);try{await n.clean()}catch(i){ht("hvigor clean",i)}console.log(`
18
+ [2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(i){ht("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
19
+ `+vi("Clean completed successfully."))}catch(r){console.error(rr(r.message)),process.exit(1)}});var Si=bi;import{Command as Na}from"commander";import{green as ki,red as La,yellow as Ha}from"colorette";import{randomUUID as xa}from"crypto";import{execa as Oa}from"execa";import{execa as Ra}from"execa";import{execFile as ba,spawn as Sa}from"child_process";import{promisify as Pa}from"util";var Ea=Pa(ba);function Pi(r,e,t){let i=r.replace(/\r\n/g,`
20
20
  `).split(`
21
- `),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 gi(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function ua(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??0}}function pa(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function ha(r,e,t,n,i){r.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=mi(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=mi(e.stderrLineBuffer+s,"stderr",t)}),r.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),r.on("close",o=>{if(e.settled)return;e.settled=!0,gi(e.stdoutLineBuffer,"stdout",t),gi(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=ua(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),n(s)})}async function yi(r,e=[],t={}){try{let{stdout:n,stderr:i}=await da(r,e,t);return{stdout:typeof n=="string"?n.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(n){let i=n;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function vi(r,e,t){return await new Promise((n,i)=>{let o=ca(r,e,{stdio:["inherit","pipe","pipe"]}),s=pa();ha(o,s,t,n,i)})}function wi(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var fa=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i],ma=[/\[fail\]/i,/\bfail!/i,/not found/i];function We(r){return r?fa.some(e=>e.test(r))?"transient":ma.some(e=>e.test(r))?"fatal":"ok":"ok"}var Qn=[800,1500,2500];function ga(r){return new Promise(e=>setTimeout(e,r))}async function ve(r,e){let t=1+Qn.length,n={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){n=await yi(r,e);let o=n.exitCode===0?n.stdout:n.stderr||n.stdout;if(We(o)!=="transient"||i>=t-1)return n;w(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Qn[i]}ms`),await ga(Qn[i])}return n}async function tr(r,e,t){let n=await ve(r,["-t",e,"shell","param","get",t]);if(n.exitCode!==0)return;let i=n.stdout.trim();if(!(!i||We(i)!=="ok"))return wi(i)}var er="__DEVECO_PARAM_DELIM__";function ya(r,e){let t=new Map,n=r.split(er);for(let i=0;i<e.length;i++){let o=(n[i]??"").trim();if(!o||We(o)!=="ok")continue;let s=wi(o);s&&t.set(e[i],s)}return t}async function Ue(r,e,t){if(t.length===0)return new Map;if(t.length===1){let o=new Map,s=await tr(r,e,t[0]);return s&&o.set(t[0],s),o}let n=t.map(o=>`param get ${o}`).join(`; echo ${er}; `)+`; echo ${er}`,i=await ve(r,["-t",e,"shell",n]);return i.exitCode!==0?new Map:ya(i.stdout,t)}function ht(r){return r.startsWith("127.0.0.1:")}var bi=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype"],B=class r{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new r(e.hdcPath)}static withHdcPath(e){return new r(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let n=e.trim(),i=t?.trim();if(!n||!i)return n;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return n.replace(o,"").trim()||n}async executeHdc(e){return va(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
22
- `)){let i=n.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];!s||s.startsWith("[Empty]")||t.push({serial:s,status:o.length>=2?o[1]:"device"})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let i=e.get("const.product.model");if(i&&i!=="emulator"){let o=e.get("const.product.brand");return this.stripBrandPrefix(i,o)}}async getDeviceName(e){let t=await Ue(this.hdcPath,e,[...bi]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let n=e.find(s=>s.serial===t);if(n)return n;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Please use a serial instead:
21
+ `),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 Ei(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function Ca(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??0}}function Da(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function Ia(r,e,t,n,i){r.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=Pi(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=Pi(e.stderrLineBuffer+s,"stderr",t)}),r.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),r.on("close",o=>{if(e.settled)return;e.settled=!0,Ei(e.stdoutLineBuffer,"stdout",t),Ei(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=Ca(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),n(s)})}async function Ci(r,e=[],t={}){try{let{stdout:n,stderr:i}=await Ea(r,e,t);return{stdout:typeof n=="string"?n.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(n){let i=n;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function Di(r,e,t){return await new Promise((n,i)=>{let o=Sa(r,e,{stdio:["inherit","pipe","pipe"]}),s=Da();Ia(o,s,t,n,i)})}function Ii(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Aa=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],ka=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function We(r){return r?Aa.some(e=>e.test(r))?"transient":ka.some(e=>e.test(r))?"fatal":"ok":"ok"}var sr=[800,1500,2500];function Ta(r){return new Promise(e=>setTimeout(e,r))}async function we(r,e){let t=1+sr.length,n={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){n=await Ci(r,e);let o=n.exitCode===0?n.stdout:n.stderr||n.stdout;if(We(o)!=="transient"||i>=t-1)return n;w(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${sr[i]}ms`),await Ta(sr[i])}return n}async function Ut(r,e,t){let n=await we(r,["-t",e,"shell","param","get",t]);if(n.exitCode!==0)return;let i=n.stdout.trim();if(!(!i||We(i)!=="ok"))return Ii(i)}var ar="__DEVECO_PARAM_DELIM__";function Ma(r,e){let t=new Map,n=r.split(ar);for(let i=0;i<e.length;i++){let o=(n[i]??"").trim();if(!o||We(o)!=="ok")continue;let s=Ii(o);s&&t.set(e[i],s)}return t}async function Ue(r,e,t){if(t.length===0)return new Map;if(t.length===1){let s=new Map,a=await Ut(r,e,t[0]);return a&&s.set(t[0],a),s}let n=t.map(s=>`param get ${s}`).join(`; echo ${ar}; `)+`; echo ${ar}`,i=await we(r,["-t",e,"shell",n]);if(i.exitCode===0){let s=Ma(i.stdout,t);if(s.size>0)return s}w(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let o=new Map;for(let s of t){let a=await Ut(r,e,s);a&&o.set(s,a)}return o}function ft(r){return r.startsWith("127.0.0.1:")}var Ai=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],V=class r{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new r(e.hdcPath)}static withHdcPath(e){return new r(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let n=e.trim(),i=t?.trim();if(!n||!i)return n;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return n.replace(o,"").trim()||n}async executeHdc(e){return Ra(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
22
+ `)){let i=n.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];!s||s.startsWith("[Empty]")||t.push({serial:s,status:o.length>=2?o[1]:"device"})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Ue(this.hdcPath,e,[...Ai]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let n=e.find(s=>s.serial===t);if(n)return n;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
23
23
  `+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
24
- `)):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 n=await Ue(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=n.get("const.product.devicetype");let i=n.get("const.ohos.apiversion"),o=n.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=ht(e),n,i;try{let o=await Ue(this.hdcPath,e,[...bi]);n=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:i}}};var jt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;w(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await ba(n,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let n=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(n.includes("uninstall bundle successfully"))return!0;if(n.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${n}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${wa()}`;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,n){let i=["-t",e,"shell","aa","start","-a",n,"-b",t];return await this.runHdc(i)}};function Da(r){let e=r.indexOf("@"),t=e!==-1?r.substring(0,e):r,n=e!==-1?r.substring(e+1):"default";return{moduleName:t,targetName:n}}async function Ia(r,e){let t=await r.listDevices();if(t.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await r.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(`
25
- `))}let n=await r.getDeviceInfo(t,e);if(!n)throw new Error("No active devices found.");if(!e){let i=await r.getDeviceName(n.serial);console.log(`Auto-selected device: ${i} (${n.serial})`)}return n.serial}function Ca(r,e){if(e)return e;let t=r.profile.modules.filter(n=>{let i=r.getModuleType(n.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let n=t[0].name;return console.log(`Auto-selected module: ${n}`),n}throw new Error(`No module specified. Please specify a module using --module <name>.
24
+ `)):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 n=await Ue(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=n.get("const.product.devicetype");let i=n.get("const.ohos.apiversion"),o=n.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=ft(e),n,i;try{let o=await Ue(this.hdcPath,e,[...Ai]);n=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:i}}};var Bt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=V.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;w(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await Oa(n,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let n=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(n.includes("uninstall bundle successfully"))return!0;if(n.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${n}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${xa()}`;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,n){let i=["-t",e,"shell","aa","start","-a",n,"-b",t];return await this.runHdc(i)}};function ja(r){let e=r.indexOf("@"),t=e!==-1?r.substring(0,e):r,n=e!==-1?r.substring(e+1):"default";return{moduleName:t,targetName:n}}async function Fa(r,e){let t=await r.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await r.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
25
+ `))}let n=await r.getDeviceInfo(t,e);if(!n)throw new Error("No active devices found.");if(!e){let i=await r.getDeviceName(n.serial);console.log(`Auto-selected device: ${i} (${n.serial})`)}return n.serial}function $a(r,e){if(e)return e;let t=r.profile.modules.filter(n=>{let i=r.getModuleType(n.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let n=t[0].name;return console.log(`Auto-selected module: ${n}`),n}throw new Error(`Specify a module using --module <name>.
26
26
  Available runnable modules:
27
27
  `+t.map(n=>` - ${n.name}`).join(`
28
- `))}function Aa(r,e,t,n,i){let o=[],s=r.collectNonHarDependentModuleList(e);for(let c of s){let d=r.findArtifactPath(c,t,n,i);o.push(d)}let a=r.findArtifactPath(e,t,n,i);return o.push(a),o}async function ka(r,e,t,n,i,o){o&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} is not installed, skipping uninstall.`)),console.log(`
29
- Installing artifacts to device ${e}...`),await r.installApp(e,n),console.log(`Launching ${t}/${i}...`);let s=await r.launchApp(e,t,i);console.log(Si(`
30
- Application '${t}': ${s}`))}var Ta=new Sa("run").description("Build and run the project on a connected device").option("--module <module>","Module 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 (e.g. debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip the build step and deploy the existing artifacts").action(async r=>{try{await xa(r)}catch(e){console.error(Pa(e.message)),process.exit(1)}});async function Ma(r,e,t,n,i,o){let s=new _e(e,r.rootDir),a=new Te(e,r.rootDir),d=r.collectNonHarDependentModuleList(t).map(k=>`${k}@${n}`),u=Zn(r,d),b={type:"modules",modulesToBuild:d,moduleTasks:u};await ut(r.rootDir,()=>Xn(s,a,i,o,b),()=>console.log("Another build is already running for this project. Waiting for it to finish...")),console.log(`
31
- `+Si("Build completed successfully!"))}async function xa(r){let e=ke.discover(process.cwd());console.warn(Ea("Please ensure the project source is trustworthy before proceeding."));let t=await O.new(),n=Ca(e,r.module),{moduleName:i,targetName:o}=Da(n),s=e.getModuleType(i);if(s!=="entry"&&s!=="feature"&&s!=="shared")throw new Error(`Module '${i}' is of type '${s}', which is not runnable. Please specify an entry or feature module.`);let a=new jt(t),c=B.from(t),d=await Ia(c,r.device),u=d.includes("127.0.0.1")||d.includes("localhost"),b=r.product||"default";e.validateProduct(b);let k=r.buildMode||"debug";r.skipBuild||await Ma(e,t,i,o,b,k);let le=Aa(e,i,o,u,b),Fe=e.getBundleName(),$e=e.getMainAbility(i,r.ability);await ka(a,d,Fe,le,$e,!!r.uninstall)}var Pi=Ta;import{Command as Ra}from"commander";import{green as Ei,red as Di,cyan as nr}from"colorette";import{execa as Ii}from"execa";function Oa(){return"@deveco-test/deveco-cli"}function Na(){return"0.8.0"}var La=new Ra("update").description("Update deveco-cli to the latest version").action(async()=>{let r=Oa(),e=Na();console.log(nr("Checking for updates..."));try{let{stdout:t}=await Ii("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(Ei(`
32
- ${r} is already up to date (version ${e})`));return}console.log(nr(`
33
- New version found: ${n} (current: ${e})`)),console.log(nr(`Updating ${r}...`)),await Ii("npm",["install","-g",`${r}@latest`],{stdio:"inherit"}),console.log(`
34
- `+Ei(`${r} updated successfully to version ${n}!`))}catch(t){let n=t;console.error(Di(`Failed to update ${r}`)),n.message&&console.error(Di(n.message)),process.exit(1)}}),Ci=La;import{Command as rc}from"commander";import{execa as sr}from"execa";function H(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Ha}from"child_process";var ja=2500;function Fa(r,e,t,n,i,o){r.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?n():i(a||`Emulator process exited with code ${s}`)})}function $a(r,e,t,n){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(d),r.removeAllListeners(),r.stderr?.removeAllListeners(),r.stderr?.destroy(),r.unref(),t())},c=u=>{if(!i){i=!0,clearTimeout(d),r.removeAllListeners(),r.stderr?.removeAllListeners();try{r.kill()}catch{}n(new Error(u))}},d=setTimeout(a,ja);r.once("error",u=>c(u.message)),Fa(r,d,s,a,c,o)}function Ai(r,e,t){return w(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,i)=>{let o=[],s=Ha(r,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),$a(s,o,n,i)})}import*as Be from"path";function _a(r){let e=new Set,t=[];for(let n of r){let i=JSON.stringify(n);e.has(i)||(e.add(i),t.push(n))}return t}function Wa(r){let e=r.instancePath?.trim();if(e)return Be.dirname(Be.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?Be.dirname(Be.normalize(t)).replace(/\\/g,"/"):""}function Ua(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function ki(r,e){return e?[...r,"-bootmode",e]:r}function Ba(r,e,t){let n=[ki(["-start",r],t)],i=Wa(e);if(i)for(let o of Ua(e.imageRoot))n.push(ki(["-hvd",r,"-path",i,...o],t));return _a(n)}async function Ti(r,e,t,n){let i=new Error("No start strategy ran"),o=Ba(r,e,n);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function rr(r){return(await B.withHdcPath(r).listDevices()).map(t=>t.serial).filter(ht)}async function ir(r){let e=await rr(r);return e.length===0?[]:(await Promise.all(e.map(n=>tr(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Mi(r,e){return(await ir(r)).includes(e)}import*as Ve from"path";import{existsSync as za,statSync as Va}from"fs";function ze(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function qa(r){let e=ze(r,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return n.trim()}return""}function Ya(r){return ze(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Ga(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Ve.dirname(Ve.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=Ve.join(t,n.name);za(i)&&Va(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function Ja(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=Ya(t),i=ze(t,["deviceType","DeviceType","devicetype"]),o=ze(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:qa(t),path:ze(t,["path","Path","hvdPath","hvd_path"]),imageRoot:ze(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function Ka(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,i;for(;(i=t.exec(r))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=o.toLowerCase();a==="isrunning"?n.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?n.instancePath=s.trim():a==="path"?n.path=s.trim():a==="imageroot"?n.imageRoot=s.trim():a==="devicetype"?n.deviceType=s.trim():a==="os.osversion"&&(n.osVersion=s.trim())}}return n&&e.push(n),e}function xi(r){let t=Ja(r)??Ka(r);return Ga(t),t}function or(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function Za(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Xa(r){if(!Za(r))return null;let e=or(r,["osVersion","OsVersion","OSVersion"]),t=or(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=or(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Ft(r){let e=r.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=Xa(i);o&&n.push(o)}return n}catch{return[]}}function Ri(r){let t=Ft(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var Oi=/no images are available/i;function ne(r){return r.normalize("NFKC").trim().toLowerCase()}function Qa(r){let e=r.message||"";return Oi.test(e)}var qe=class r{emulatorPath;sdkPath;hdcPath;constructor(e,t,n){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=n}static from(e){return new r(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return sr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Ai(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return xi(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set(H(n.name),n.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),n=H(e),i=t.find(a=>H(a.name)===n);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 Ti(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.
35
- 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:Mi(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),n=H(e),i=t.find(a=>H(a.name)===n);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 executeEmulatorInherit(e){let{exitCode:t}=await sr(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 n;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!Qa(o))throw o;n=o}(n!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,n)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:n}=await this.executeEmulator(t);return n}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return Ri(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,n){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=n!==void 0?`Primary uninstall failed: ${n.message}
36
- `:"";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}" is still listed as downloaded after uninstall.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(n=>n.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),n=Ft(t),i=ne(e.deviceType),o=ne(e.osVersion);return n.filter(s=>ne(s.deviceType)===i&&(ne(s.osVersion)===o||ne(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let n=await this.listEmulatorImages({downloaded:!0}),i=Ft(n),o=ne(t),s=e?.trim()?ne(e):void 0;return i.some(a=>ne(a.osVersion)===o||ne(a.softwareVersion)===o?s===void 0?!0:ne(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:[Oi]})}async runEmulatorChecked(e,t){let{stdout:n,stderr:i,exitCode:o}=await sr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20971520}),s=[n,i].filter(Boolean).join(`
37
- `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(u=>u.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 u=(t?.transformOutput?t.transformOutput(s):s).trim();u&&console.log(u)}}async checkExistingVirtualDevice(e,t){let n=await this.listEmulators(),i=H(e),o=n.find(s=>H(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),n=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(n,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
38
- `)}),!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 timeout. Please open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,n=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>H(a.name)===e))return!0;await new Promise(a=>setTimeout(a,n))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),n=H(e),i=t.find(s=>H(s.name)===n);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}
39
- The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as ar,yellow as Li,gray as Hi}from"colorette";import ic from"ora";import{red as ec}from"colorette";function $t(r,e){r?r.fail(e):console.error(ec(e)),process.exit(1)}import{green as tc}from"colorette";function Ni(r,e){return r+" ".repeat(Math.max(0,e-r.length))}function nc(r,e){return r.map((t,n)=>{let i=t.length;for(let o of e){let s=o.cells[n]??"";i=Math.max(i,s.length)}return i})}function ft(r,e){let t=nc(r,e),n=[];n.push(r.map((i,o)=>Ni(i,t[o])).join(" ")),n.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Ni(s??"",t[a])).join(" ").trimEnd();n.push(i.highlight?tc(o):o)}return n.join(`
40
- `)}function oc(r,e){if(e.size!==0)for(let t of r){if(!t.isEmulator||!t.name)continue;let n=e.get(H(t.name));n&&(t.deviceType=n)}}var sc=["Name","Serial","Kind","Device Type"];function ac(r){return{cells:[r.name??r.serial,r.serial,r.isEmulator?"emulator":"device",r.deviceType??"-"],highlight:!0}}function cc(r,e){return r.isEmulator!==e.isEmulator?r.isEmulator?1:-1:(r.name??r.serial).localeCompare(e.name??e.serial)}function lc(){console.log(Li(" No active devices.")),console.log(Hi(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function dc(r){let t=[...r].sort(cc).map(ac);console.log(ft(sc,t))}async function uc(r,e){if(!r.some(i=>i.isEmulator)||!e.emulatorPath)return;let n=await qe.from(e).getDeviceTypeByName();oc(r,n)}async function pc(r,e,t){try{let n=await r.getConnectedEntries();await uc(n,e),t?.stop(),n.length===0?lc():dc(n)}catch(n){$t(t,`Failed to list devices: ${n.message}`)}}async function hc(r,e){let t=await r.listDevices();if(!(t.length<2)){console.error(ar("Multiple devices connected. Please specify a device with:"));for(let n of t){let i=await r.getDeviceName(n.serial);console.error(Hi(` ${e} -t ${n.serial} # ${i}`))}process.exit(1)}}async function fc(r,e){try{e||await hc(r,"devecocli device view");let t=await r.listDevices(),n=await r.getDeviceInfo(t,e);n||(console.log(Li("No connected device found.")),process.exit(1));let i=await r.getDeviceDetail(n.serial),o=await r.getDeviceName(n.serial);console.log(` Serial: ${n.serial}`),console.log(` Device Name: ${o}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}catch(t){console.error(ar(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function ji(){try{let r=await O.new();return{manager:B.from(r),toolProvider:r}}catch(r){console.error(ar(`Failed to initialize device manager: ${r.message}`)),process.exit(1);return}}var cr=new rc("device").description("Manage connected devices");cr.command("list").description("List all connected devices").action(async()=>{let{manager:r,toolProvider:e}=await ji(),t=ic({text:"Querying connected devices\u2026",color:"cyan"}).start();await pc(r,e,t)});cr.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async r=>{let{manager:e}=await ji();await fc(e,r.target)});var Fi=cr;import{Command as hr,Option as Qi}from"commander";import{green as Wt,cyan as Ge,red as z,yellow as re,gray as Je}from"colorette";import Oc from"ora";import mc from"readline/promises";import{execa as _i}from"execa";import*as we from"fs/promises";import*as dr from"os";import*as Me from"path";var lr=`1/4:\r
28
+ `))}function _a(r,e,t,n,i){let o=[],s=r.collectNonHarDependentModuleList(e);for(let c of s){let d=r.findArtifactPath(c,t,n,i);o.push(d)}let a=r.findArtifactPath(e,t,n,i);return o.push(a),o}async function Wa(r,e,t,n,i,o){o&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
29
+ Installing artifacts to device ${e}...`),await r.installApp(e,n),console.log(`Launching ${t}/${i}...`);let s=await r.launchApp(e,t,i);console.log(ki(`
30
+ Application '${t}': ${s}`))}var Ua=new Na("run").description("Build and run the project on a connected device").option("--module <module>","Module 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").action(async r=>{try{await Va(r)}catch(e){console.error(La(e.message)),process.exit(1)}});async function Ba(r,e,t,n,i,o){let s=new _e(e,r.rootDir),a=new Te(e,r.rootDir),d=r.collectNonHarDependentModuleList(t).map(D=>`${D}@${n}`),u=ir(r,d),v={type:"modules",modulesToBuild:d,moduleTasks:u};await pt(r.rootDir,()=>or(s,a,i,o,v),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
31
+ `+ki("Build completed successfully."))}async function Va(r){let e=ke.discover(process.cwd());console.warn(Ha("Ensure the project source is trusted before proceeding."));let t=await O.new(),n=$a(e,r.module),{moduleName:i,targetName:o}=ja(n),s=e.getModuleType(i);if(s!=="entry"&&s!=="feature"&&s!=="shared")throw new Error(`Module '${i}' '${s}' is not runnable. Specify an entry or feature module.`);let a=new Bt(t),c=V.from(t),d=await Fa(c,r.device),u=d.includes("127.0.0.1")||d.includes("localhost"),v=r.product||"default";e.validateProduct(v);let D=r.buildMode||"debug";r.skipBuild||await Ba(e,t,i,o,v,D);let le=_a(e,i,o,u,v),Fe=e.getBundleName(),$e=e.getMainAbility(i,r.ability);await Wa(a,d,Fe,le,$e,!!r.uninstall)}var Ti=Ua;import{Command as za}from"commander";import{green as Mi,red as Ri,cyan as cr}from"colorette";import{execa as xi}from"execa";function qa(){return"@deveco-test/deveco-cli"}function Ya(){return"1.2.0"}var Ga=new za("update").description("Update deveco-cli to latest").action(async()=>{let r=qa(),e=Ya();console.log(cr("Checking for updates..."));try{let{stdout:t}=await xi("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(Mi(`
32
+ ${r} is already up to date (version ${e}.)`));return}console.log(cr(`
33
+ New version found: ${n} (current: ${e})`)),console.log(cr(`Updating ${r}...`)),await xi("npm",["install","-g",`${r}@latest`],{stdio:"inherit"}),console.log(`
34
+ `+Mi(`${r} updated successfully to version ${n}.`))}catch(t){let n=t;console.error(Ri(`Failed to update ${r}`)),n.message&&console.error(Ri(n.message)),process.exit(1)}}),Oi=Ga;import{Command as gc}from"commander";import{execa as pr}from"execa";function H(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Ja}from"child_process";var Ka=2500;function Xa(r,e,t,n,i,o){r.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?n():i(a||`Emulator process exited with code ${s}`)})}function Za(r,e,t,n){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(d),r.removeAllListeners(),r.stderr?.removeAllListeners(),r.stderr?.destroy(),r.unref(),t())},c=u=>{if(!i){i=!0,clearTimeout(d),r.removeAllListeners(),r.stderr?.removeAllListeners();try{r.kill()}catch{}n(new Error(u))}},d=setTimeout(a,Ka);r.once("error",u=>c(u.message)),Xa(r,d,s,a,c,o)}function Ni(r,e,t){return w(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,i)=>{let o=[],s=Ja(r,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),Za(s,o,n,i)})}import*as Be from"path";function Qa(r){let e=new Set,t=[];for(let n of r){let i=JSON.stringify(n);e.has(i)||(e.add(i),t.push(n))}return t}function ec(r){let e=r.instancePath?.trim();if(e)return Be.dirname(Be.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?Be.dirname(Be.normalize(t)).replace(/\\/g,"/"):""}function tc(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function Li(r,e){return e?[...r,"-bootmode",e]:r}function nc(r,e,t){let n=[Li(["-start",r],t)],i=ec(e);if(i)for(let o of tc(e.imageRoot))n.push(Li(["-hvd",r,"-path",i,...o],t));return Qa(n)}async function Hi(r,e,t,n){let i=new Error("No start strategy ran"),o=nc(r,e,n);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function lr(r){return(await V.withHdcPath(r).listDevices()).map(t=>t.serial).filter(ft)}async function dr(r){let e=await lr(r);return e.length===0?[]:(await Promise.all(e.map(n=>Ut(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function ji(r,e){return(await dr(r)).includes(e)}import*as ze from"path";import{existsSync as rc,statSync as ic}from"fs";function Ve(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function oc(r){let e=Ve(r,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return n.trim()}return""}function sc(r){return Ve(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function ac(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=ze.dirname(ze.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=ze.join(t,n.name);rc(i)&&ic(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function cc(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=sc(t),i=Ve(t,["deviceType","DeviceType","devicetype"]),o=Ve(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:oc(t),path:Ve(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Ve(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function lc(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,i;for(;(i=t.exec(r))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=o.toLowerCase();a==="isrunning"?n.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?n.instancePath=s.trim():a==="path"?n.path=s.trim():a==="imageroot"?n.imageRoot=s.trim():a==="devicetype"?n.deviceType=s.trim():a==="os.osversion"&&(n.osVersion=s.trim())}}return n&&e.push(n),e}function Fi(r){let t=cc(r)??lc(r);return ac(t),t}function ur(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function dc(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function uc(r){if(!dc(r))return null;let e=ur(r,["osVersion","OsVersion","OSVersion"]),t=ur(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=ur(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Vt(r){let e=r.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=uc(i);o&&n.push(o)}return n}catch{return[]}}function $i(r){let t=Vt(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var _i=/no images are available/i;function re(r){return r.normalize("NFKC").trim().toLowerCase()}function pc(r){let e=r.message||"";return _i.test(e)}var qe=class r{emulatorPath;sdkPath;hdcPath;constructor(e,t,n){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=n}static from(e){return new r(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return pr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Ni(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Fi(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set(H(n.name),n.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),n=H(e),i=t.find(a=>H(a.name)===n);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 Hi(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.
35
+ 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:ji(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),n=H(e),i=t.find(a=>H(a.name)===n);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 executeEmulatorInherit(e){let{exitCode:t}=await pr(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 n;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!pc(o))throw o;n=o}(n!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,n)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:n}=await this.executeEmulator(t);return n}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return $i(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,n){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=n!==void 0?`Primary uninstall failed: ${n.message}
36
+ `:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(n=>n.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),n=Vt(t),i=re(e.deviceType),o=re(e.osVersion);return n.filter(s=>re(s.deviceType)===i&&(re(s.osVersion)===o||re(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let n=await this.listEmulatorImages({downloaded:!0}),i=Vt(n),o=re(t),s=e?.trim()?re(e):void 0;return i.some(a=>re(a.osVersion)===o||re(a.softwareVersion)===o?s===void 0?!0:re(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:[_i]})}async runEmulatorChecked(e,t){let{stdout:n,stderr:i,exitCode:o}=await pr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20971520}),s=[n,i].filter(Boolean).join(`
37
+ `).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(u=>u.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 u=(t?.transformOutput?t.transformOutput(s):s).trim();u&&console.log(u)}}async checkExistingVirtualDevice(e,t){let n=await this.listEmulators(),i=H(e),o=n.find(s=>H(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),n=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(n,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
38
+ `)}),!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,n=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>H(a.name)===e))return!0;await new Promise(a=>setTimeout(a,n))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),n=H(e),i=t.find(s=>H(s.name)===n);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}
39
+ The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as hr,yellow as Ui,gray as Bi}from"colorette";import yc from"ora";import{red as hc}from"colorette";function zt(r,e){r?r.fail(e):console.error(hc(e)),process.exit(1)}import{green as fc}from"colorette";function Wi(r,e){return r+" ".repeat(Math.max(0,e-r.length))}function mc(r,e){return r.map((t,n)=>{let i=t.length;for(let o of e){let s=o.cells[n]??"";i=Math.max(i,s.length)}return i})}function mt(r,e){let t=mc(r,e),n=[];n.push(r.map((i,o)=>Wi(i,t[o])).join(" ")),n.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Wi(s??"",t[a])).join(" ").trimEnd();n.push(i.highlight?fc(o):o)}return n.join(`
40
+ `)}function vc(r,e){if(e.size!==0)for(let t of r){if(!t.isEmulator||!t.name)continue;let n=e.get(H(t.name));n&&(t.deviceType=n)}}var wc=["Name","Serial","Kind","Device Type"];function bc(r){return{cells:[r.name??r.serial,r.serial,r.isEmulator?"emulator":"device",r.deviceType??"-"],highlight:!0}}function Sc(r,e){return r.isEmulator!==e.isEmulator?r.isEmulator?1:-1:(r.name??r.serial).localeCompare(e.name??e.serial)}function Pc(){console.log(Ui(" No active devices.")),console.log(Bi(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Ec(r){let t=[...r].sort(Sc).map(bc);console.log(mt(wc,t))}async function Cc(r,e){if(!r.some(i=>i.isEmulator)||!e.emulatorPath)return;let n=await qe.from(e).getDeviceTypeByName();vc(r,n)}async function Dc(r,e,t){try{let n=await r.getConnectedEntries();await Cc(n,e),t?.stop(),n.length===0?Pc():Ec(n)}catch(n){zt(t,`Failed to list devices: ${n.message}`)}}async function Ic(r,e){let t=await r.listDevices();if(!(t.length<2)){console.error(hr("Multiple devices connected. Specify a device with:"));for(let n of t){let i=await r.getDeviceName(n.serial);console.error(Bi(` ${e} -t ${n.serial} # ${i}`))}process.exit(1)}}async function Ac(r,e){try{e||await Ic(r,"devecocli device view");let t=await r.listDevices(),n=await r.getDeviceInfo(t,e);n||(console.log(Ui("No connected device found.")),process.exit(1));let i=await r.getDeviceDetail(n.serial),o=await r.getDeviceName(n.serial);console.log(` Serial: ${n.serial}`),console.log(` Device Name: ${o}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}catch(t){console.error(hr(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Vi(){try{let r=await O.new();return{manager:V.from(r),toolProvider:r}}catch(r){console.error(hr(`Failed to initialize device manager: ${r.message}`)),process.exit(1);return}}var fr=new gc("device").description("Manage connected devices");fr.command("list").description("List all connected devices").action(async()=>{let{manager:r,toolProvider:e}=await Vi(),t=yc({text:"Querying connected devices\u2026",color:"cyan"}).start();await Dc(r,e,t)});fr.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async r=>{let{manager:e}=await Vi();await Ac(e,r.target)});var zi=fr;import{Command as wr,Option as so}from"commander";import{green as Yt,cyan as Ge,red as z,yellow as ie,gray as yt}from"colorette";import qc from"ora";import kc from"readline/promises";import{execa as Yi}from"execa";import*as be from"fs/promises";import*as gr from"os";import*as Me from"path";var mr=`1/4:\r
41
41
  ---------------------------------------\r
42
42
  Statement About HarmonyOS and Privacy\r
43
43
  \r
@@ -1207,58 +1207,58 @@ Part I: Chinese mainland.\r
1207
1207
  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
1208
1208
  \r
1209
1209
  Part III: Other countries and regions.\r
1210
- ---------------------------------------\r`;var gc=new Set,_t=new Map,ur="HarmonyOS_Software_Service_Agreement",Wi=["Emulator license agreements are not accepted yet.","","Accept the agreements in an interactive terminal:"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1211
- `),Ui=Wi,pr="HarmonyOS_SDK_Agreement";function Bi(r,e){return`${r}\0${e}`}function yc(){gc.clear(),_t.clear()}var vc=Wi,Z=class extends Error{constructor(e=vc){super(e),this.name="EmulatorLicenseBlockedError"}};function zi(r,e){return[r??"",e??""].join(`
1212
- `)}function Vi(r){let e=r.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let n=e.match(/(\d+)\.(\d+)\b/);return n?`${n[1]}.${n[2]}`:null}function wc(r){return`Emulator${r.trim()}`}function qi(r){let e=wc(r);if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;if(!n)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return Me.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Me.join(dr.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Me.join(dr.homedir(),".cache");return Me.join(t,"Huawei",e,".emu_config")}async function bc(r,e,t){let n=Bi(r,e),i=_t.get(n);if(i!==void 0)return i;let o=await _i(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=zi(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Z(t);return _t.set(n,s),s}function Sc(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function Pc(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,i]of Object.entries(e))t[n]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function Ec(r){let e=r.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let n=e.indexOf(t);if(n<=0)continue;let i=e.slice(0,n).trim();if(!i||t===":"&&i.includes("//"))continue;let o=Sc(e.slice(n+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Dc(r){let e={};for(let t of r.split(/\r?\n/)){let n=Ec(t);n&&(e[n.key]=n.entry)}return e}function Ic(r){let e=r.trim();if(!e)return{};let t=Pc(e);return t||Dc(r)}function Cc(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function Yi(r,e,t,n){let i=await bc(r,e,n),o=Vi(i);if(!o)throw new Z(n);let s=qi(o),a;try{a=await we.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new Z(n):u}let d=Ic(a)[t];if(!d)throw new Z(n);if(d.delimiter==="=")throw new Z(n);if(!Cc(d.value))throw new Z(n)}async function Gi(r,e){await Yi(r,e,ur,Ui)}async function Ji(r,e){await Yi(r,e,pr,Ui)}async function Ac(r,e){let t=await _i(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=zi(t.stdout,t.stderr).trim();if(t.exitCode!==0||!n)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=Bi(r,e);return _t.set(i,n),n}async function kc(r,e){let t=await Ac(r,e),n=Vi(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
1213
- ${t}`);return qi(n)}function $i(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Tc(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[ur]="agree",n[pr]="agree",await we.writeFile(r,`${JSON.stringify(n,null,2)}
1214
- `,"utf8"),!0}catch{}return!1}async function Mc(r,e){let t=ur,n=pr,i=[{k:t,re:new RegExp(`^\\s*${$i(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${$i(n)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let d=!1;for(let{k:u,re:b}of i)if(b.test(c)){s.push(`${u}:agree`),a.add(u),d=!0;break}d||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(n)||s.push(`${n}:agree`),await we.writeFile(r,s.join(`
1210
+ ---------------------------------------\r`;var Tc=new Set,qt=new Map,yr="HarmonyOS_Software_Service_Agreement",Gi=["Emulator license agreements are not accepted yet.","","Accept the agreements in an interactive terminal:"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
1211
+ `),Ji=Gi,vr="HarmonyOS_SDK_Agreement";function Ki(r,e){return`${r}\0${e}`}function Mc(){Tc.clear(),qt.clear()}var Rc=Gi,Z=class extends Error{constructor(e=Rc){super(e),this.name="EmulatorLicenseBlockedError"}};function Xi(r,e){return[r??"",e??""].join(`
1212
+ `)}function Zi(r){let e=r.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let n=e.match(/(\d+)\.(\d+)\b/);return n?`${n[1]}.${n[2]}`:null}function xc(r){return`Emulator${r.trim()}`}function Qi(r){let e=xc(r);if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;if(!n)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return Me.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Me.join(gr.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Me.join(gr.homedir(),".cache");return Me.join(t,"Huawei",e,".emu_config")}async function Oc(r,e,t){let n=Ki(r,e),i=qt.get(n);if(i!==void 0)return i;let o=await Yi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Xi(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new Z(t);return qt.set(n,s),s}function Nc(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function Lc(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,i]of Object.entries(e))t[n]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function Hc(r){let e=r.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let n=e.indexOf(t);if(n<=0)continue;let i=e.slice(0,n).trim();if(!i||t===":"&&i.includes("//"))continue;let o=Nc(e.slice(n+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function jc(r){let e={};for(let t of r.split(/\r?\n/)){let n=Hc(t);n&&(e[n.key]=n.entry)}return e}function Fc(r){let e=r.trim();if(!e)return{};let t=Lc(e);return t||jc(r)}function $c(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function eo(r,e,t,n){let i=await Oc(r,e,n),o=Zi(i);if(!o)throw new Z(n);let s=Qi(o),a;try{a=await be.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new Z(n):u}let d=Fc(a)[t];if(!d)throw new Z(n);if(d.delimiter==="=")throw new Z(n);if(!$c(d.value))throw new Z(n)}async function to(r,e){await eo(r,e,yr,Ji)}async function no(r,e){await eo(r,e,vr,Ji)}async function _c(r,e){let t=await Yi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=Xi(t.stdout,t.stderr).trim();if(t.exitCode!==0||!n)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=Ki(r,e);return qt.set(i,n),n}async function Wc(r,e){let t=await _c(r,e),n=Zi(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
1213
+ ${t}.`);return Qi(n)}function qi(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Uc(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[yr]="agree",n[vr]="agree",await be.writeFile(r,`${JSON.stringify(n,null,2)}
1214
+ `,"utf8"),!0}catch{}return!1}async function Bc(r,e){let t=yr,n=vr,i=[{k:t,re:new RegExp(`^\\s*${qi(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${qi(n)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let d=!1;for(let{k:u,re:v}of i)if(v.test(c)){s.push(`${u}:agree`),a.add(u),d=!0;break}d||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(n)||s.push(`${n}:agree`),await be.writeFile(r,s.join(`
1215
1215
  `)+(s.length>0?`
1216
- `:""),"utf8")}async function xc(r){await we.mkdir(Me.dirname(r),{recursive:!0});let e="";try{e=await we.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Tc(r,e,t)||await Mc(r,e)}async function Ki(r,e){return console.log(lr),0}var Rc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Zi(r,e){if(console.log(lr),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("devecocli emulator license accept requires an interactive terminal."),1;let n=mc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(Rc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await kc(r,e);await xc(s),yc()}catch(s){return console.error(s.message),1}return 0}var Nc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Lc(r){let e=r.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Hc(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid: use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)"'):new Error(`--os-version must start with "HarmonyOS " (e.g. HarmonyOS 5.1.1(19)). Got: "${r}"`)}function jc(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(re("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(re("Run `devecocli emulator image download ...` then `devecocli emulator image list` and copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===n)){console.error(z("--os-version does not match any downloaded image (exact string required).")),console.log(re("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${r}".`)}}var Fc=["Name","Status","Serial","Device Type","OS Version"];function $c(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-",r.osVersion??"-"],highlight:t}}async function _c(r,e){let t=await Promise.all(e.map(async n=>{let i=await Ue(r,n,Nc);return[n,i]}));return new Map(t)}async function Wc(r){let e=await rr(r),t=await _c(r,e);return{serials:e,params:t}}function Uc(r,e,t,n,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function Bc(r,e,t){let n=new Map,i=new Map,o=[...r],s=[...t];for(let a of r){let c=e.get(a),d=c?.get("ohos.qemu.hvd.name");d&&i.set(d,a),t.length>0&&Uc(a,c,s,o,n)}for(let a=0;a<s.length&&a<o.length;a++)n.set(s[a],o[a]);return{productSerialMap:n,hvdSerialMap:i}}function zc(r,e,t){let n=r.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return n.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),n.map(i=>$c(i.emu,i.serial,i.effectiveRunning))}async function Vc(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),Wc(e)]);if(n.length===0){t?.stop(),console.log(re(" No emulator instances found.")),console.log(Je(" You can create an emulator in DevEco Studio."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=Bc(i.serials,i.params,o);t?.stop();let c=zc(n,s,a);console.log(ft(Fc,c))}catch(n){$t(t,`Failed to list emulators: ${n.message}`)}}function eo(r,e,t){let n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(o.status!=="rejected")continue;n=!0;let s=o.reason;console.error(z(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Je(s.stdout)),s.stderr&&console.error(Je(s.stderr))}return n}var qc=2e3,Yc=6e4;async function Gc(r,e){let t=H(e);return(await ir(r)).some(i=>H(i)===t)}async function to(r,e,t,n=Yc,i=qc){let o=Date.now()+n;for(;Date.now()<o;){if(await Gc(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function Jc(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(re(`Emulator "${t}" is already running.`));return}console.log(Ge(`Starting emulator "${t}"...`));let i=await to(e,t,!0);console.log(i?Wt(`Emulator "${t}" started successfully.`):re(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Kc(r,e,t){let n=await Promise.allSettled(t.map(o=>Jc(r,e,o)));eo(n,t,"start")&&process.exit(1)}async function Zc(r,e){let t=e.trim();if(!ht(t))return t;let n=await B.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function Xc(r,e,t){let n=await Zc(e,t);if(console.log(Ge(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(re(`Emulator "${n}" is already stopped.`));return}let o=await to(e,n,!1);console.log(o?Wt(`Emulator "${n}" stopped successfully!`):re(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the timeout.`))}async function Qc(r,e,t){let n=await Promise.allSettled(t.map(o=>Xc(r,e,o)));eo(n,t,"stop")&&process.exit(1)}async function ie(){try{let r=await O.new();return{manager:qe.from(r),toolProvider:r}}catch(r){console.error(z(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var be=new hr("emulator").description("Manage emulator instances"),el=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Ut(r){let e=new Qi("--device-type <type>","Emulator device type").choices([...el]);return r?e.makeOptionMandatory():e}function Ye(r,e){for(let t of e)if(t in r)return r[t]}function mt(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function Xi(r){let e=mt(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var tl=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],nl="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function no(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function ro(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=mt(Ye(i,["osVersion","OsVersion","OSVersion","os_version"])),s=mt(Ye(i,["deviceType","DeviceType","device_type"])),a=Xi(Ye(i,["downloaded","Downloaded","isDownloaded"])),c=mt(Ye(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=mt(Ye(i,["releaseType","ReleaseType","release_type"])),u=Xi(Ye(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function rl(r){let e=r.trim();if(!e)return!0;let t=no(e);return t===null?!1:t.length===0?!0:ro(t,!0).length===0}function il(r,e){let t=r.trim();if(!t)return"";let n=no(t);if(!n)return r.trimEnd();let i=ro(n,e);return ft(tl,i)}var Bt=new hr("image").description("HarmonyOS emulator system images (download, list, remove)");Bt.command("download").description("Download a system image").addOption(Ut(!1)).option("--os-version <version>","e.g. HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let{manager:e,toolProvider:t}=await ie();try{await Ji(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof Z&&(console.error(z(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(z("error: required option '--device-type <type>' not specified")),process.exit(1)),r.osVersion?.trim()||(console.error(z("error: required option '--os-version <version>' not specified")),process.exit(1));try{await e.installEmulatorImage({deviceType:r.deviceType.trim(),osVersion:r.osVersion.trim(),force:r.force===!0})}catch(n){console.error(z(`Failed to download system image: ${n.message}`)),process.exit(1)}});Bt.command("remove").description("Remove a downloaded system image").addOption(Ut(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await ie();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(z(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Bt.command("list").description("List system images").addOption(Ut(!1)).option("--all","List all images (downloaded and not downloaded)").addOption(new Qi("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await ie();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(rl(n)){console.log(re(nl));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=il(n,r.all===!0);console.log(i)}catch(t){console.error(z(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});be.addCommand(Bt);var fr=new hr("license").description("HarmonyOS local emulator license");fr.command("view").description("review the agreement text (read-only)").action(async()=>{let{toolProvider:r}=await ie(),e=await Ki(r.emulatorPath,r.sdkPath);process.exit(e)});fr.command("accept").description("review and accept the agreements").action(async()=>{let{toolProvider:r}=await ie(),e=await Zi(r.emulatorPath,r.sdkPath);process.exit(e)});be.addCommand(fr);be.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await ie(),t=Oc({text:"Listing emulators\u2026",color:"cyan"}).start();await Vc(r,e.hdcPath,t)});be.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await ie();try{await Gi(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof Z&&(console.error(z(n.message)),process.exit(1)),n}r?.length||(console.error(z("error: missing required argument 'names'")),process.exit(1)),await Kc(e,t.hdcPath,r)});be.command("stop <names...>").description("Stop one or more emulator instances (by name or 127.0.0.1:<port> serial)").action(async r=>{let{manager:e,toolProvider:t}=await ie();r?.length||(console.error(z("error: missing required argument 'names'")),process.exit(1)),await Qc(e,t.hdcPath,r)});var io=be.command("create <name>").description("Create a local emulator. Runs emulator -create <name> \u2026; --os-version must match a downloaded image from `emulator image list`.").addOption(Ut(!0)).requiredOption("--os-version <version>",'Exact downloaded image label. Quote in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or use --os-version="\u2026"; see `devecocli emulator image list`').option("--force","Overwrite if the tool supports it");io.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
1217
- ${re("Tip: ")}${Je("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1216
+ `:""),"utf8")}async function Vc(r){await be.mkdir(Me.dirname(r),{recursive:!0});let e="";try{e=await be.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Uc(r,e,t)||await Bc(r,e)}async function ro(r,e){return console.log(mr),0}var zc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function io(r,e){if(console.log(mr),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let n=kc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(zc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Wc(r,e);await Vc(s),Mc()}catch(s){return console.error(s.message),1}return 0}var Yc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Gc(r){let e=r.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Jc(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${r}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function Kc(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(ie("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ie("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)===n)){console.error(z("--os-version does not match any downloaded image (exact string required).")),console.log(ie("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${r}".`)}}var Xc=["Name","Status","Serial","Device Type","OS Version"];function Zc(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-",r.osVersion??"-"],highlight:t}}async function Qc(r,e){let t=await Promise.all(e.map(async n=>{let i=await Ue(r,n,Yc);return[n,i]}));return new Map(t)}async function el(r){let e=await lr(r),t=await Qc(r,e);return{serials:e,params:t}}function tl(r,e,t,n,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function nl(r,e,t){let n=new Map,i=new Map,o=[...r],s=[...t];for(let a of r){let c=e.get(a),d=c?.get("ohos.qemu.hvd.name");d&&i.set(d,a),t.length>0&&tl(a,c,s,o,n)}for(let a=0;a<s.length&&a<o.length;a++)n.set(s[a],o[a]);return{productSerialMap:n,hvdSerialMap:i}}function rl(r,e,t){let n=r.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return n.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),n.map(i=>Zc(i.emu,i.serial,i.effectiveRunning))}async function il(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),el(e)]);if(n.length===0){t?.stop(),console.log(ie(" No emulator instances found."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=nl(i.serials,i.params,o);t?.stop();let c=rl(n,s,a);console.log(mt(Xc,c))}catch(n){zt(t,`Failed to list emulators: ${n.message}`)}}function ao(r,e,t){let n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(o.status!=="rejected")continue;n=!0;let s=o.reason;console.error(z(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(yt(s.stdout)),s.stderr&&console.error(yt(s.stderr))}return n}var ol=2e3,sl=6e4;async function al(r,e){let t=H(e);return(await dr(r)).some(i=>H(i)===t)}async function co(r,e,t,n=sl,i=ol){let o=Date.now()+n;for(;Date.now()<o;){if(await al(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function cl(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(ie(`Emulator "${t}" is already running.`));return}console.log(Ge(`Starting emulator "${t}"...`));let i=await co(e,t,!0);console.log(i?Yt(`Emulator "${t}" started successfully.`):ie(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function ll(r,e,t){let n=await Promise.allSettled(t.map(o=>cl(r,e,o)));ao(n,t,"start")&&process.exit(1)}async function dl(r,e){let t=e.trim();if(!ft(t))return t;let n=await V.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function ul(r,e,t){let n=await dl(e,t);if(console.log(Ge(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(ie(`Emulator "${n}" is already stopped.`));return}let o=await co(e,n,!1);console.log(o?Yt(`Emulator "${n}" stopped successfully.`):ie(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function pl(r,e,t){let n=await Promise.allSettled(t.map(o=>ul(r,e,o)));ao(n,t,"stop")&&process.exit(1)}async function oe(){try{let r=await O.new();return{manager:qe.from(r),toolProvider:r}}catch(r){console.error(z(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var Se=new wr("emulator").description("Manage emulator instances"),hl=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Gt(r){let e=new so("--device-type <type>","Emulator device type").choices([...hl]);return r?e.makeOptionMandatory():e}function Ye(r,e){for(let t of e)if(t in r)return r[t]}function gt(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function oo(r){let e=gt(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var fl=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],ml="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function lo(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function uo(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=gt(Ye(i,["osVersion","OsVersion","OSVersion","os_version"])),s=gt(Ye(i,["deviceType","DeviceType","device_type"])),a=oo(Ye(i,["downloaded","Downloaded","isDownloaded"])),c=gt(Ye(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=gt(Ye(i,["releaseType","ReleaseType","release_type"])),u=oo(Ye(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function gl(r){let e=r.trim();if(!e)return!0;let t=lo(e);return t===null?!1:t.length===0?!0:uo(t,!0).length===0}function yl(r,e){let t=r.trim();if(!t)return"";let n=lo(t);if(!n)return r.trimEnd();let i=uo(n,e);return mt(fl,i)}var Jt=new wr("image").description("HarmonyOS emulator system images (download, list, remove)");Jt.command("download").description("Download system image").addOption(Gt(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let{manager:e,toolProvider:t}=await oe();try{await no(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof Z&&(console.error(z(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(z("Error: missing required option '--device-type <type>'")),process.exit(1)),r.osVersion?.trim()||(console.error(z("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:r.deviceType.trim(),osVersion:r.osVersion.trim(),force:r.force===!0})}catch(n){console.error(z(`Failed to download system image: ${n.message}`)),process.exit(1)}});Jt.command("remove").description("Remove a downloaded system image").addOption(Gt(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await oe();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(z(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Jt.command("list").description("List system images").addOption(Gt(!1)).option("--all","List all images (local and remote)").addOption(new so("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await oe();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(gl(n)){console.log(ie(ml));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=yl(n,r.all===!0);console.log(i)}catch(t){console.error(z(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Se.addCommand(Jt);var br=new wr("license").description("local emulator license");br.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:r}=await oe(),e=await ro(r.emulatorPath,r.sdkPath);process.exit(e)});br.command("accept").description("review and accept agreements").action(async()=>{let{toolProvider:r}=await oe(),e=await io(r.emulatorPath,r.sdkPath);process.exit(e)});Se.addCommand(br);Se.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await oe(),t=qc({text:"Listing emulators\u2026",color:"cyan"}).start();await il(r,e.hdcPath,t)});Se.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await oe();try{await to(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof Z&&(console.error(z(n.message)),process.exit(1)),n}r?.length||(console.error(z("Error: missing required argument 'names'")),process.exit(1)),await ll(e,t.hdcPath,r)});Se.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async r=>{let{manager:e,toolProvider:t}=await oe();r?.length||(console.error(z("Error: missing required argument 'names'")),process.exit(1)),await pl(e,t.hdcPath,r)});var po=Se.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(Gt(!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");po.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
1217
+ ${ie("Tip: ")}${yt("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
1218
1218
  ${Ge('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
1219
1219
  ${Ge('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
1220
- `)}});io.action(async(r,e)=>{try{Lc(r),Hc(e.osVersion);let{manager:t}=await ie(),n=await t.listDownloadedImageOsVersions();jc(e.osVersion,n),console.log(Ge(`Creating emulator "${r}"...`)),await t.createVirtualDevice({name:r,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Wt(`Emulator "${r}" created successfully.`))}catch(t){console.error(z(`${t.message}`)),process.exit(1)}});be.command("delete <name>").description("Delete a local emulator instance").action(async r=>{let{manager:e}=await ie();console.log(Ge(`Deleting emulator "${r}"...`));try{let t=await e.deleteVirtualDevice(r);console.log(Wt(`Emulator "${t}" deleted successfully.`))}catch(t){let n=t;console.error(z(n.message)),n.stdout&&console.error(Je(n.stdout)),n.stderr&&console.error(Je(n.stderr)),process.exit(1)}});var oo=be;import{Command as wl}from"commander";import{green as bl,red as bt,cyan as xo,yellow as Ro,dim as Oo}from"colorette";import Sl from"p-limit";import ol from"ora";var xe=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=ol(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 lo from"fs";import*as uo from"path";import{homedir as al}from"os";import sl from"axios";var mr={HTTP_TIMEOUT_MS:2e4},zt={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 gr="https://matrix.openharmony.cn",X={TAGS_API_URL:`${gr}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${gr}/api/registry/skill/skills`,SKILL_API_BASE:`${gr}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},de={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as Se}from"os";import oe from"path";var se="deveco-mcp";var Pe={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:oe.join(Se(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:oe.join(Se(),".config","trae-cn","mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:oe.join(Se(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:oe.join(Se(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:oe.join(process.platform==="win32"?oe.join(process.env.APPDATA??oe.join(Se(),"AppData","Roaming"),"Qoder","SharedClientCache"):oe.join(Se(),"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:oe.join(Se(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:oe.join(Se(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function ao(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function so(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function co(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function Vt(r,e){return r.format==="opencode"?ao(e):r.format==="claude-code"||r.format==="codex"?so(e):co(e)}var yr=class{client;constructor(){let e={timeout:mr.HTTP_TIMEOUT_MS,headers:{"User-Agent":zt.USER_AGENT,"accept-language":zt.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=sl.create(e),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1221
- ${n}`)})}async get(e,t){let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}async post(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}},Ee=new yr;async function qt(){let r=await Ee.get(X.TAGS_API_URL),t=Yt(r,"Tags API").data.skill.filter(n=>n.name==="HMOS"||n.name==="DevEco");if(t.length===0)throw new Error("No HMOS or DevEco tags found");return t.map(n=>n.id)}async function cl(r){let e=[],t=X.DEFAULT_PAGE_SIZE,n=1;for(;;){let i=await Ee.post(X.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:n,pageSize:t,tagIds:[r]}}),o=Yt(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;n++}return e}async function vr(r){let e=new Map,t=r.map(i=>cl(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values())}async function ll(r,e){let t=await Ee.post(X.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:X.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return Yt(t,"Skills API").data.list}async function wr(r,e){let t=new Map,n=e.map(o=>ll(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values())}function po(r){let e=[];for(let[,t]of Object.entries(de)){let n=uo.join(al(),t.path,r);lo.existsSync(n)&&e.push(t.displayName)}return e.sort()}function Yt(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=Ee.parseJson(r);if(t.code!==X.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function ho(r){let e=`${X.SKILL_API_BASE}/${r}/checksum`,t=await Ee.get(e);return Yt(t,"Checksum API").data}import dl from"adm-zip";import ul from"crypto";import mo from"fs";import R from"path";import{fileURLToPath as pl}from"url";import{homedir as go}from"os";import{red as hl}from"colorette";var ue=mo.promises;function br(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function fo(r,e){let t=R.resolve(e),n=R.resolve(r),i=R.relative(n,t);if(i.startsWith("..")||R.isAbsolute(i))throw new Error(`Path escape detected: ${e}`)}function Sr(r){return R.isAbsolute(r)?r:R.resolve(process.cwd(),r)}function fl(r){return ul.createHash("sha256").update(r).digest("hex")}async function ml(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=fl(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function yo(r){let e=`${X.SKILL_API_BASE}/${r}/install?format=zip`,t=await Ee.getBinary(e),n=await ho(r);return await ml(t,n),t}async function gl(r,e,t){br(t);let n=new dl(r),i=n.getEntries();try{await ue.stat(e)}catch{await ue.mkdir(e,{recursive:!0})}let o=R.join(e,t);fo(e,o);for(let s of i){let a=R.join(o,s.entryName);fo(o,a)}n.extractAllTo(o,!0)}async function Pr(r){let e=de[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(de).join(", ")}`);let t=R.join(go(),e.path.replace("/skills",""));try{return await ue.access(t),!0}catch{return!1}}function Er(r){let e=de[r];return R.join(go(),e.path)}function Dr(r,e){return R.join(r,"."+e,"skills")}async function yl(r,e,t){br(e);let n=R.join(r,e);try{if(await ue.access(n),t)await ue.rm(n,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${r}`),{skillDir:n,shouldSkip:!0}}catch{}return{skillDir:n,shouldSkip:!1}}async function Ir(r,e,t){await gl(r,e,t),console.log(`Skill ${t} installed to ${R.join(e,t)}`)}async function Cr(r,e,t){let n=R.join(e,t);await ue.mkdir(n,{recursive:!0});let i=R.join(n,R.basename(r));await ue.copyFile(r,i),console.log(`Skill ${t} installed to ${n}`)}function vo(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(hl(`Skill ${r} operation failed - ${n}`)),{success:!1,error:n}}async function Ke(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await yl(i,r,n);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return vo(r,i,"Installation failed")}}async function Ar(r,e){try{br(r);let t=await e(),n=R.join(t,r);try{await ue.access(n)}catch{return console.log(`Skill ${r} does not exist in ${t}`),{success:!0,skipped:!0}}return await ue.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}`),{success:!0}}catch(t){return vo(r,t,"Removal failed")}}async function wo(r,e,t,n=!1){return Ke(r,()=>Er(e),i=>Ir(t,i,r),n)}async function bo(r,e,t,n=!1){return Ke(r,()=>t,i=>Ir(e,i,r),n)}async function So(r,e,t,n,i=!1){return Ke(r,()=>Dr(t,n),o=>Ir(e,o,r),i)}async function Po(r,e,t,n=!1){return Ke(r,()=>Er(t),i=>Cr(e,i,r),n)}async function Eo(r,e,t,n,i=!1){return Ke(r,()=>Dr(t,n),o=>Cr(e,o,r),i)}async function Do(r,e,t,n=!1){return Ke(r,()=>t,i=>Cr(e,i,r),n)}async function Io(r,e){return Ar(r,()=>Er(e))}async function Co(r,e){return Ar(r,()=>e)}async function Ao(r,e,t){return Ar(r,()=>Dr(e,t))}function ko(){let e=R.dirname(pl(import.meta.url));for(;;){let t=R.join(e,"SKILL.md");if(mo.existsSync(t))return t;let n=R.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package; please reinstall deveco-cli.")}import To from"fs";import{cyan as vl}from"colorette";async function gt(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await Pr(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function yt(){let r=[];for(let e of Object.keys(de))await Pr(e)&&r.push(e);return r}function vt(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(vl("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function De(r,e,t){if(!To.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!To.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function wt(r,e,t){if(r&&(e||t))throw new Error("Cannot use --path with --project or --agent");return{resolvedPath:r?Sr(r):void 0,resolvedProject:e?Sr(e):void 0}}async function Gt(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await gt(r.agent)).map(a=>({project:t,agent:a})):t?i=(await yt()).map(a=>({project:t,agent:a})):r.agent?n=await gt(r.agent):n=await yt(),!o&&n.length===0&&i.length===0)throw new Error("No agents found. Please install an AI agent (cursor, opencode, etc.) or use --path for a custom location.");return{agents:n,projectAgents:i,customPath:o}}async function Pl(r){let e=await qt();if(r.all)return(await vr(e)).map(n=>n.enName);{let n=(await wr(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function El(r,e,t,n){let i=[];if(t.customPath){let o=await bo(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await wo(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await So(r,e,o,s,n);i.push(a)}return i}function Dl(r){if(r.all&&r.skill)throw new Error("--all and --skill cannot be specified together");if(!r.all&&!r.skill)throw new Error("Must specify --all or --skill");let{resolvedPath:e,resolvedProject:t}=wt(r.path,r.project,r.agent);return t&&De(t,"Project directory",r.force),e&&De(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function Il(r,e,t){let n=await Gt(r,e,t);return{skillNames:await Pl(r),targets:n}}async function Cl(r,e,t,n){let i=[],o=r.length,s=Sl(5),a=r.map(async c=>s(async()=>{try{let d=await yo(c);return{name:c,buffer:d,success:!0}}catch(d){let u=d instanceof Error?d.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<r.length;c++){let d=r[c],u=o>1?` (${c+1}/${o})`:"";n.start(`Installing ${d}${u}...`);let b=await a[c];if(!b.success){n.fail(),console.log(bt(`${d}: Download failed - ${b.error}`)),i.push({success:!1});continue}n.stop();let k=await El(d,b.buffer,e,t);i.push(...k)}return i}async function Al(r){let e=new xe;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=Dl(r),{skillNames:i,targets:o}=await Il(r,t,n),s=await Cl(i,o,r.force||!1,e);e.stop(),vt(s)}catch(t){throw e.stop(),t}}function kl(r){let{resolvedPath:e,resolvedProject:t}=wt(r.path,r.project,r.agent);return t&&De(t,"Project directory"),e&&De(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Tl(r,e){let t=new xe;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=kl(e);t.stop();let o=await Ml(e,r,n,i);t.stop(),vt(o)}catch(n){throw t.stop(),n}}function Mo(r,e=""){if(r.length===0)throw new Error(`No agents found. Please install an AI agent (cursor, opencode, etc.) ${e}`)}async function Jt(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await Io(r,n.agent):await Ao(r,n.project,n.agent);t.push(i)}return t}async function Ml(r,e,t,n){if(t)return[await Co(e,t)];if(n&&r.agent){let a=(await gt(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return Jt(e,a)}if(n){let s=await yt();Mo(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return Jt(e,a)}if(r.agent){let a=(await gt(r.agent)).map(c=>({type:"agent",agent:c}));return Jt(e,a)}let i=await yt();Mo(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Jt(e,o)}var St=new wl("skills").description("Manage HarmonyOS skills");St.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new xe;try{e.start("Fetching skills...");let t=await qt(),n=await vr(t);if(n.length===0){e.stop(),console.log(Ro("No skills available"));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(xo(i.enName)),console.log(Oo(i.description));let o=po(i.enName);o.length>0&&console.log(bl(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(bt(t.message)),process.exit(1)}});St.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new xe;try{e.start("Searching skills...");let t=await qt(),n=await wr(r,t);if(n.length===0){console.log(Ro(`No skills found matching '${r}'`)),e.stop();return}e.succeed(`Found ${n.length} skills`);for(let i of n)console.log(xo(i.enName)),console.log(Oo(i.description)),console.log()}catch(t){e.stop(),console.error(bt(t.message)),process.exit(1)}});St.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory to install the skill into").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await Al(r)}catch(e){console.error(bt(e.message)),process.exit(1)}});St.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; removes from all available agents if omitted").option("--project <path>","Project root directory to remove the skill from").option("--path <path>","Path to remove the skill from").action(async r=>{try{await Tl(r.skill,r)}catch(e){console.error(bt(e.message)),process.exit(1)}});var No=St;import{Command as Rl,InvalidArgumentError as Ho}from"commander";import{cyan as Kt}from"colorette";function Re(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=We(t);return n==="transient"?new Error(`${e}: device communication channel is not ready yet. Please retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var kr=[800,1500,2500];function xl(r){return new Promise(e=>setTimeout(e,r))}var Zt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}createFollowLineHandler(e){return(t,n)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(n!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1222
- `)}async loadConnectedDevicesByName(){let e=await this.getConnectedDevices();if(e)return e}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!t)return;if(!e&&t.length===1){let i=t[0];return w(Kt(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return w(Kt(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(n){if(e){let i=this.findDeviceByArg(n,e);if(i)return w(Kt(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(n);throw new Error(`Device '${e}' not found.
1220
+ `)}});po.action(async(r,e)=>{try{Gc(r),Jc(e.osVersion);let{manager:t}=await oe(),n=await t.listDownloadedImageOsVersions();Kc(e.osVersion,n),console.log(Ge(`Creating emulator "${r}"...`)),await t.createVirtualDevice({name:r,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Yt(`Emulator "${r}" created successfully.`))}catch(t){console.error(z(`${t.message}`)),process.exit(1)}});Se.command("delete <name>").description("Delete a local emulator instance").action(async r=>{let{manager:e}=await oe();console.log(Ge(`Deleting emulator "${r}"...`));try{let t=await e.deleteVirtualDevice(r);console.log(Yt(`Emulator "${t}" deleted successfully.`))}catch(t){let n=t;console.error(z(n.message)),n.stdout&&console.error(yt(n.stdout)),n.stderr&&console.error(yt(n.stderr)),process.exit(1)}});var ho=Se;import{Command as xl}from"commander";import{green as Ol,red as Pt,cyan as Fo,yellow as $o,dim as _o}from"colorette";import Nl from"p-limit";import vl from"ora";var Re=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=vl(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 yo from"fs";import*as vo from"path";import{homedir as bl}from"os";import wl from"axios";var Sr={HTTP_TIMEOUT_MS:2e4},Kt={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 Pr="https://matrix.openharmony.cn",Q={TAGS_API_URL:`${Pr}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Pr}/api/registry/skill/skills`,SKILL_API_BASE:`${Pr}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},de={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as ue}from"os";import G from"path";var se="deveco-mcp";var Pe={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:G.join(ue(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:G.join(process.platform==="win32"?G.join(process.env.APPDATA??G.join(ue(),"AppData","Roaming"),"Trae CN","User"):G.join(ue(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:G.join(ue(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:G.join(ue(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:G.join(process.platform==="win32"?G.join(process.env.APPDATA??G.join(ue(),"AppData","Roaming"),"Qoder","SharedClientCache"):G.join(ue(),"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:G.join(ue(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:G.join(ue(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function mo(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function fo(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function go(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function Xt(r,e){return r.format==="opencode"?mo(e):r.format==="claude-code"||r.format==="codex"?fo(e):go(e)}var Er=class{client;constructor(){let e={timeout:Sr.HTTP_TIMEOUT_MS,headers:{"User-Agent":Kt.USER_AGENT,"accept-language":Kt.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=wl.create(e),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
1221
+ ${n}`)})}async get(e,t){let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}async post(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}},Ee=new Er;async function Zt(){let r=await Ee.get(Q.TAGS_API_URL),t=Qt(r,"Tags API").data.skill.filter(n=>n.name==="HMOS"||n.name==="DevEco");if(t.length===0)throw new Error("No HMOS or DevEco tags found.");return t.map(n=>n.id)}async function Sl(r){let e=[],t=Q.DEFAULT_PAGE_SIZE,n=1;for(;;){let i=await Ee.post(Q.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:n,pageSize:t,tagIds:[r]}}),o=Qt(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;n++}return e}async function Cr(r){let e=new Map,t=r.map(i=>Sl(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values())}async function Pl(r,e){let t=await Ee.post(Q.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Q.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return Qt(t,"Skills API").data.list}async function Dr(r,e){let t=new Map,n=e.map(o=>Pl(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values())}function wo(r){let e=[];for(let[,t]of Object.entries(de)){let n=vo.join(bl(),t.path,r);yo.existsSync(n)&&e.push(t.displayName)}return e.sort()}function Qt(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=Ee.parseJson(r);if(t.code!==Q.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function bo(r){let e=`${Q.SKILL_API_BASE}/${r}/checksum`,t=await Ee.get(e);return Qt(t,"Checksum API").data}import El from"adm-zip";import Cl from"crypto";import Po from"fs";import x from"path";import{fileURLToPath as Dl}from"url";import{homedir as Eo}from"os";import{red as Il}from"colorette";var pe=Po.promises;function Ir(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function So(r,e){let t=x.resolve(e),n=x.resolve(r),i=x.relative(n,t);if(i.startsWith("..")||x.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Ar(r){return x.isAbsolute(r)?r:x.resolve(process.cwd(),r)}function Al(r){return Cl.createHash("sha256").update(r).digest("hex")}async function kl(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=Al(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Co(r){let e=`${Q.SKILL_API_BASE}/${r}/install?format=zip`,t=await Ee.getBinary(e),n=await bo(r);return await kl(t,n),t}async function Tl(r,e,t){Ir(t);let n=new El(r),i=n.getEntries();try{await pe.stat(e)}catch{await pe.mkdir(e,{recursive:!0})}let o=x.join(e,t);So(e,o);for(let s of i){let a=x.join(o,s.entryName);So(o,a)}n.extractAllTo(o,!0)}async function kr(r){let e=de[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(de).join(", ")}`);let t=x.join(Eo(),e.path.replace("/skills",""));try{return await pe.access(t),!0}catch{return!1}}function Tr(r){let e=de[r];return x.join(Eo(),e.path)}function Mr(r,e){return x.join(r,"."+e,"skills")}async function Ml(r,e,t){Ir(e);let n=x.join(r,e);try{if(await pe.access(n),t)await pe.rm(n,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${r}.`),{skillDir:n,shouldSkip:!0}}catch{}return{skillDir:n,shouldSkip:!1}}async function Rr(r,e,t){await Tl(r,e,t),console.log(`Skill ${t} installed to ${x.join(e,t)}.`)}async function xr(r,e,t){let n=x.join(e,t);await pe.mkdir(n,{recursive:!0});let i=x.join(n,x.basename(r));await pe.copyFile(r,i),console.log(`Skill ${t} installed to ${n}.`)}function Do(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(Il(`Faild to exute operation for skill "${r}": ${n}`)),{success:!1,error:n}}async function Je(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await Ml(i,r,n);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Do(r,i,"Installation failed")}}async function Or(r,e){try{Ir(r);let t=await e(),n=x.join(t,r);try{await pe.access(n)}catch{return console.log(`Skill ${r} not found in ${t}`),{success:!0,skipped:!0}}return await pe.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}.`),{success:!0}}catch(t){return Do(r,t,"Removal failed")}}async function Io(r,e,t,n=!1){return Je(r,()=>Tr(e),i=>Rr(t,i,r),n)}async function Ao(r,e,t,n=!1){return Je(r,()=>t,i=>Rr(e,i,r),n)}async function ko(r,e,t,n,i=!1){return Je(r,()=>Mr(t,n),o=>Rr(e,o,r),i)}async function To(r,e,t,n=!1){return Je(r,()=>Tr(t),i=>xr(e,i,r),n)}async function Mo(r,e,t,n,i=!1){return Je(r,()=>Mr(t,n),o=>xr(e,o,r),i)}async function Ro(r,e,t,n=!1){return Je(r,()=>t,i=>xr(e,i,r),n)}async function xo(r,e){return Or(r,()=>Tr(e))}async function Oo(r,e){return Or(r,()=>e)}async function No(r,e,t){return Or(r,()=>Mr(e,t))}function Lo(){let e=x.dirname(Dl(import.meta.url));for(;;){let t=x.join(e,"SKILL.md");if(Po.existsSync(t))return t;let n=x.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Ho from"fs";import{cyan as Rl}from"colorette";async function vt(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await kr(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function wt(){let r=[];for(let e of Object.keys(de))await kr(e)&&r.push(e);return r}function bt(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(Rl("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Ce(r,e,t){if(!Ho.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!Ho.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function St(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?Ar(r):void 0,resolvedProject:e?Ar(e):void 0}}async function en(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await vt(r.agent)).map(a=>({project:t,agent:a})):t?i=(await wt()).map(a=>({project:t,agent:a})):r.agent?n=await vt(r.agent):n=await wt(),!o&&n.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:n,projectAgents:i,customPath:o}}async function Ll(r){let e=await Zt();if(r.all)return(await Cr(e)).map(n=>n.enName);{let n=(await Dr(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function Hl(r,e,t,n){let i=[];if(t.customPath){let o=await Ao(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await Io(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await ko(r,e,o,s,n);i.push(a)}return i}function jl(r){if(r.all&&r.skill)throw new Error("`--all` and `--skill` cannot be specified together.");if(!r.all&&!r.skill)throw new Error("Must specify `--all` or `--skill`");let{resolvedPath:e,resolvedProject:t}=St(r.path,r.project,r.agent);return t&&Ce(t,"Project directory",r.force),e&&Ce(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function Fl(r,e,t){let n=await en(r,e,t);return{skillNames:await Ll(r),targets:n}}async function $l(r,e,t,n){let i=[],o=r.length,s=Nl(5),a=r.map(async c=>s(async()=>{try{let d=await Co(c);return{name:c,buffer:d,success:!0}}catch(d){let u=d instanceof Error?d.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<r.length;c++){let d=r[c],u=o>1?` (${c+1}/${o})`:"";n.start(`Installing ${d}${u}...`);let v=await a[c];if(!v.success){n.fail(),console.log(Pt(`${d}: Download failed - ${v.error}`)),i.push({success:!1});continue}n.stop();let D=await Hl(d,v.buffer,e,t);i.push(...D)}return i}async function _l(r){let e=new Re;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=jl(r),{skillNames:i,targets:o}=await Fl(r,t,n),s=await $l(i,o,r.force||!1,e);e.stop(),bt(s)}catch(t){throw e.stop(),t}}function Wl(r){let{resolvedPath:e,resolvedProject:t}=St(r.path,r.project,r.agent);return t&&Ce(t,"Project directory"),e&&Ce(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Ul(r,e){let t=new Re;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=Wl(e);t.stop();let o=await Bl(e,r,n,i);t.stop(),bt(o)}catch(n){throw t.stop(),n}}function jo(r,e=""){if(r.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function tn(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await xo(r,n.agent):await No(r,n.project,n.agent);t.push(i)}return t}async function Bl(r,e,t,n){if(t)return[await Oo(e,t)];if(n&&r.agent){let a=(await vt(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return tn(e,a)}if(n){let s=await wt();jo(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return tn(e,a)}if(r.agent){let a=(await vt(r.agent)).map(c=>({type:"agent",agent:c}));return tn(e,a)}let i=await wt();jo(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return tn(e,o)}var Et=new xl("skills").description("Manage HarmonyOS skills");Et.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new Re;try{e.start("Fetching skills...");let t=await Zt(),n=await Cr(t);if(n.length===0){e.stop(),console.log($o("No skills available."));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(Fo(i.enName)),console.log(_o(i.description));let o=wo(i.enName);o.length>0&&console.log(Ol(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(Pt(t.message)),process.exit(1)}});Et.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new Re;try{e.start("Searching skills...");let t=await Zt(),n=await Dr(r,t);if(n.length===0){console.log($o(`No skills found matching '${r}'.`)),e.stop();return}e.succeed(`Found ${n.length} skills.`);for(let i of n)console.log(Fo(i.enName)),console.log(_o(i.description)),console.log()}catch(t){e.stop(),console.error(Pt(t.message)),process.exit(1)}});Et.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await _l(r)}catch(e){console.error(Pt(e.message)),process.exit(1)}});Et.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async r=>{try{await Ul(r.skill,r)}catch(e){console.error(Pt(e.message)),process.exit(1)}});var Wo=Et;import{Command as zl,InvalidArgumentError as Bo}from"commander";import{cyan as nn}from"colorette";function xe(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=We(t);return n==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Nr=[800,1500,2500];function Vl(r){return new Promise(e=>setTimeout(e,r))}var rn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=V.from(e)}createFollowLineHandler(e){return(t,n)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(n!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
1222
+ `)}async loadConnectedDevicesByName(){let e=await this.getConnectedDevices();if(e)return e}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!t)return;if(!e&&t.length===1){let i=t[0];return w(nn(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return w(nn(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(n){if(e){let i=this.findDeviceByArg(n,e);if(i)return w(nn(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(n);throw new Error(`Device '${e}' not found.
1223
1223
  Available devices:
1224
- ${o}`)}if(n.length===1){let i=n[0];return w(Kt(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Please specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(n))}}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,n){w(`Trying to get PID for bundle: ${n}`),E.assertBundleName(n);let i=await ve(e,["-t",t,"shell","pidof",n]),o=Re(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 w(`Found PID for ${n}: ${a}`),a}return w(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){w(`Setting hilog buffer size to: ${n}`);let i=await ve(e,["-t",t,"shell","hilog","-G",n]),o=Re(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,n,i){let o=this.buildHilogShellCommand(n,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let n=["hilog"];return e.isFollow||n.push("-x"),e.tag&&(E.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(E.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(E.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(E.assertHilogKeyword(e.keyword),n.push("-e",E.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,i,o){let a=await vi(e,t,{onData:n,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,n,i,o){let s=1+kr.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){a=await this.followHilog(e,t,n,i,o);let d=a.exitCode===0?a.stdout:a.stderr||a.stdout;if(We(d)!=="transient"||c>=s-1)return a;w(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${kr[c]}ms`),await xl(kr[c])}return a}async printTailSnapshotIfNeeded(e,t,n,i){if(!n.tail&&!n.fromSeconds&&!n.toSeconds)return;let o={...n,isFollow:!1},[,s]=this.buildHilogCommand(e,t,o,i),a=await ve(e,s),c=Re(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 d=E.filterLogsByRelativeWindow(a.stdout||a.stderr,n.fromSeconds,n.toSeconds);d=E.getLastLines(d,n.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,n,i){let[o,s]=this.buildHilogCommand(e,t,n,i);w(`Ready to execute hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,()=>{},b=>{w(`hilog once stream error callback: ${b.message}`)},()=>{}),c=Re(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 d=a.stdout||a.stderr,u=E.filterLogsByRelativeWindow(d,n.fromSeconds,n.toSeconds);return u=E.getLastLines(u,n.tail),u}async runHilogFollow(e,t,n,i){await this.printTailSnapshotIfNeeded(e,t,n,i);let[o,s]=this.buildHilogCommand(e,t,n,i);w(`Ready to execute hilog command which contain follow and tail: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(n),d=>{console.error(d.message)},()=>{}),c=Re(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let n=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(n,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Make sure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(n,e,t.logSize),t.isFollow?await this.runHilogFollow(n,e,t,i||""):await this.getHilogOnce(n,e,t,i||"")}async getCrashLog(e,t){w(`Fetching crash logs from device: ${e}`);let n=this.toolProvider.hdcPath,i=await this.listCrashLogs(n,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,d)=>{let u=c.split("-").pop()||"";return(d.split("-").pop()||"").localeCompare(u)})[0],a=await this.fetchCrashLogContent(n,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,n){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];w(`Executing command: ${e} ${i.join(" ")}`);let o=await ve(e,i),s=Re(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 w(`Crash logs list output:
1224
+ ${o}`)}if(n.length===1){let i=n[0];return w(nn(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(n))}}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,n){w(`Retrieving PID for bundle ${n}`),C.assertBundleName(n);let i=await we(e,["-t",t,"shell","pidof",n]),o=xe(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 w(`Found PID for ${n}: ${a}`),a}return w(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){w(`Setting hilog buffer size to: ${n}`);let i=await we(e,["-t",t,"shell","hilog","-G",n]),o=xe(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,n,i){let o=this.buildHilogShellCommand(n,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let n=["hilog"];return e.isFollow||n.push("-x"),e.tag&&(C.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(C.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(C.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(C.assertHilogKeyword(e.keyword),n.push("-e",C.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,i,o){let a=await Di(e,t,{onData:n,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,n,i,o){let s=1+Nr.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){a=await this.followHilog(e,t,n,i,o);let d=a.exitCode===0?a.stdout:a.stderr||a.stdout;if(We(d)!=="transient"||c>=s-1)return a;w(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Nr[c]}ms`),await Vl(Nr[c])}return a}async printTailSnapshotIfNeeded(e,t,n,i){if(!n.tail&&!n.fromSeconds&&!n.toSeconds)return;let o={...n,isFollow:!1},[,s]=this.buildHilogCommand(e,t,o,i),a=await we(e,s),c=xe(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 d=C.filterLogsByRelativeWindow(a.stdout||a.stderr,n.fromSeconds,n.toSeconds);d=C.getLastLines(d,n.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,n,i){let[o,s]=this.buildHilogCommand(e,t,n,i);w(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,()=>{},v=>{w(`Callback triggered when an error occurs during a single hilog streaming read: ${v.message}`)},()=>{}),c=xe(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 d=a.stdout||a.stderr,u=C.filterLogsByRelativeWindow(d,n.fromSeconds,n.toSeconds);return u=C.getLastLines(u,n.tail),u}async runHilogFollow(e,t,n,i){await this.printTailSnapshotIfNeeded(e,t,n,i);let[o,s]=this.buildHilogCommand(e,t,n,i);w(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(n),d=>{console.error(d.message)},()=>{}),c=xe(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let n=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(n,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(n,e,t.logSize),t.isFollow?await this.runHilogFollow(n,e,t,i||""):await this.getHilogOnce(n,e,t,i||"")}async getCrashLog(e,t){w(`Fetching crash logs from device: ${e}`);let n=this.toolProvider.hdcPath,i=await this.listCrashLogs(n,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,d)=>{let u=c.split("-").pop()||"";return(d.split("-").pop()||"").localeCompare(u)})[0],a=await this.fetchCrashLogContent(n,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,n){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];w(`Running command: ${e} ${i.join(" ")}`);let o=await we(e,i),s=xe(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 w(`Crash logs list output:
1225
1225
  ${o.stdout}`),o.stdout.split(`
1226
- `).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return E.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>n?c.toLowerCase().includes(n.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){w(`Fetching latest crash log file: ${n}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];w(`Executing command: ${e} ${i.join(" ")}`);let o=await ve(e,i),s=Re(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash log content: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as Tr,red as jo}from"colorette";import Ol from"ora";function Nl(r){try{return E.parsePositiveInteger(r,"tail")}catch{throw new Ho("tail must be a positive integer")}}function Lo(r,e){try{return E.parseDurationToSeconds(r,e)}catch{throw new Ho(`${e} must be like 30s, 5m or 2.5m (s/m only; seconds/default must be integers)`)}}function Ll(r){if(r.to&&r.follow)throw new Error("--to cannot be used with --follow");E.assertRelativeTimeRange(r.from,r.to)}async function Hl(r,e,t,n,i){return t.crash?await r.getCrashLog(e,t.bundleName):await r.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:n,toSeconds:i})}function jl(r,e,t,n){let i=E.filterLogsByRelativeWindow(r,t,n);return e.tail?E.getLastLines(i,e.tail):i}var Fl=new Rl("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(jo(r))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain the crash log").option("--level <level>","Log level filter: D, I, W, E, F").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",Nl).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Lo(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Lo(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await $l(r)});async function $l(r){let e=Ol({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Ll(r);let n=r.from,i=r.to,o=await O.new(),s=new Zt(o),a=await s.selectDevice(r.device);a||(t(),process.exit(1)),w(Tr(`deviceId: ${a}`)),w(Tr(`type: ${r.crash?"Crash logs":"Common logs"}`)),w(Tr("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await Hl(s,a,r,n,i);t(),r.crash&&c&&(c=jl(c,r,n,i)),c&&console.log(c)}catch(n){t(),console.error(jo(n.message)),process.exit(1)}}var Fo=Fl;import Et from"path";import pe from"fs";import xr from"process";import qo from"os";import{Command as Zl}from"commander";import{green as Uo,red as Mr,cyan as Xl,yellow as Bo}from"colorette";import j from"fs-extra";import T from"path";import*as $o from"os";import{fileURLToPath as _l}from"url";var Wl={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"}},Ul=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function Bl(){let r=import.meta.url,e=_l(r);if(e.includes("dist")){let o=T.dirname(e),s=T.dirname(o);return T.join(s,"templates","application")}let t=T.dirname(e),n=T.dirname(t),i=T.dirname(n);return T.join(i,"templates","application")}function _o(r,e){j.mkdirSync(e,{recursive:!0});for(let t of j.readdirSync(r,{withFileTypes:!0})){let n=T.join(r,t.name),i=T.join(e,t.name);if(t.isDirectory()){_o(n,i);continue}j.existsSync(i)||(j.mkdirSync(T.dirname(i),{recursive:!0}),j.copyFileSync(n,i))}}function Pt(r,e){let t=j.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&j.writeFileSync(r,n,"utf-8")}function zl(r,e){if(e===22)return;let t=Wl[e];t&&(Pt(T.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Pt(T.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Pt(T.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Vl(r){return Ul.filter(t=>!j.existsSync(T.join(r,t))).length===0}function ql(){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 Yl(r){return $o.platform()==="darwin"?T.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):T.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function Gl(r,e){let t=Yl(e);if(!j.existsSync(t))return!1;let n=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of n){let s=T.join(t,i),a=T.join(r,o);j.existsSync(s)&&(j.mkdirSync(T.dirname(a),{recursive:!0}),j.copyFileSync(s,a))}return!0}function Jl(r){let e=ql(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let i=T.join(r,n);j.mkdirSync(T.dirname(i),{recursive:!0}),j.writeFileSync(i,e)}}function Kl(r,e){e&&Gl(r,e)||Jl(r)}function Wo(r,e,t,n,i){let o=Bl();if(!j.existsSync(o))throw new Error(`Template directory not found: ${o}`);j.mkdirSync(r,{recursive:!0}),_o(o,r),Kl(r,i),Pt(T.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Pt(T.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),zl(r,n);let s=Vl(r);if(!s)throw new Error("Template integrity check failed");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function Ql(r){if(r.length<1||r.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error("App name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function ed(r){if(r.length<7||r.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${r.length}`);if(r.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example")');let e=r.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 segments separated by dots");let t=/^[a-zA-Z0-9_]+$/;for(let n=0;n<e.length;n++){let i=e[n];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed`);if(n===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z)`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit`)}}function Yo(r){if(qo.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function zo(r){if(r.length===0)throw new Error("Project path cannot be empty");if(r.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${r.length})`);let e=qo.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(r)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}`)}let n=Yo(r);if(/[\u4e00-\u9fff]/.test(n))throw new Error("Project path cannot contain Chinese characters");if(n.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function td(r){let e=r,t=Et.parse(r).root;for(;e!==t;){if(pe.existsSync(e))return e;e=Et.dirname(e)}return pe.existsSync(t)?t:null}function Vo(r){let e=td(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{pe.accessSync(e,pe.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Et.join(e,`.deveco_write_test_${Date.now()}`);try{pe.writeFileSync(t,"test"),pe.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function nd(r){return`com.example.${r.toLowerCase()}`}function rd(r,e){if(e){let i=Yo(e),o=Et.resolve(i);if(pe.existsSync(o)){if(pe.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project in non-empty directory.`)}else Vo(o);return o}let t=xr.cwd(),n=Et.join(t,r);if(pe.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return Vo(n),n}function id(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let i=Number(r.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API level ${r.apiLevel}. Minimum supported is API 17`);if(t!==void 0){if(i>t)throw new Error(`Invalid API level ${r.apiLevel}. Your SDK supports API 17-${t}`)}else if(i>n)throw new Error(`Invalid API level ${r.apiLevel}. Without DevEco Studio, supported range is API 17-${n}`);return i}return t!==void 0?t:23}async function od(){try{return await O.new()}catch(r){console.error(Bo(`DevEco Studio not found: ${r.message}`)),console.log(Bo("Using placeholder API level instead."));return}}var sd=new Zl("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async r=>{try{r.appName||(console.error(Mr("Error: --app-name is required")),xr.exit(1));let e=r.appName;Ql(e);let t=r.bundleName||nd(e);ed(t),r.projectPath&&zo(r.projectPath);let n=rd(e,r.projectPath);zo(n),console.log(Xl("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await od(),o=id(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Wo(n,e,t,o,s);console.log(`
1227
- `+Uo("Project created successfully!")),console.log(`Project root: ${a.projectRoot}`),console.log(`App name: ${a.appName}`),console.log(`Bundle name: ${a.bundleName}`),console.log(`API level: ${a.apiLevel}`),console.log(Uo("Template integrity check passed"))}catch(e){let t=e;console.error(Mr(`
1228
- Failed to create project`)),console.error(Mr(t.message)),xr.exit(1)}}),Go=sd;import{Command as hd}from"commander";import{red as fd,cyan as ts}from"colorette";import ad from"fs";import Xt from"path";import{cyan as cd}from"colorette";import*as Qt from"smol-toml";var Ze=ad.promises;async function ld(r){try{let e=await Ze.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read config file ${r}: ${e.message}`,{cause:e})}}async function dd(r){try{let e=await Ze.readFile(r,"utf8");return e.trim()===""?{}:Qt.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function ud(r,e){let t=Xt.dirname(r);await Ze.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Ze.writeFile(r,n,"utf8")}async function pd(r,e){let t=Xt.dirname(r);await Ze.mkdir(t,{recursive:!0});let n=Qt.stringify(e);await Ze.writeFile(r,n,"utf8")}function Jo(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function Ko(r,e,t,n,i){(!r[e]||typeof r[e]!="object")&&(r[e]={});let o=r[e];return t in o&&!i?!1:(o[t]=n,!0)}async function Zo(r,e){return r.format==="codex"?dd(e):ld(e)}async function Xo(r,e,t){return r.format==="codex"?pd(e,t):ud(e,t)}async function Qo(r,e,t=!1){let n=Pe[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Pe).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await Zo(n,n.globalConfigPath);if(Jo(i,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${n.globalConfigPath}`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=Vt(n,void 0);return Ko(i,n.mcpServersKey,se,o,t),await Xo(n,n.globalConfigPath,i),console.log(`MCP server ${se} configured in ${n.globalConfigPath}`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}async function Rr(r,e,t=!1){let n=Pe[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Pe).join(", ")}`};let i=Xt.isAbsolute(n.projectConfigPath)?n.projectConfigPath:Xt.join(e,n.projectConfigPath);try{let o=await Zo(n,i);if(Jo(o,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${i}`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=Vt(n,e);return Ko(o,n.mcpServersKey,se,s,t),await Xo(n,i,o),console.log(`MCP server ${se} configured in ${i}`),{success:!0,configPath:i,agentName:r,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}function es(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(cd("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}var Or="deveco-cli";async function md(r,e,t){let n=[];if(r.customPath){let i=await Do(Or,e,r.customPath,t.force);return n.push(i),n}for(let{project:i,agent:o}of r.projectAgents){let s=await Eo(Or,e,i,o,t.force);n.push(s)}for(let i of r.agents){let o=await Po(Or,e,i,t.force);n.push(o)}return n}async function gd(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Rr(o,i,t);n.push(s)}for(let i of r.agents){let o=await Rr(i,e,t);n.push(o)}return n}async function yd(r,e){let t=[];for(let n of r){if(!Pe[n])continue;let o=await Qo(n,process.cwd(),e);t.push(o)}return t}async function vd(r,e,t){if(t.agent&&t.agent.split(",").map(d=>d.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let n=t.force??!1,i=r.projectAgents.filter(c=>c.agent!=="qoder"),o=r.agents.filter(c=>c!=="qoder"),s={...r,projectAgents:i,agents:o},a=e?await gd(s,e,n):await yd(s.agents,n);a.length>0&&(console.log(ts("MCP Configuration:")),es(a))}async function wd(r){if(r.skill&&r.mcp)throw new Error("Cannot use --skill and --mcp together. Use --skill for skill installation only, or --mcp for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=wt(r.path,r.project,r.agent);t&&De(t,"Project directory",r.force),e&&De(e,"Directory",r.force);let n=await Gt(r,e,t);if(r.mcp){await vd(n,t,r);return}let i=ko(),o=await md(n,i,r);console.log(),o.length>0&&(console.log(ts("Skill Installation:")),vt(o))}var bd=new hd("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 to install the skill or MCP config into").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 an existing skill / MCP configuration").action(async r=>{try{await wd(r)}catch(e){console.error(fd(e.message)),process.exit(1)}}),ns=bd;import{Command as Hu}from"commander";import{McpServer as Ou}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Nu}from"@modelcontextprotocol/sdk/server/stdio.js";import*as dt from"path";import{z as Xr}from"zod";var en=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:n}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>n(i)))}};function Nr(){return new en}import*as ye from"fs";import*as ee from"path";import{z as Jr}from"zod";import D from"fs";import*as tn from"os";import*as S from"path";import Sd from"json5";var Lr="Huawei";var Pd=3,ss=3,rs="DevEco Studio",as={DevEcoStudio:"deveco_studio"};function Hr(r){if(!D.existsSync(r)||!D.statSync(r).isDirectory())return!1;let e=D.existsSync(S.join(r,"build-profile.json5")),t=D.existsSync(S.join(r,"hvigorfile.js"))||D.existsSync(S.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=D.readFileSync(S.join(r,"build-profile.json5"),"utf-8");return Sd.parse(n).app!==void 0}catch{return!1}}function cs(r,e,t){if(e>=t)return null;let n=Ed(r),i=Dd(n);if(i)return i;for(let o of n){let s=cs(o,e+1,t);if(s)return s}return null}function Ed(r){try{let e=D.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(S.join(r,n.name));return t}catch{return[]}}function Dd(r){for(let e of r)if(Hr(e))return e;return null}function he(r){if(!r||r.trim()==="")return null;let e=S.resolve(r),t;try{t=D.realpathSync(e)}catch{t=e}if(!D.existsSync(t))return null;if(Hr(t))return t;let n=t;for(let i=1;i<=3;i++){let o=S.dirname(n);if(o===n)break;if(Hr(o))return o;n=o}if(D.statSync(t).isDirectory()){let i=cs(t,0,Pd);if(i)return i}return null}function ls(r){if(process.platform==="linux")return null;let e=r??Oe();if(!e)return null;let t;if(process.platform==="win32")t=S.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=S.join(e,"contents","plugins","openharmony");else return null;let n=S.join(t,"ace-server","out","index.js");return D.existsSync(n)?t:null}var Id=["sdk","default","openharmony","native","llvm","bin","clangd"],jr=[".idea",".deveco","cxx","compile_commands.json"];function Cd(r){return process.platform==="darwin"&&r.endsWith(".app")?S.join(r,"Contents"):r}function is(r){let e=new Set,t=[r,Cd(r)];for(let n of t){let i=S.join(n,...Id);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function ds(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of is(t.trim()))if(e.push(i),D.existsSync(i))return i}let n=r??Oe();if(n){for(let i of is(n))if(e.push(i),D.existsSync(i))return i}return null}function nn(r){return S.join(r,...jr)}function Oe(){if(process.platform==="win32"){let r=[S.join("C:\\Program Files",Lr,rs),S.join("C:\\Program Files (x86)",Lr,rs)];return os(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",S.join(process.env.HOME??"","Applications","DevEco Studio.app")];return os(r)}return null}function os(r){for(let e of r)if(D.existsSync(e))return e;return null}function ae(r){return process.platform==="darwin"?S.join(r,"Contents"):r}function Ad(r){if(!r||!D.existsSync(r)||!us(r))return!1;let e=ae(r);return[S.join(e,"plugins","openharmony"),S.join(e,"sdk"),S.join(e,"tools")].some(n=>D.existsSync(n))}function us(r){try{return D.statSync(r).isDirectory()}catch{return!1}}function Fr(r,e){return!r||!D.existsSync(r)?!1:e===as.DevEcoStudio?Ad(r):!1}function rn(r,e=as.DevEcoStudio){if(!r)return"";if(Fr(r,e))return r;let t=kd(r,e);if(t)return t;let n=Td(r,e);return n||r}function kd(r,e){let t=r;for(let n=0;n<ss;n++){let i=S.dirname(t);if(!i||i===t)break;if(Fr(i,e))return i;t=i}return null}function Td(r,e){if(!D.existsSync(r)||!us(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=ss)continue;let o=Md(n,i,e,t);if(o)return o}return null}function Md(r,e,t,n){let i;try{i=D.readdirSync(r,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=S.join(r,o.name);if(Fr(s,t))return s;n.push({p:s,depth:e+1})}return null}function ps(r){return new Promise(e=>setTimeout(e,r))}var xd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function on(r){let e=S.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&xd.has(e)}function hs(r){return S.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ce(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function $r(r){return ce(r)}function Ne(r){let e=$r(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Dt(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),Ne(t)}}catch{}return r}function fs(r){let e=[],t=r.lastIndexOf("file:/");if(t>=0){let n=r.slice(t).replace(/^file:\/+/,"");if(n){let i=n.startsWith("/")?`file://${n}`:`file:///${n}`,o=Dt(i);o!==r&&o!==Dt(r)&&e.push(o)}}return e}function sn(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(tn.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(tn.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(tn.homedir(),".local","share","devecocli-mcp-server","logs")}function ms(r,e){let t=Rd(e),n=Od(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=Nd(t,r,s);return Ld(e,a),i}function Rd(r){let e;try{e=D.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Od(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(n+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Nd(r,e,t){let n=!1,i=r.map(o=>{if(n)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):o});return n||i.push(t),i}function Ld(r,e){try{D.mkdirSync(S.dirname(r),{recursive:!0})}catch{}try{D.writeFileSync(r,e.join(`
1226
+ `).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return C.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>n?c.toLowerCase().includes(n.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){w(`Fetching latest crash log file: ${n}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];w(`Executing command: ${e} ${i.join(" ")}`);let o=await we(e,i),s=xe(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 Lr,red as Vo}from"colorette";import ql from"ora";function Yl(r){try{return C.parsePositiveInteger(r,"tail")}catch{throw new Bo("`tail` must be a positive integer.")}}function Uo(r,e){try{return C.parseDurationToSeconds(r,e)}catch{throw new Bo(`${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 Gl(r){if(r.to&&r.follow)throw new Error("`--to` cannot be used with `--follow`.");C.assertRelativeTimeRange(r.from,r.to)}async function Jl(r,e,t,n,i){return t.crash?await r.getCrashLog(e,t.bundleName):await r.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:n,toSeconds:i})}function Kl(r,e,t,n){let i=C.filterLogsByRelativeWindow(r,t,n);return e.tail?C.getLastLines(i,e.tail):i}var Xl=new zl("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(Vo(r))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",Yl).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Uo(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Uo(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await Zl(r)});async function Zl(r){let e=ql({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Gl(r);let n=r.from,i=r.to,o=await O.new(),s=new rn(o),a=await s.selectDevice(r.device);a||(t(),process.exit(1)),w(Lr(`deviceId: ${a}`)),w(Lr(`type: ${r.crash?"Crash logs":"Common logs"}`)),w(Lr("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await Jl(s,a,r,n,i);t(),r.crash&&c&&(c=Kl(c,r,n,i)),c&&console.log(c)}catch(n){t(),console.error(Vo(n.message)),process.exit(1)}}var zo=Xl;import Dt from"path";import he from"fs";import jr from"process";import Qo from"os";import{Command as dd}from"commander";import{green as Jo,red as Hr,cyan as ud,yellow as Ko}from"colorette";import j from"fs-extra";import T from"path";import*as qo from"os";import{fileURLToPath as Ql}from"url";var ed={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"}},td=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function nd(){let r=import.meta.url,e=Ql(r);if(e.includes("dist")){let o=T.dirname(e),s=T.dirname(o);return T.join(s,"templates","application")}let t=T.dirname(e),n=T.dirname(t),i=T.dirname(n);return T.join(i,"templates","application")}function Yo(r,e){j.mkdirSync(e,{recursive:!0});for(let t of j.readdirSync(r,{withFileTypes:!0})){let n=T.join(r,t.name),i=T.join(e,t.name);if(t.isDirectory()){Yo(n,i);continue}j.existsSync(i)||(j.mkdirSync(T.dirname(i),{recursive:!0}),j.copyFileSync(n,i))}}function Ct(r,e){let t=j.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&j.writeFileSync(r,n,"utf-8")}function rd(r,e){if(e===22)return;let t=ed[e];t&&(Ct(T.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Ct(T.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Ct(T.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function id(r){return td.filter(t=>!j.existsSync(T.join(r,t))).length===0}function od(){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 sd(r){return qo.platform()==="darwin"?T.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):T.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function ad(r,e){let t=sd(e);if(!j.existsSync(t))return!1;let n=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of n){let s=T.join(t,i),a=T.join(r,o);j.existsSync(s)&&(j.mkdirSync(T.dirname(a),{recursive:!0}),j.copyFileSync(s,a))}return!0}function cd(r){let e=od(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let i=T.join(r,n);j.mkdirSync(T.dirname(i),{recursive:!0}),j.writeFileSync(i,e)}}function ld(r,e){e&&ad(r,e)||cd(r)}function Go(r,e,t,n,i){let o=nd();if(!j.existsSync(o))throw new Error(`Template directory not found: ${o}`);j.mkdirSync(r,{recursive:!0}),Yo(o,r),ld(r,i),Ct(T.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Ct(T.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),rd(r,n);let s=id(r);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function pd(r){if(r.length<1||r.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function hd(r){if(r.length<7||r.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${r.length}`);if(r.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=r.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let n=0;n<e.length;n++){let i=e[n];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(n===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}function es(r){if(Qo.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function Xo(r){if(r.length===0)throw new Error("Project path cannot be empty.");if(r.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${r.length}).`);let e=Qo.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(r)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let n=es(r);if(/[\u4e00-\u9fff]/.test(n))throw new Error("Project path cannot contain Chinese characters.");if(n.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function fd(r){let e=r,t=Dt.parse(r).root;for(;e!==t;){if(he.existsSync(e))return e;e=Dt.dirname(e)}return he.existsSync(t)?t:null}function Zo(r){let e=fd(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{he.accessSync(e,he.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Dt.join(e,`.deveco_write_test_${Date.now()}`);try{he.writeFileSync(t,"test"),he.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function md(r){return`com.example.${r.toLowerCase()}`}function gd(r,e){if(e){let i=es(e),o=Dt.resolve(i);if(he.existsSync(o)){if(he.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else Zo(o);return o}let t=jr.cwd(),n=Dt.join(t,r);if(he.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return Zo(n),n}function yd(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let i=Number(r.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${r.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${r.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>n)throw new Error(`Invalid API version ${r.apiLevel}. Without DevEco Studio, supported range is API version 17-${n}`);return i}return t!==void 0?t:23}async function vd(){try{return await O.new()}catch(r){console.error(Ko(`DevEco Studio not found: ${r.message}`)),console.log(Ko("Use placeholder API level instead."));return}}var wd=new dd("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async r=>{try{r.appName||(console.error(Hr("Error: --app-name is required")),jr.exit(1));let e=r.appName;pd(e);let t=r.bundleName||md(e);hd(t),r.projectPath&&Xo(r.projectPath);let n=gd(e,r.projectPath);Xo(n),console.log(ud("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await vd(),o=yd(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Go(n,e,t,o,s);console.log(`
1227
+ `+Jo("Project created successfully.")),console.log(`Project root: ${a.projectRoot}`),console.log(`App name: ${a.appName}`),console.log(`Bundle name: ${a.bundleName}`),console.log(`API level: ${a.apiLevel}`),console.log(Jo("Template integrity check passed."))}catch(e){let t=e;console.error(Hr(`
1228
+ Failed to create project.`)),console.error(Hr(t.message)),jr.exit(1)}}),ts=wd;import{Command as Id}from"commander";import{red as Ad,cyan as cs}from"colorette";import bd from"fs";import on from"path";import{cyan as Sd}from"colorette";import*as sn from"smol-toml";var Ke=bd.promises;async function Pd(r){try{let e=await Ke.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${r}: ${e.message}`,{cause:e})}}async function Ed(r){try{let e=await Ke.readFile(r,"utf8");return e.trim()===""?{}:sn.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function Cd(r,e){let t=on.dirname(r);await Ke.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Ke.writeFile(r,n,"utf8")}async function Dd(r,e){let t=on.dirname(r);await Ke.mkdir(t,{recursive:!0});let n=sn.stringify(e);await Ke.writeFile(r,n,"utf8")}function ns(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function rs(r,e,t,n,i){(!r[e]||typeof r[e]!="object")&&(r[e]={});let o=r[e];return t in o&&!i?!1:(o[t]=n,!0)}async function is(r,e){return r.format==="codex"?Ed(e):Pd(e)}async function os(r,e,t){return r.format==="codex"?Dd(e,t):Cd(e,t)}async function ss(r,e,t=!1){let n=Pe[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Pe).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await is(n,n.globalConfigPath);if(ns(i,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${n.globalConfigPath}.`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=Xt(n,void 0);return rs(i,n.mcpServersKey,se,o,t),await os(n,n.globalConfigPath,i),console.log(`MCP server ${se} configured in ${n.globalConfigPath}.`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}async function Fr(r,e,t=!1){let n=Pe[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Pe).join(", ")}`};let i=on.isAbsolute(n.projectConfigPath)?n.projectConfigPath:on.join(e,n.projectConfigPath);try{let o=await is(n,i);if(ns(o,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=Xt(n,e);return rs(o,n.mcpServersKey,se,s,t),await os(n,i,o),console.log(`MCP server ${se} configured in ${i}.`),{success:!0,configPath:i,agentName:r,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}function as(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(Sd("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}var $r="deveco-cli";async function kd(r,e,t){let n=[];if(r.customPath){let i=await Ro($r,e,r.customPath,t.force);return n.push(i),n}for(let{project:i,agent:o}of r.projectAgents){let s=await Mo($r,e,i,o,t.force);n.push(s)}for(let i of r.agents){let o=await To($r,e,i,t.force);n.push(o)}return n}async function Td(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Fr(o,i,t);n.push(s)}for(let i of r.agents){let o=await Fr(i,e,t);n.push(o)}return n}async function Md(r,e){let t=[];for(let n of r){if(!Pe[n])continue;let o=await ss(n,process.cwd(),e);t.push(o)}return t}async function Rd(r,e,t){if(t.agent&&t.agent.split(",").map(d=>d.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let n=t.force??!1,i=r.projectAgents.filter(c=>c.agent!=="qoder"),o=r.agents.filter(c=>c!=="qoder"),s={...r,projectAgents:i,agents:o},a=e?await Td(s,e,n):await Md(s.agents,n);a.length>0&&(console.log(cs("MCP Configuration:")),as(a))}async function xd(r){if(r.skill&&r.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=St(r.path,r.project,r.agent);t&&Ce(t,"Project directory",r.force),e&&Ce(e,"Directory",r.force);let n=await en(r,e,t);if(r.mcp){await Rd(n,t,r);return}let i=Lo(),o=await kd(n,i,r);console.log(),o.length>0&&(console.log(cs("Skill Installation:")),bt(o))}var Od=new Id("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async r=>{try{await xd(r)}catch(e){console.error(Ad(e.message)),process.exit(1)}}),ls=Od;import{Command as Ku}from"commander";import{McpServer as Yu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Gu}from"@modelcontextprotocol/sdk/server/stdio.js";import*as ut from"path";import{z as oi}from"zod";var an=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:n}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>n(i)))}};function _r(){return new an}import*as ve from"fs";import*as te from"path";import{z as ti}from"zod";import I from"fs";import*as cn from"os";import*as S from"path";import Nd from"json5";var Wr="Huawei";var Ld=3,hs=3,ds="DevEco Studio",fs={DevEcoStudio:"deveco_studio"};function Ur(r){if(!I.existsSync(r)||!I.statSync(r).isDirectory())return!1;let e=I.existsSync(S.join(r,"build-profile.json5")),t=I.existsSync(S.join(r,"hvigorfile.js"))||I.existsSync(S.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=I.readFileSync(S.join(r,"build-profile.json5"),"utf-8");return Nd.parse(n).app!==void 0}catch{return!1}}function ms(r,e,t){if(e>=t)return null;let n=Hd(r),i=jd(n);if(i)return i;for(let o of n){let s=ms(o,e+1,t);if(s)return s}return null}function Hd(r){try{let e=I.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(S.join(r,n.name));return t}catch{return[]}}function jd(r){for(let e of r)if(Ur(e))return e;return null}function fe(r){if(!r||r.trim()==="")return null;let e=S.resolve(r),t;try{t=I.realpathSync(e)}catch{t=e}if(!I.existsSync(t))return null;if(Ur(t))return t;let n=t;for(let i=1;i<=3;i++){let o=S.dirname(n);if(o===n)break;if(Ur(o))return o;n=o}if(I.statSync(t).isDirectory()){let i=ms(t,0,Ld);if(i)return i}return null}function gs(r){if(process.platform==="linux")return null;let e=r??Oe();if(!e)return null;let t;if(process.platform==="win32")t=S.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=S.join(e,"contents","plugins","openharmony");else return null;let n=S.join(t,"ace-server","out","index.js");return I.existsSync(n)?t:null}var Fd=["sdk","default","openharmony","native","llvm","bin","clangd"],Br=[".idea",".deveco","cxx","compile_commands.json"];function $d(r){return process.platform==="darwin"&&r.endsWith(".app")?S.join(r,"Contents"):r}function us(r){let e=new Set,t=[r,$d(r)];for(let n of t){let i=S.join(n,...Fd);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function ys(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of us(t.trim()))if(e.push(i),I.existsSync(i))return i}let n=r??Oe();if(n){for(let i of us(n))if(e.push(i),I.existsSync(i))return i}return null}function ln(r){return S.join(r,...Br)}function Oe(){if(process.platform==="win32"){let r=[S.join("C:\\Program Files",Wr,ds),S.join("C:\\Program Files (x86)",Wr,ds)];return ps(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",S.join(process.env.HOME??"","Applications","DevEco Studio.app")];return ps(r)}return null}function ps(r){for(let e of r)if(I.existsSync(e))return e;return null}function ae(r){return process.platform==="darwin"?S.join(r,"Contents"):r}function _d(r){if(!r||!I.existsSync(r)||!vs(r))return!1;let e=ae(r);return[S.join(e,"plugins","openharmony"),S.join(e,"sdk"),S.join(e,"tools")].some(n=>I.existsSync(n))}function vs(r){try{return I.statSync(r).isDirectory()}catch{return!1}}function Vr(r,e){return!r||!I.existsSync(r)?!1:e===fs.DevEcoStudio?_d(r):!1}function dn(r,e=fs.DevEcoStudio){if(!r)return"";if(Vr(r,e))return r;let t=Wd(r,e);if(t)return t;let n=Ud(r,e);return n||r}function Wd(r,e){let t=r;for(let n=0;n<hs;n++){let i=S.dirname(t);if(!i||i===t)break;if(Vr(i,e))return i;t=i}return null}function Ud(r,e){if(!I.existsSync(r)||!vs(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=hs)continue;let o=Bd(n,i,e,t);if(o)return o}return null}function Bd(r,e,t,n){let i;try{i=I.readdirSync(r,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=S.join(r,o.name);if(Vr(s,t))return s;n.push({p:s,depth:e+1})}return null}function ws(r){return new Promise(e=>setTimeout(e,r))}var Vd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function un(r){let e=S.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&Vd.has(e)}function bs(r){return S.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ce(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function zr(r){return ce(r)}function Ne(r){let e=zr(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function It(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),Ne(t)}}catch{}return r}function Ss(r){let e=[],t=r.lastIndexOf("file:/");if(t>=0){let n=r.slice(t).replace(/^file:\/+/,"");if(n){let i=n.startsWith("/")?`file://${n}`:`file:///${n}`,o=It(i);o!==r&&o!==It(r)&&e.push(o)}}return e}function pn(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(cn.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(cn.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(cn.homedir(),".local","share","devecocli-mcp-server","logs")}function Ps(r,e){let t=zd(e),n=qd(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=Yd(t,r,s);return Gd(e,a),i}function zd(r){let e;try{e=I.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function qd(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(n+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Yd(r,e,t){let n=!1,i=r.map(o=>{if(n)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):o});return n||i.push(t),i}function Gd(r,e){try{I.mkdirSync(S.dirname(r),{recursive:!0})}catch{}try{I.writeFileSync(r,e.join(`
1229
1229
  `)+`
1230
- `,"utf8")}catch{}}function _r(r,e,t="[Cleanup]"){try{let n=S.dirname(r);if(!D.existsSync(n))return;let i=Date.now();for(let o of D.readdirSync(n,{withFileTypes:!0}))o.isDirectory()&&Hd(S.join(n,o.name),i,e,t)}catch{}}function Hd(r,e,t,n){try{let{mtimeMs:i}=D.statSync(r);if(e-i<=t)return;D.rmSync(r,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${n} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${r}`)}catch(i){console.error(`${n} Failed to remove expired dir ${r}: ${i}`)}}function an(r){let e=r.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",n=S.join(e,"node",t);return D.existsSync(n)||process.platform!=="win32"&&(n=S.join(e,"node","bin","node"),D.existsSync(n))?n:process.execPath??"node"}import*as C from"fs";import*as ln from"path";var gs="mcp-server.log",jd="mcp-server",Fd={maxSize:10*1024*1024,maxFiles:4},Wr=class{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;constructor(e,t){this.rotationOptions={...Fd,...t},e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=sn(),this.currentLogFile=ln.join(this.logDir,gs),C.existsSync(this.logDir)||C.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}getRotatedFileName(e,t){return ln.join(this.logDir,`${jd}-${e}.log.${t}`)}fileExists(e){try{return C.accessSync(e,C.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=C.readdirSync(this.logDir),t=[];for(let i of e)if(i===gs||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=ln.join(this.logDir,i),s=C.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<t.length;i++)try{C.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)&&C.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)&&C.renameSync(o,s)}let n=this.getRotatedFileName(e,1);C.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=C.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=C.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{C.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent")return;let i=n.map(c=>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}
1231
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);C.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{C.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},J=null;function Ur(r=!1){J&&J.dispose(),J=new Wr(r)}function ys(){J&&(J.dispose(),J=null)}function vs(){J&&J.flush()}function ws(){return J?.getLogFilePath()??null}function bs(){return J?.getLogDirectory()??null}function cn(){return J||Ur(!1),J}var f={debug:(r,...e)=>cn().debug(r,...e),info:(r,...e)=>cn().info(r,...e),warn:(r,...e)=>cn().warn(r,...e),error:(r,...e)=>cn().error(r,...e)};function Ss(r){return"method"in r&&!("id"in r)}import{spawn as _d}from"child_process";import{EventEmitter as Wd}from"events";import*as Qe from"fs";import*as Cs from"path";import*as Ps from"util";var Br="";function Es(r){if(!r||r==="auto"||r==="stdout"||r==="none"){Br="";return}Br=r}function Ds(){return Br||(bs()??"")}function dn(r,...e){if(e.length===0)return r;try{return Ps.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var l={info(r,...e){f.info(`[lsp] ${dn(r,...e)}`)},warn(r,...e){f.warn(`[lsp] ${dn(r,...e)}`)},error(r,...e){f.error(`[lsp] ${dn(r,...e)}`)},debug(r,...e){f.debug(`[lsp] ${dn(r,...e)}`)}};import*as It from"fs";import*as zr from"os";import*as Xe from"path";import $d from"json5";function Y(r){if(!It.existsSync(r))return null;try{let e=It.readFileSync(r,"utf-8");return e.trim()?$d.parse(e):null}catch{return null}}function fe(r){try{let e=Xe.resolve(r),t=new URL(`file://${e}`).toString();if(zr.platform()==="win32"){let n=t.match(/^file:\/\/\/([A-Za-z]):/);if(n){let i=n[1].toUpperCase(),o=t.substring(`file:///${n[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return r}}function un(r){return r&&r.replace(/\\/g,"/")}function F(r){let e=Xe.normalize(r).replace(/\\/g,"/");if(zr.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Is(r){return Xe.join(r,"build-profile.json5")}var pn=class extends Wd{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;async start(){let t=Cs.join(this.config.logPath,"lspLog");Qe.existsSync(t)||Qe.mkdirSync(t,{recursive:!0}),Qe.existsSync(this.config.indexingDataLocation)||Qe.mkdirSync(this.config.indexingDataLocation,{recursive:!0});let n=this.config.nodeMaxOldSpaceSize??8192,i=F(t),o=["--expose-gc",`--max-old-space-size=${n}`,"--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"];l.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";l.info(`[LspClient] nodePath: ${s}`),this.process=_d(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();l.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{l.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),l.info("[LspClient] start lsp process success")}sendRaw(t,n){if(!this.process?.stdin?.writable){l.warn("[LspClient] Cannot send message, stdin not writable");return}l.info(`[LspClient] send message: ${n}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,n,i){let o={jsonrpc:"2.0",method:t,params:n};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1230
+ `,"utf8")}catch{}}function qr(r,e,t="[Cleanup]"){try{let n=S.dirname(r);if(!I.existsSync(n))return;let i=Date.now();for(let o of I.readdirSync(n,{withFileTypes:!0}))o.isDirectory()&&Jd(S.join(n,o.name),i,e,t)}catch{}}function Jd(r,e,t,n){try{let{mtimeMs:i}=I.statSync(r);if(e-i<=t)return;I.rmSync(r,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${n} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${r}`)}catch(i){console.error(`${n} Failed to remove expired dir ${r}: ${i}`)}}function hn(r){let e=r.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",n=S.join(e,"node",t);return I.existsSync(n)||process.platform!=="win32"&&(n=S.join(e,"node","bin","node"),I.existsSync(n))?n:process.execPath??"node"}import*as A from"fs";import*as mn from"path";var Es="mcp-server.log",Kd="mcp-server",Xd={maxSize:10*1024*1024,maxFiles:4},Yr=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...Xd,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=pn(),this.currentLogFile=mn.join(this.logDir,Es),A.existsSync(this.logDir)||A.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}getRotatedFileName(e,t){return mn.join(this.logDir,`${Kd}-${e}.log.${t}`)}fileExists(e){try{return A.accessSync(e,A.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=A.readdirSync(this.logDir),t=[];for(let i of e)if(i===Es||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=mn.join(this.logDir,i),s=A.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<t.length;i++)try{A.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)&&A.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)&&A.renameSync(o,s)}let n=this.getRotatedFileName(e,1);A.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=A.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=A.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{A.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(c=>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}
1231
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);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{A.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},K=null;function Gr(r=!1){K&&K.dispose(),K=new Yr(r)}function Cs(){K&&(K.dispose(),K=null)}function Ds(){K&&K.flush()}function Is(){return K?.getLogFilePath()??null}function As(){return K?.getLogDirectory()??null}function fn(){return K||Gr(!1),K}var f={debug:(r,...e)=>fn().debug(r,...e),info:(r,...e)=>fn().info(r,...e),warn:(r,...e)=>fn().warn(r,...e),error:(r,...e)=>fn().error(r,...e)};function ks(r){return"method"in r&&!("id"in r)}import{spawn as eu}from"child_process";import{EventEmitter as tu}from"events";import*as Ze from"fs";import*as js from"path";import*as Ts from"util";var Jr="";function Ms(r){if(!r||r==="auto"||r==="stdout"||r==="none"){Jr="";return}Jr=r}function Rs(){return Jr||(As()??"")}function gn(r,...e){if(e.length===0)return r;try{return Ts.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var l={info(r,...e){f.info(`[lsp] ${gn(r,...e)}`)},warn(r,...e){f.warn(`[lsp] ${gn(r,...e)}`)},error(r,...e){f.error(`[lsp] ${gn(r,...e)}`)},debug(r,...e){f.debug(`[lsp] ${gn(r,...e)}`)}};import*as kt from"fs";import*as Tt from"os";import*as Xe from"path";import Qd from"json5";var Zd={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"},yn={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DEFINITION:"textDocument/definition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",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",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles"},y={...Zd,...yn},M="2.0",X={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"};var xs=8192,Kr=100,Os=.03,Ns=.7,At=900*1e3;function W(r){if(!kt.existsSync(r))return null;try{let e=kt.readFileSync(r,"utf-8");return e.trim()?Qd.parse(e):null}catch{return null}}function Ls(r,e){let t=Math.floor(Tt.totalmem()/1048576),n=Math.floor(t*Ns),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=xs,r>Kr&&(i+=(r-Kr)*Os*1024),o=`formula(moduleCount=${r})`);let s=n>0&&i>n;s&&(i=n);let a=Math.round(i);return l.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${n}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function me(r){try{let e=Xe.resolve(r),t=new URL(`file://${e}`).toString();if(Tt.platform()==="win32"){let n=t.match(/^file:\/\/\/([A-Za-z]):/);if(n){let i=n[1].toUpperCase(),o=t.substring(`file:///${n[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return r}}function vn(r){return r&&r.replace(/\\/g,"/")}function F(r){let e=Xe.normalize(r).replace(/\\/g,"/");if(Tt.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Hs(r){return Xe.join(r,"build-profile.json5")}var wn=class extends tu{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=js.join(this.config.logPath,"lspLog");return Ze.existsSync(t)||Ze.mkdirSync(t,{recursive:!0}),Ze.existsSync(this.config.indexingDataLocation)||Ze.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let n=this.ensureDirectories();l.info(`[LspClient] serverMaxSize=${t}MB`);let i=F(n),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"];l.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";l.info(`[LspClient] nodePath: ${s}`),this.process=eu(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();l.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{l.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),l.info("[LspClient] start lsp process success")}sendRaw(t,n){if(!this.process?.stdin?.writable){l.warn("[LspClient] Cannot send message, stdin not writable");return}l.info(`[LspClient] send message: ${n}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,n,i){let o={jsonrpc:"2.0",method:t,params:n};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
1232
1232
  \r
1233
1233
  ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
1234
1234
  \r
1235
- `);if(n===-1)break;let o=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){l.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(o[1],10),a=n+4,c=a+s;if(this.buffer.length<c)break;let d=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(d);if(u&&u.rest.length>0){l.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${d.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",d),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let n=this.process;return!n||n.exitCode!==null||n.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),n.off("exit",a),i())},a=()=>s();n.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let n=t.search(/\S/);if(n<0||t[n]!=="{"&&t[n]!=="[")return null;let i=0,o=!1,s=!1;for(let a=n;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let d=t.slice(n,a+1),u=t.slice(a+1);return{json:d,rest:u}}}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 hn=class{callbacks=new Map;timeouts=new Map;register(e,t){this.callbacks.set(e,t)}emit(e,t,n){l.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);i&&(i(t,n),this.callbacks.delete(e))}registerTimeout(e,t,n,i){this.timeouts.has(e)&&clearTimeout(this.timeouts.get(e));let o=setTimeout(()=>{l.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},n);this.timeouts.set(e,o)}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)}clear(e){this.clearTimeout(e),this.callbacks.delete(e)}};var fn=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let n=`${e}:${t}`;if(this.uniqueMessages.has(n)){l.info(`[Diagnostic] addMessage: duplicate message=${n}`);return}this.uniqueMessages.add(n),this.messages.push(new Vr(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)}},Vr=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var mn=class{map=new Map;register(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}unregister(e,t){let n=this.map.get(e);n&&(t!==void 0?n.delete(t):n.clear(),n.size===0&&this.map.delete(e))}invoke(e,...t){let n=this.map.get(e);if(n)for(let i of n)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function m(r){return typeof r=="object"&&r!==null}function qr(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}var Ud={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"},gn={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DEFINITION:"textDocument/definition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",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",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles"},g={...Ud,...gn},M="2.0",K={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"};function Bd(r){if(!m(r))return!1;let e=r.textDocument;return m(e)&&typeof e.uri=="string"}function zd(r){return m(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}var yn=class r{client;isInitialized=!1;stopOnce=null;callbacks=new mn;requestCallbacks=new hn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new pn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(){await this.client.start()}stop(){return this.stopOnce||(this.stopOnce=(async()=>{l.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.EXIT,params:{}}),K.EXIT),l.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),l.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(g.BROADCAST),this.callbacks.register(g.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(g.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(g.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(g.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:M,method:g.INITIALIZED,params:{editors:e}}),K.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:M,id:0,result:{}}),K.EMPTY)}sendAsyncRequest(e,t,n,i){if(!m(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Bd(t)){l.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof n!="number"){l.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(n)}`);return}let o=t.textDocument.uri,s=fe(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;l.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(l.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!zd(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),g.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!m(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){l.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;l.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),K.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=fe(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new fn(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,gn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),K.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=fe(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,gn.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),K.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=fe(e);l.info(`[LSP] didClose, uri: ${n}`);let i=this.diagnosticMap.get(n);if(!t&&(!i||i.isFromEditor)){l.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.DID_CLOSE,params:{textDocument:{uri:n}}}),K.DID_CLOSE)}getDiagnosticMessage(e){let t=fe(e),n=this.diagnosticMap.get(t);return n?n.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let n=t instanceof Error?t.message:String(t);l.error(`[LSP] JSON parse error: ${n}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let n=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,g.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:M,method:g.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e){switch(e){case g.MODULE_INIT_FINISH:return l.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(g.MODULE_INIT_FINISH),this.callbacks.unregister(g.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case g.INDEXING_PROGRESS_UPDATE:return l.info("[LSP] handleLspMessage, receive onIndexingProgressUpdate"),this.callbacks.invoke(g.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case g.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case g.ON_PACKAGE_CHANGE_FINISH:l.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case g.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case g.ON_ASYNC_HOVER:this.handleAsyncResponse(t,g.HOVER);return;case g.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,g.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case g.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,g.REFERENCES);return;default:l.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){l.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;m(t)&&m(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){l.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:M,method:g.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){l.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(n);return}if(!(t.length>0&&t[0]===!0)){l.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(n);return}l.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){l.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let n=e.params;if(!m(n)){l.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=n.requestId;if(typeof i!="number"){l.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,n)}handleForceOpenFile(e){if(!e){l.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,g.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){l.info("[LSP] publishDiagnostics uri is null");return}let n=e.version??-1;if(n===-1)return;let i=this.diagnosticMap.get(t);if(!i){l.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(n,JSON.stringify(s))}):i.setReceivedType(n),i.hasReceivedAllTypes(r.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,g.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),n={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=n[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let n=e[t];n&&typeof n.line=="number"&&(n.line=n.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,r.DIAGNOSTIC_TIMEOUT_MS,()=>{let n=this.diagnosticMap.get(e),i=n?n.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${r.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,n,i){let o={uri:e,diagnostics:n,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Fn from"path";import*as Dn from"path";var vn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var wn=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var bn=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Sn=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Pn=class{typeSetting=new bn;parameterNames=new Sn};var En=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=F(Dn.dirname(t)),this.indexingDataLocation=F(i),this.loggerPath=F(Dn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new vn;gutterIconsSetting=new wn;inlayHintsSetting=new Pn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as As from"path";var Ct=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(F(As.join(e,"src","main","resources")))}};var Vd="OS",et=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${Vd}`;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 Ct(e)):this.buildProfileParam=new Ct}toString(){return JSON.stringify(this)}};var tt=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as W from"path";import*as it from"fs";var In=class{modulePath;dependencies={};dynamicDependencies={}};var Le=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 nt=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as me from"path";import*as Cn from"fs";var rt=class{name="";version="";storePath="";dependencyPath="";path=""};var I={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:"oh-package.json5"},At=`${I.HVIGOR_CACHE}/${I.DEPENDENCY}`,He=`${I.DEPENDENCY}${I.JSON5}`;var kt=class r{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,n){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new r(e,t,n),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,n){this.dependencyPath=e,this.modulePath=t,this.projectPath=n,this.fileSpecPattern=r.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=me.join(this.dependencyPath,I.OH_PACKAGE_JSON5),n=Y(t);n&&(this.dependencies=this.getDependencyList(n,I.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,I.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,I.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!m(e))return n;let i=e[t];if(!m(i))return n;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){l.error(`${o} package dependency value is not String ${t}`);continue}let a=new rt;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,i){if(!(!e||!t))try{let o=me.normalize(me.join(this.modulePath,I.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=o;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=o;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),me.isAbsolute(s)){n.dependencyPath=o;return}i||(o=me.normalize(me.join(this.modulePath,s))),Cn.existsSync(o)&&Cn.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as Tt from"fs";import*as Ie from"path";import qd from"json5";var An=class r{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;constructor(e=""){this.projectPath=e}parseDependencies(e){let t=this.getLockFilePath(),n=this.readLockFile(t);if(!n)return!1;let i=this.validateLockFile(n);return i.valid?(this.extractDependencies(i.modules,i.packages,e),!0):!1}getLockFilePath(){return Ie.join(this.projectPath,I.OH_MODULES_PATH,I.OHPM_PATH,I.LOCK_JSON5_FILE)}readLockFile(e){if(!Tt.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Tt.readFileSync(e,"utf8"),n=qd.parse(t);return n||(l.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return l.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!m(e))return l.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return l.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(l.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=this.parseStorePathMap(t),this.finalDependencies=this.getDependencyList(e,I.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,I.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,I.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!m(e))return t;for(let[n,i]of Object.entries(e)){if(!m(i)){l.error(`${n} value is not json object`);continue}typeof i.storePath=="string"&&t.set(n,i.storePath)}return t}getDependencyList(e,t,n){if(!m(e))return[];for(let[i,o]of Object.entries(e))if(m(o)){let s=typeof o.name=="string"?o.name:"";if(n==="."&&s===""||s===n)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,n){let i=e[n];if(!m(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!m(s))return[];for(let[a,c]of Object.entries(s)){if(!m(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",b=new rt;b.name=a,b.version=u.startsWith(r.FILE_DEPENDENCY_PREFIX)?u.substring(r.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(b,n,a,d,u);let k=`${a}@${u}`;this.storePathMap.has(k)&&(b.storePath=this.storePathMap.get(k)||""),o.push(b)}return o}parseDependencyPath(e,t,n,i,o){let s=Ie.normalize(Ie.join(this.projectPath,t,I.OH_MODULES_PATH,n));try{let a=o;o.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(a=o.substring(r.FILE_DEPENDENCY_PREFIX.length));let c=a;if(Ie.isAbsolute(c)||(c=Ie.join(this.projectPath,a)),!Tt.existsSync(c)){e.dependencyPath=s;return}if(e.path=i,this.fileNameForOhpm.test(o)){e.dependencyPath=s;return}e.dependencyPath=c}catch(a){l.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var je=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Is(this.projectRoot);try{let t=Y(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function ks(r){return m(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Mt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new je(this.projectPath)}projectPath;sdkPath;moduleInfoParse;getAllDependencyMap(e){let t=this.projectPath,n=W.join(t,At),i=W.join(n,He);if(!it.existsSync(n)||!it.existsSync(i)){let a="Dependency map or JSON not found";return l.warn(`[Parser] getAllDependencyMap failed: ${a}.`),{status:"ERROR",message:`${a}, please rebuild project`}}let o=new nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let a="No modules found in build-profile.json5";return l.warn(`[Parser] getAllDependencyMap failed: ${a}.`),{status:"ERROR",message:a}}for(let a of s)ks(a)&&this.parseSingleModule(a,n,o,e);return{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=W.join(n,At),o=W.join(i,He);if(!it.existsSync(i)||!it.existsSync(o))return l.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(d=>d.trim()).filter(Boolean)):null,a=new nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return l.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let d of c){if(!ks(d))continue;let u=d.name;if(s&&!s.has(u))continue;let b=d.srcPath,k=W.resolve(this.projectPath,b),le=W.join(i,u),Fe=F(k),$e=this.buildModuleDependencies(u,Fe,le,a);$e.moduleName=u,t.push($e)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=e.srcPath,a=W.resolve(this.projectPath,s),c=W.join(t,o),d=F(a),u=new et(d),b=this.buildModuleDependencies(o,d,c,n);this.parseModuleJson5(d,u);let k=this.parseMainPages(d);this.parseSdkJson(u),this.parseCompatibleSdkVersion(u),u.moduleName=o,u.moduleType=o,u.packageName=o,u.moduleDependencies=b,u.moduleJsonParam=new tt(k),i.push(u)}buildModuleDependencies(e,t,n,i){let o=new nt(this.projectPath,e,t);kt.getInstance(n,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new In;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let n={},i={};for(let o of e.finalDependencies)n[o.name]=new Le(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Le(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=W.join(e,I.OH_PACKAGE_JSON5);if(!it.existsSync(n))return;kt.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=new An(e.projectPath);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)}parseModuleJson5(e,t){let n=W.join(e,"src","main","module.json5"),i=Y(n);if(!m(i)||!m(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(m(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)m(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=W.join(e,"src","main","resources","base","profile","main_pages.json"),n=Y(t);return!m(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=W.join(this.sdkPath,"default","sdk-pkg.json"),n=Y(t);!m(n)||!m(n.data)||(typeof n.data.apiVersion=="string"&&(e.compileSdkLevel=n.data.apiVersion),typeof n.data.releaseType=="string"&&(e.compileSdkType=n.data.releaseType),typeof n.data.version=="string"&&(e.compileSdkVersion=n.data.version))}parseCompatibleSdkVersion(e){let t=W.join(this.projectPath,"build-profile.json5"),n=Y(t);if(!m(n)||!m(n.app)||!Array.isArray(n.app.products)||n.app.products.length===0)return;let i=n.app.products[0];if(!m(i)||typeof i.compatibleSdkVersion!="string")return;let[o,s]=this.parseBySplit(i.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=s}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!m(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 kn=class{constructor(e=[]){this.valueSet=e}valueSet};var ot=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Ts=(y=>(y[y.File=1]="File",y[y.Module=2]="Module",y[y.Namespace=3]="Namespace",y[y.Package=4]="Package",y[y.Class=5]="Class",y[y.Method=6]="Method",y[y.Property=7]="Property",y[y.Field=8]="Field",y[y.Constructor=9]="Constructor",y[y.Enum=10]="Enum",y[y.Interface=11]="Interface",y[y.Function=12]="Function",y[y.Variable=13]="Variable",y[y.Constant=14]="Constant",y[y.String=15]="String",y[y.Number=16]="Number",y[y.Boolean=17]="Boolean",y[y.Array=18]="Array",y[y.Object=19]="Object",y[y.Key=20]="Key",y[y.Null=21]="Null",y[y.EnumMember=22]="EnumMember",y[y.Struct=23]="Struct",y[y.Event=24]="Event",y[y.Operator=25]="Operator",y[y.TypeParameter=26]="TypeParameter",y))(Ts||{}),Ms=()=>Object.values(Ts).filter(r=>typeof r=="number");var Tn=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Mn=class{applyEdit=!0;workspaceEdit=new Tn;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new kn(Ms());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new ot;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var xn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Rn=class{constructor(e=[]){this.valueSet=e}valueSet};var On=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var xs=(v=>(v[v.Text=1]="Text",v[v.Method=2]="Method",v[v.Function=3]="Function",v[v.Constructor=4]="Constructor",v[v.Field=5]="Field",v[v.Variable=6]="Variable",v[v.Class=7]="Class",v[v.Interface=8]="Interface",v[v.Module=9]="Module",v[v.Property=10]="Property",v[v.Unit=11]="Unit",v[v.Value=12]="Value",v[v.Enum=13]="Enum",v[v.Keyword=14]="Keyword",v[v.Snippet=15]="Snippet",v[v.Color=16]="Color",v[v.File=17]="File",v[v.Reference=18]="Reference",v[v.Folder=19]="Folder",v[v.EnumMember=20]="EnumMember",v[v.Constant=21]="Constant",v[v.Struct=22]="Struct",v[v.Event=23]="Event",v[v.Operator=24]="Operator",v[v.TypeParameter=25]="TypeParameter",v))(xs||{}),Rs=()=>Object.values(xs).filter(r=>typeof r=="number");var Nn=class{completionItemKind=new Rn(Rs());completionItem=new On;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Ln=class{synchronization=new xn;completion=new Nn;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 ot;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Hn=class{workspace=new Mn;textDocument=new Ln;notebookDocument=null;window=null;general=null;experimental=null};var jn=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function st(r){return m(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function Os(r){return m(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function Ns(r){if(!m(r)||typeof r.text!="string")return!1;let e=r.range;return m(e)?st(e.start)&&st(e.end):!1}var $n=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=Fn.resolve(t,"ace-server","out","index.js"),this.logPath=Ds(),this.indexLogPath=i||this.logPath,this.messageHandle=new yn({serverPath:this.serverPath,logPath:this.logPath,nodeMaxOldSpaceSize:this.nodeMaxOldSpaceSize,indexingDataLocation:this.indexLogPath}),this.messageHandle.setBroadcastToClients(s=>this.onLspMessage(s))}sdkPath;rootUri;nodeMaxOldSpaceSize;messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}initTimeoutMs=60*1e3;async start(e,t){let n=!1;try{l.info(`serverPath: ${this.serverPath}`),l.info(`rootUri: ${this.rootUri}`),l.info(`sdkPath: ${this.sdkPath}`),l.info(`logPath: ${this.logPath}`),await this.messageHandle.start();let i=fe(this.rootUri),o=new En(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Mt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s,this.currentParams=new jn(i,o,new Hn),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:M,method:g.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((d,u)=>{this.messageHandle.onIndexingProgressUpdate(u),this.messageHandle.onInitializationCompleted(d)},"LSP initialization",this.initTimeoutMs),this.messageHandle.sendInitialized(e),n=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),l.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(n)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=fe(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=m(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:M,method:n,params:{uri:typeof o.uri=="string"?o.uri:t,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(a=>typeof a=="string"):[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(n,i)=>{l.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${n}`);let o={jsonrpc:M,id:e,result:m(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Mt(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){l.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let d=n.getDependenciesOnly();this.markDependencyTypesIncremental(d);let u=this.mergeDepsOnlyIntoModuleList(d,i);return this.applyModuleModelsUpdate(u),l.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=d,d}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return l.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];l.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=n.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),l.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),n=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,n),c=i.dependencies??{},d=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,b)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,b)}),this.markAddAndDeleteInDeps(a,d,(u,b)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,b)})}}getOldDepsForModule(e,t,n){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=n.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,n){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||n(i,e[i])}makeDeleteEntry(e,t){return new Le({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new et(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new tt([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let i=new Map(n.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=un(Fn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=un(Fn.join(t,"default/openharmony/ets/api")),o=un(Fn.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case g.HOVER:this.handleHoverRequest(e);break;case g.DEFINITION:this.handleDefinitionRequest(e);break;case g.REFERENCES:this.handleReferencesRequest(e);break;default:l.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!m(n)||typeof n.uri!="string"||!st(i)){l.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof o!="number"){l.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_HOVER,t,o,K.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!m(n)||typeof n.uri!="string"||!st(i)){l.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_DEFINITION,t,o,K.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!m(n)||typeof n.uri!="string"||!st(i)){l.error("Invalid client textDocument/references, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_FIND_USAGES,t,o,K.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!Ss(e)){l.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case g.DID_OPEN:this.handleDidOpenNotification(e);break;case g.DID_CHANGE:this.handleDidChangeNotification(e);break;case g.DID_CLOSE:this.handleDidCloseNotification(e);break;case g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case g.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:l.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!Os(n)||!qr(i)){l.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:i,textDocument:n};this.registerDiagnosticCallback(n.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!m(n)||typeof n.uri!="string"||typeof n.version!="number"){l.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(i)||!i.every(Ns)){l.error("Invalid client textDocument/didChange, contentChanges invalid");return}let o=n.uri,s=n.version;this.registerDiagnosticCallback(o),this.messageHandle.onAsyncDidChange({uri:o,version:s,contentChanges:i})}handleDidCloseNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!m(n)||typeof n.uri!="string"){l.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let i=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(n.uri,i)}handleDidChangePackageDependencies(e){let t=e.params;if(!m(t)){l.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:n}=t;if(!Array.isArray(n)||n.length===0){l.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!m(t)){l.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:n}=t;if(!Array.isArray(n)){l.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(n)}withResettableTimeout(e,t,n){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${n}ms`))},n)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}async dispose(){await this.messageHandle.stop()}};import*as ge from"fs";import*as V from"path";import{createHash as Yd}from"crypto";import{EventEmitter as Gd}from"events";var _n=class extends Gd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),n=new Set(this.watchers.keys());for(let i of t)n.has(i)||(this.watchFile(i),l.info(`[ConfigFileWatcher] Started watching: ${i}`));for(let i of n)t.has(i)||(this.unwatchFile(i),l.info(`[ConfigFileWatcher] Stopped watching: ${i}`));l.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!ge.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=ge.watch(t,n=>{n==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",n=>{l.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${n.message}`)}),l.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${n instanceof Error?n.message:String(n)}`)}}emitModuleAddedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:n,moduleName:i.name})}}emitModuleRemovedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:n,removedModuleName:i.name})}}emitModuleRenamedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){l.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,l.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=V.join(this.projectRoot,I.OH_PACKAGE_JSON5);ge.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=V.resolve(this.projectRoot,o.srcPath),a=V.join(s,I.OH_PACKAGE_JSON5);ge.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return V.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=ge.readFileSync(t,"utf-8");return Yd("sha256").update(n).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let n=this.computeFileHash(t);n&&this.contentHashes.set(t,n);let i=ge.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{l.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch ${t}: ${n instanceof Error?n.message:String(n)}`)}}unwatchFile(t){let n=this.watchers.get(t);n&&(n.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){l.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){l.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),l.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:V.basename(t),relativePath:V.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(),l.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ce from"fs";import*as Q from"path";import{createHash as Jd}from"crypto";import{EventEmitter as Kd}from"events";var Wn=class extends Kd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=Q.join(t,At)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ce.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ce.watch(this.depMapDir,{recursive:!0},(t,n)=>this.onDirEvent(t,n)),this.dirWatcher.on("error",t=>{l.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){l.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),l.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return F(Q.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===I.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===He)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Q.join(this.depMapDir,n);Ce.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,l.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Q.join(this.depMapDir,I.OH_PACKAGE_JSON5),n=Q.join(this.depMapDir,He),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:Q.join(this.depMapDir,s.name,I.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Ce.existsSync(s))continue;let c=this.canonicalPath(s),d=this.computeFileHash(s);if(!d)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,d);continue}u!==d&&(this.contentHashes.set(c,d),l.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Q.join(this.depMapDir,He);try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of n)i.add(o.info.newName);return i}emitIncrementalReload(t,n,i,o,s){l.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(l.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){l.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(n,i,o,s,a);for(let d of o)s.delete(d);if(o.size===0&&s.size===0&&a.length===0){l.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return F(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let n=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:n,bySrcPath:i}}detectModuleRenames(t,n,i,o){for(let[s,a]of t){let c=n.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let d=Q.join(this.depMapDir,a.name,I.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(d)),l.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=n.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),l.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,i){for(let[o]of t)i.has(o)||n.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,n,i){for(let[o]of t)if(!i.has(o)&&!n.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=Q.join(this.depMapDir,o,I.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),n=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);l.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(n,o,a,c),this.detectAddedModules(o,n,c),this.detectRemovedModules(n,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=Ce.readFileSync(t,"utf-8");return Jd("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as Zd}from"child_process";import*as zn from"path";import*as Bn from"fs";var Xd=600*1e3;function Qd(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function eu(r){let e=[],t=[];return r.stdout?.on("data",n=>{e.push(n.toString())}),r.stderr?.on("data",n=>{t.push(n.toString())}),{stdout:e,stderr:t}}function Un(r){return r.join("")}function tu(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
1235
+ `);if(n===-1)break;let o=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){l.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(o[1],10),a=n+4,c=a+s;if(this.buffer.length<c)break;let d=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(d);if(u&&u.rest.length>0){l.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${d.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",d),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let n=this.process;return!n||n.exitCode!==null||n.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),n.off("exit",a),i())},a=()=>s();n.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let n=t.search(/\S/);if(n<0||t[n]!=="{"&&t[n]!=="[")return null;let i=0,o=!1,s=!1;for(let a=n;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let d=t.slice(n,a+1),u=t.slice(a+1);return{json:d,rest:u}}}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 bn=class{callbacks=new Map;timeouts=new Map;register(e,t){this.callbacks.set(e,t)}emit(e,t,n){l.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);i&&(i(t,n),this.callbacks.delete(e))}registerTimeout(e,t,n,i){this.timeouts.has(e)&&clearTimeout(this.timeouts.get(e));let o=setTimeout(()=>{l.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},n);this.timeouts.set(e,o)}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)}clear(e){this.clearTimeout(e),this.callbacks.delete(e)}};var Sn=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let n=`${e}:${t}`;if(this.uniqueMessages.has(n)){l.info(`[Diagnostic] addMessage: duplicate message=${n}`);return}this.uniqueMessages.add(n),this.messages.push(new Xr(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)}},Xr=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var Pn=class{map=new Map;register(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}unregister(e,t){let n=this.map.get(e);n&&(t!==void 0?n.delete(t):n.clear(),n.size===0&&this.map.delete(e))}invoke(e,...t){let n=this.map.get(e);if(n)for(let i of n)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function m(r){return typeof r=="object"&&r!==null}function Zr(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}function nu(r){if(!m(r))return!1;let e=r.textDocument;return m(e)&&typeof e.uri=="string"}function ru(r){return m(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}function iu(r){return m(r)&&typeof r.moduleName=="string"&&typeof r.current=="number"&&typeof r.total=="number"?`indexing module '${r.moduleName}', ${r.current} of total ${r.total} modules`:`params=${JSON.stringify(r??null)}`}var En=class r{client;isInitialized=!1;stopOnce=null;callbacks=new Pn;requestCallbacks=new bn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new wn(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()=>{l.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:y.EXIT,params:{}}),X.EXIT),l.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),l.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)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(y.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(y.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:M,method:y.INITIALIZED,params:{editors:e}}),X.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:M,id:0,result:{}}),X.EMPTY)}sendAsyncRequest(e,t,n,i){if(!m(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!nu(t)){l.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof n!="number"){l.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(n)}`);return}let o=t.textDocument.uri,s=me(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;l.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(l.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!ru(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:M,method:y.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),y.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!m(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){l.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;l.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:y.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),X.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=me(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Sn(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,yn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:y.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),X.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=me(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,yn.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:y.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),X.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=me(e);l.info(`[LSP] didClose, uri: ${n}`);let i=this.diagnosticMap.get(n);if(!t&&(!i||i.isFromEditor)){l.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:y.DID_CLOSE,params:{textDocument:{uri:n}}}),X.DID_CLOSE)}getDiagnosticMessage(e){let t=me(e),n=this.diagnosticMap.get(t);return n?n.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let n=t instanceof Error?t.message:String(t);l.error(`[LSP] JSON parse error: ${n}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let n=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,y.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:M,method:y.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 y.MODULE_INIT_FINISH:return l.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(y.MODULE_INIT_FINISH),this.callbacks.unregister(y.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case y.INDEXING_PROGRESS_UPDATE:return l.info(`[LSP] onIndexingProgressUpdate: ${iu(t.params)}`),this.callbacks.invoke(y.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case y.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case y.ON_PACKAGE_CHANGE_FINISH:l.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case y.ON_ASYNC_HOVER:this.handleAsyncResponse(t,y.HOVER);return;case y.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,y.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case y.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,y.REFERENCES);return;default:l.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){l.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;m(t)&&m(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){l.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:M,method:y.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){l.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(n);return}if(!(t.length>0&&t[0]===!0)){l.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(n);return}l.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){l.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let n=e.params;if(!m(n)){l.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=n.requestId;if(typeof i!="number"){l.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,n)}handleForceOpenFile(e){if(!e){l.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,y.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){l.info("[LSP] publishDiagnostics uri is null");return}let n=e.version??-1;if(n===-1)return;let i=this.diagnosticMap.get(t);if(!i){l.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(n,JSON.stringify(s))}):i.setReceivedType(n),i.hasReceivedAllTypes(r.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,y.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),n={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=n[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let n=e[t];n&&typeof n.line=="number"&&(n.line=n.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,r.DIAGNOSTIC_TIMEOUT_MS,()=>{let n=this.diagnosticMap.get(e),i=n?n.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${r.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,n,i){let o={uri:e,diagnostics:n,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Vn from"path";import*as Mn from"path";var Cn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Dn=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var In=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var An=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var kn=class{typeSetting=new In;parameterNames=new An};var Tn=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=F(Mn.dirname(t)),this.indexingDataLocation=F(i),this.loggerPath=F(Mn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Cn;gutterIconsSetting=new Dn;inlayHintsSetting=new kn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Fs from"path";var Mt=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(F(Fs.join(e,"src","main","resources")))}};var ou="OS",Qe=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${ou}`;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 Mt(e)):this.buildProfileParam=new Mt}toString(){return JSON.stringify(this)}};var et=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as U from"path";import*as rt from"fs";var Rn=class{modulePath;dependencies={};dynamicDependencies={}};var Le=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 tt=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as ge from"path";import*as xn from"fs";var nt=class{name="";version="";storePath="";dependencyPath="";path=""};var P={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:"oh-package.json5",SYNC_OUTPUT_FILE:"output.json",ENV_FORCE_SYNC:"DEVECO_MCP_FORCE_SYNC"},Rt=`${P.HVIGOR_CACHE}/${P.DEPENDENCY}`,He=`${P.DEPENDENCY}${P.JSON5}`,$s=`${P.HVIGOR_CACHE}/outputs/sync/${P.SYNC_OUTPUT_FILE}`;var xt=class r{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,n){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new r(e,t,n),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,n){this.dependencyPath=e,this.modulePath=t,this.projectPath=n,this.fileSpecPattern=r.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=ge.join(this.dependencyPath,P.OH_PACKAGE_JSON5),n=W(t);n&&(this.dependencies=this.getDependencyList(n,P.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,P.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,P.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!m(e))return n;let i=e[t];if(!m(i))return n;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){l.error(`${o} package dependency value is not String ${t}`);continue}let a=new nt;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,i){if(!(!e||!t))try{let o=ge.normalize(ge.join(this.modulePath,P.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=o;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=o;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),ge.isAbsolute(s)){n.dependencyPath=o;return}i||(o=ge.normalize(ge.join(this.modulePath,s))),xn.existsSync(o)&&xn.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as Ot from"fs";import*as De from"path";import su from"json5";var On=class r{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 n=this.validateLockFile(t);return n.valid?(this.lockFileCache={modules:n.modules,storePathMap:this.parseStorePathMap(n.packages)},!0):!1}getLockFilePath(){return De.join(this.projectPath,P.OH_MODULES_PATH,P.OHPM_PATH,P.LOCK_JSON5_FILE)}readLockFile(e){if(!Ot.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Ot.readFileSync(e,"utf8"),n=su.parse(t);return n||(l.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return l.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!m(e))return l.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return l.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(l.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,P.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,P.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,P.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!m(e))return t;for(let[n,i]of Object.entries(e)){if(!m(i)){l.error(`${n} value is not json object`);continue}typeof i.storePath=="string"&&t.set(n,i.storePath)}return t}getDependencyList(e,t,n){if(!m(e))return[];for(let[i,o]of Object.entries(e))if(m(o)){let s=typeof o.name=="string"?o.name:"";if(n==="."&&s===""||s===n)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,n){let i=e[n];if(!m(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!m(s))return[];for(let[a,c]of Object.entries(s)){if(!m(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",v=new nt;v.name=a,v.version=u.startsWith(r.FILE_DEPENDENCY_PREFIX)?u.substring(r.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(v,n,a,d,u);let D=`${a}@${u}`;this.storePathMap.has(D)&&(v.storePath=this.storePathMap.get(D)||""),o.push(v)}return o}parseDependencyPath(e,t,n,i,o){let s=De.normalize(De.join(this.projectPath,t,P.OH_MODULES_PATH,n));try{let a=o;o.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(a=o.substring(r.FILE_DEPENDENCY_PREFIX.length));let c=a;if(De.isAbsolute(c)||(c=De.join(this.projectPath,a)),!Ot.existsSync(c)){e.dependencyPath=s;return}if(e.path=i,this.fileNameForOhpm.test(o)){e.dependencyPath=s;return}e.dependencyPath=c}catch(a){l.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var je=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Hs(this.projectRoot);try{let t=W(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function _s(r){return m(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Nt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new je(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,n=U.join(t,Rt),i=U.join(n,He);if(!rt.existsSync(n)||!rt.existsSync(i)){let c="Dependency map or JSON not found";return l.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return l.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let d=s[c];_s(d)&&(this.parseSingleModule(d,n,o,e),(c+1)%100===0&&l.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return l.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=U.join(n,Rt),o=U.join(i,He);if(!rt.existsSync(i)||!rt.existsSync(o))return l.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(d=>d.trim()).filter(Boolean)):null,a=new tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return l.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let d of c){if(!_s(d))continue;let u=d.name;if(s&&!s.has(u))continue;let v=d.srcPath,D=U.resolve(this.projectPath,v),le=U.join(i,u),Fe=F(D),$e=this.buildModuleDependencies(u,Fe,le,a);$e.moduleName=u,t.push($e)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=e.srcPath,a=U.resolve(this.projectPath,s),c=U.join(t,o),d=F(a),u=new Qe(d),v=this.buildModuleDependencies(o,d,c,n);this.parseModuleJson5(d,u);let D=this.parseMainPages(d);this.parseSdkJson(u),this.parseCompatibleSdkVersion(u),u.moduleName=o,u.moduleType=o,u.packageName=o,u.moduleDependencies=v,u.moduleJsonParam=new et(D),i.push(u)}buildModuleDependencies(e,t,n,i){let o=new tt(this.projectPath,e,t);xt.getInstance(n,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Rn;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let n={},i={};for(let o of e.finalDependencies)n[o.name]=new Le(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Le(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=U.join(e,P.OH_PACKAGE_JSON5);if(!rt.existsSync(n))return;xt.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 On(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let n=U.join(e,"src","main","module.json5"),i=W(n);if(!m(i)||!m(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(m(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)m(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=U.join(e,"src","main","resources","base","profile","main_pages.json"),n=W(t);return!m(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();!m(t)||!m(t.data)||(typeof t.data.apiVersion=="string"&&(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=U.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=W(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!m(t)||!m(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let n=t.app.products[0];if(!m(n)||typeof n.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(n.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=U.join(this.projectPath,"build-profile.json5");this.buildProfileCache=W(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!m(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 Nn=class{constructor(e=[]){this.valueSet=e}valueSet};var it=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Ws=(g=>(g[g.File=1]="File",g[g.Module=2]="Module",g[g.Namespace=3]="Namespace",g[g.Package=4]="Package",g[g.Class=5]="Class",g[g.Method=6]="Method",g[g.Property=7]="Property",g[g.Field=8]="Field",g[g.Constructor=9]="Constructor",g[g.Enum=10]="Enum",g[g.Interface=11]="Interface",g[g.Function=12]="Function",g[g.Variable=13]="Variable",g[g.Constant=14]="Constant",g[g.String=15]="String",g[g.Number=16]="Number",g[g.Boolean=17]="Boolean",g[g.Array=18]="Array",g[g.Object=19]="Object",g[g.Key=20]="Key",g[g.Null=21]="Null",g[g.EnumMember=22]="EnumMember",g[g.Struct=23]="Struct",g[g.Event=24]="Event",g[g.Operator=25]="Operator",g[g.TypeParameter=26]="TypeParameter",g))(Ws||{}),Us=()=>Object.values(Ws).filter(r=>typeof r=="number");var Ln=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Hn=class{applyEdit=!0;workspaceEdit=new Ln;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Nn(Us());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new it;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var jn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Fn=class{constructor(e=[]){this.valueSet=e}valueSet};var $n=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Bs=(b=>(b[b.Text=1]="Text",b[b.Method=2]="Method",b[b.Function=3]="Function",b[b.Constructor=4]="Constructor",b[b.Field=5]="Field",b[b.Variable=6]="Variable",b[b.Class=7]="Class",b[b.Interface=8]="Interface",b[b.Module=9]="Module",b[b.Property=10]="Property",b[b.Unit=11]="Unit",b[b.Value=12]="Value",b[b.Enum=13]="Enum",b[b.Keyword=14]="Keyword",b[b.Snippet=15]="Snippet",b[b.Color=16]="Color",b[b.File=17]="File",b[b.Reference=18]="Reference",b[b.Folder=19]="Folder",b[b.EnumMember=20]="EnumMember",b[b.Constant=21]="Constant",b[b.Struct=22]="Struct",b[b.Event=23]="Event",b[b.Operator=24]="Operator",b[b.TypeParameter=25]="TypeParameter",b))(Bs||{}),Vs=()=>Object.values(Bs).filter(r=>typeof r=="number");var _n=class{completionItemKind=new Fn(Vs());completionItem=new $n;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Wn=class{synchronization=new jn;completion=new _n;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 it;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Un=class{workspace=new Hn;textDocument=new Wn;notebookDocument=null;window=null;general=null;experimental=null};var Bn=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function ot(r){return m(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function zs(r){return m(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function qs(r){if(!m(r)||typeof r.text!="string")return!1;let e=r.range;return m(e)?ot(e.start)&&ot(e.end):!1}var zn=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=Vn.resolve(t,"ace-server","out","index.js"),this.logPath=Rs(),this.indexLogPath=i||this.logPath,this.messageHandle=new En({serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath}),this.messageHandle.setBroadcastToClients(s=>this.onLspMessage(s))}sdkPath;rootUri;nodeMaxOldSpaceSize;messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let n=!1;try{l.info(`serverPath: ${this.serverPath}`),l.info(`rootUri: ${this.rootUri}`),l.info(`sdkPath: ${this.sdkPath}`),l.info(`logPath: ${this.logPath}`);let i=me(this.rootUri),o=new Tn(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Nt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let d=Ls(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new Bn(i,o,new Un),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:M,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,v)=>{this.messageHandle.onIndexingProgressUpdate(v),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",At),this.messageHandle.sendInitialized(e),n=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),l.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(n)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=me(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=m(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:M,method:n,params:{uri:typeof o.uri=="string"?o.uri:t,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(a=>typeof a=="string"):[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(n,i)=>{l.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${n}`);let o={jsonrpc:M,id:e,result:m(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Nt(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){l.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let d=n.getDependenciesOnly();this.markDependencyTypesIncremental(d);let u=this.mergeDepsOnlyIntoModuleList(d,i);return this.applyModuleModelsUpdate(u),l.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=d,d}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return l.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];l.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=n.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),l.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),n=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,n),c=i.dependencies??{},d=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,v)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,v)}),this.markAddAndDeleteInDeps(a,d,(u,v)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,v)})}}getOldDepsForModule(e,t,n){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=n.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,n){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||n(i,e[i])}makeDeleteEntry(e,t){return new Le({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Qe(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new et([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let i=new Map(n.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=vn(Vn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=vn(Vn.join(t,"default/openharmony/ets/api")),o=vn(Vn.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.handleHoverRequest(e);break;case y.DEFINITION:this.handleDefinitionRequest(e);break;case y.REFERENCES:this.handleReferencesRequest(e);break;default:l.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!m(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof o!="number"){l.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(y.ON_ASYNC_HOVER,t,o,X.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!m(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(y.ON_ASYNC_DEFINITION,t,o,X.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!m(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/references, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(y.ON_ASYNC_FIND_USAGES,t,o,X.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!ks(e)){l.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.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:l.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!zs(n)||!Zr(i)){l.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:i,textDocument:n};this.registerDiagnosticCallback(n.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!m(n)||typeof n.uri!="string"||typeof n.version!="number"){l.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(i)||!i.every(qs)){l.error("Invalid client textDocument/didChange, contentChanges invalid");return}let o=n.uri,s=n.version;this.registerDiagnosticCallback(o),this.messageHandle.onAsyncDidChange({uri:o,version:s,contentChanges:i})}handleDidCloseNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!m(n)||typeof n.uri!="string"){l.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let i=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(n.uri,i)}handleDidChangePackageDependencies(e){let t=e.params;if(!m(t)){l.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:n}=t;if(!Array.isArray(n)||n.length===0){l.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!m(t)){l.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:n}=t;if(!Array.isArray(n)){l.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(n)}withResettableTimeout(e,t,n){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${n}ms`))},n)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}async dispose(){await this.messageHandle.stop()}};import*as ye from"fs";import*as q from"path";import{createHash as au}from"crypto";import{EventEmitter as cu}from"events";var qn=class extends cu{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),n=new Set(this.watchers.keys());for(let i of t)n.has(i)||this.watchFile(i);for(let i of n)t.has(i)||(this.unwatchFile(i),l.info(`[ConfigFileWatcher] Stopped watching: ${i}`));l.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!ye.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=ye.watch(t,n=>{n==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",n=>{l.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${n.message}`)}),l.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${n instanceof Error?n.message:String(n)}`)}}emitModuleAddedEvents(t,n){for(let i of t){let o=q.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:n,moduleName:i.name})}}emitModuleRemovedEvents(t,n){for(let i of t){let o=q.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:n,removedModuleName:i.name})}}emitModuleRenamedEvents(t,n){for(let i of t){let o=q.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,n){for(let i of t){let o=q.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){l.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,l.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=W(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=q.join(this.projectRoot,P.OH_PACKAGE_JSON5);ye.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=q.resolve(this.projectRoot,o.srcPath),a=q.join(s,P.OH_PACKAGE_JSON5);ye.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return q.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=ye.readFileSync(t,"utf-8");return au("sha256").update(n).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let n=this.computeFileHash(t);n&&this.contentHashes.set(t,n);let i=ye.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{l.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch ${t}: ${n instanceof Error?n.message:String(n)}`)}}unwatchFile(t){let n=this.watchers.get(t);n&&(n.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){l.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){l.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),l.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:q.basename(t),relativePath:q.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(),l.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ie from"fs";import*as ee from"path";import{createHash as lu}from"crypto";import{EventEmitter as du}from"events";var Yn=class extends du{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=ee.join(t,Rt)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ie.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ie.watch(this.depMapDir,{recursive:!0},(t,n)=>this.onDirEvent(t,n)),this.dirWatcher.on("error",t=>{l.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){l.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),l.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return F(ee.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===P.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===He)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=ee.join(this.depMapDir,n);Ie.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,l.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=ee.join(this.depMapDir,P.OH_PACKAGE_JSON5),n=ee.join(this.depMapDir,He),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:ee.join(this.depMapDir,s.name,P.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Ie.existsSync(s))continue;let c=this.canonicalPath(s),d=this.computeFileHash(s);if(!d)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,d);continue}u!==d&&(this.contentHashes.set(c,d),l.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=ee.join(this.depMapDir,He);try{let n=W(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of n)i.add(o.info.newName);return i}emitIncrementalReload(t,n,i,o,s){l.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(l.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){l.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(n,i,o,s,a);for(let d of o)s.delete(d);if(o.size===0&&s.size===0&&a.length===0){l.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return F(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let n=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:n,bySrcPath:i}}detectModuleRenames(t,n,i,o){for(let[s,a]of t){let c=n.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let d=ee.join(this.depMapDir,a.name,P.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(d)),l.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=n.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),l.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,i){for(let[o]of t)i.has(o)||n.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,n,i){for(let[o]of t)if(!i.has(o)&&!n.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=ee.join(this.depMapDir,o,P.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),n=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);l.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(n,o,a,c),this.detectAddedModules(o,n,c),this.detectRemovedModules(n,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=Ie.readFileSync(t,"utf-8");return lu("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as uu}from"child_process";import*as Kn from"path";import*as Jn from"fs";var pu=600*1e3;function hu(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function fu(r){let e=[],t=[];return r.stdout?.on("data",n=>{e.push(n.toString())}),r.stderr?.on("data",n=>{t.push(n.toString())}),{stdout:e,stderr:t}}function Gn(r){return r.join("")}function mu(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
1236
1236
  Output so far:
1237
- `+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function nu(r,e,t){return new Promise(n=>{let i=Zd(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=eu(i),a=setTimeout(()=>{i.kill();let c=[Un(o),Un(s)].filter(Boolean).join(`
1237
+ `+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function gu(r,e,t){return new Promise(n=>{let i=uu(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=fu(i),a=setTimeout(()=>{i.kill();let c=[Gn(o),Gn(s)].filter(Boolean).join(`
1238
1238
  `).trim();n({success:!1,output:`Build process timeout after 10 minutes.
1239
1239
  Output so far:
1240
- `+c,exitCode:-1})},Xd);i.on("close",(c,d)=>{clearTimeout(a);let u=[Un(o),Un(s)].filter(Boolean).join(`
1241
- `).trim()||"";n(tu(c,d,u))}),i.on("error",c=>{clearTimeout(a),n({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Yr(r,e,t,n,i){let o={...process.env,DEVECO_SDK_HOME:n},s=Qd(e,t,i);return await nu(s,r,o)}function ru(r){let e=zn.join(zn.dirname(r),"tools","hvigor","bin","hvigorw.js");return{node_path:an(r),hvigor_path:e,sdk_path:r}}function iu(r){return!r.node_path||!Bn.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!Bn.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!Bn.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var ou="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Ls(r,e){try{let t=ru(e),n=iu(t);return n!=null?(l.info(`Config validation failed: ${n}`),!1):(await Yr(r,t.node_path,t.hvigor_path,e,ou)).success}catch(t){return l.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as su}from"child_process";import*as Gr from"fs";import*as xt from"path";var au=["install","--all"];function cu(r){let e=r.replace(/sdk\/?$/i,"tools"),t=xt.join(e,"ohpm","bin","pm-cli.js");if(Gr.existsSync(t))return t;let n=r.toLowerCase().endsWith("sdk")?xt.dirname(r):r;return t=xt.join(n,"ohpm","bin","pm-cli.js"),Gr.existsSync(t)?t:null}async function lu(r,e,t,n){return new Promise(i=>{let o=su(r,[e,...au],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},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 d=[s,a].filter(Boolean).join(`
1240
+ `+c,exitCode:-1})},pu);i.on("close",(c,d)=>{clearTimeout(a);let u=[Gn(o),Gn(s)].filter(Boolean).join(`
1241
+ `).trim()||"";n(mu(c,d,u))}),i.on("error",c=>{clearTimeout(a),n({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Qr(r,e,t,n,i){let o={...process.env,DEVECO_SDK_HOME:n},s=hu(e,t,i);return await gu(s,r,o)}function yu(r){let e=Kn.join(Kn.dirname(r),"tools","hvigor","bin","hvigorw.js");return{node_path:hn(r),hvigor_path:e,sdk_path:r}}function vu(r){return!r.node_path||!Jn.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!Jn.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!Jn.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var wu="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Ys(r,e){try{let t=yu(e),n=vu(t);return n!=null?(l.info(`Config validation failed: ${n}`),!1):(await Qr(r,t.node_path,t.hvigor_path,e,wu)).success}catch(t){return l.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as bu}from"child_process";import*as ei from"fs";import*as Lt from"path";var Su=["install","--all"];function Pu(r){let e=r.replace(/sdk\/?$/i,"tools"),t=Lt.join(e,"ohpm","bin","pm-cli.js");if(ei.existsSync(t))return t;let n=r.toLowerCase().endsWith("sdk")?Lt.dirname(r):r;return t=Lt.join(n,"ohpm","bin","pm-cli.js"),ei.existsSync(t)?t:null}async function Eu(r,e,t,n){return new Promise(i=>{let o=bu(r,[e,...Su],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},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 d=[s,a].filter(Boolean).join(`
1242
1242
  `);i({exitCode:c??-1,output:d})}),o.on("error",c=>{let d=[s,a].filter(Boolean).join(`
1243
1243
  `);i({exitCode:-1,output:d+`
1244
- `+c.message})})})}function du(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>l.info("[ohpm] %s",e))}async function Hs(r,e){try{let t=an(e);if(!t)return l.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let n=cu(e);if(!n)return l.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await lu(t,n,r,e);return du(o),i===0?(l.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(l.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),l.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return l.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var js={UNINITIALIZED:-32099,UNKNOWN:-32e3},Rt=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,js.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,js.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var at=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t){if(l.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return l.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),!1;if(!await Hs(e,t))return l.error("[ArktsLspManager] ohpm install failed"),!1;let i=await Ls(e,t);return i?l.info("[ArktsLspManager] syncProject completed successfully"):l.error("[ArktsLspManager] syncProject failed"),i}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){l.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new $n(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)l.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:M,method:g.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();l.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?Rt.uninitialized(t):Rt.unknown();this.onMessage({jsonrpc:M,method:g.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(l.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:M,method:g.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new _n(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Wn(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){l.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let n=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.lspProxy.sendNotification({jsonrpc:M,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:n}}),this.onMessage({jsonrpc:M,method:g.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}handleConfigChanged(e){l.info(`[ArktsLspManager] Config file changed: ${e.filePath}`);try{let t=e.kind??4,n={jsonrpc:M,method:g.WORKSPACE_DID_CHANGE_CONFIGURATION,params:{relativePath:e.relativePath,timestamp:e.timestamp,changeSource:e.source,changeSignal:t,...e.filePath&&{filePath:e.filePath},...e.fileName!==void 0&&{fileName:e.fileName},...e.moduleName!==void 0&&{moduleName:e.moduleName},...e.removedModuleName!==void 0&&{removedModuleName:e.removedModuleName}}};this.onMessage(n)}catch(t){l.error(`[ArktsLspManager] Failed to handle config change: ${t instanceof Error?t.message:String(t)}`)}}};var uu=120*1e3,pu=300*1e3,hu=180*1e3,fu=10080*60*1e3,mu=7200*60*1e3,ct=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;arktsLangServerPath;nodeMaxOldSpaceSize;constructor(e,t,n){this.projectPath=e,this.devecoPath=t??"",this.arktsLangServerPath=null,this.nodeMaxOldSpaceSize=n}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:Jr.object({files:Jr.array(Jr.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:n}=this.resolveProjectAndDeveco(),i=ce(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{_r(s,fu,"[ArkTS-Check]"),_r(o,mu,"[ArkTS-Check]")}),Es(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a,d=ee.join(ae(t),"sdk");f.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${ae(t)}, sdkPath: ${d}`),this.manager=new at({sdkPath:d,arktsLangServerPath:n,workspaceRoot:F(i),indexLogPath:s,nodeMaxOldSpaceSize:c}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),await new Promise((u,b)=>{this.initResolve=u,this.initReject=b,this.armInitTimer(pu),this.manager.start([]).catch(k=>{let le=k instanceof Error?k:new Error(String(k));this.failInit(le)})})}resolveProjectAndDeveco(){let e=he(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Oe();if(f.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=ls(t);if(!n)throw new Error("arkts-lang-server path not found");return this.arktsLangServerPath=n,{harmonyRoot:e,devecoPath:t,arktsLangServerPath:n}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=Dt(Ne(e)),n=$r(e),i=await ye.promises.readFile(e,"utf8"),s=`deveco.apptool.${ee.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((d,u)=>{let b=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},uu);this.diagnosticWaiters.set(t,{resolve:d,reject:u,timer:b})}),c={textDocument:{uri:n,text:i,languageId:s,version:i.length},editorFiles:[n],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${n} content_len=${i.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],n=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1245
- `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,n),this.formatCallResult(t,n))}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=ee.isAbsolute(o)?o:ee.join(n,o);if(!ye.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!ye.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,n){for(let i of e){await ps(500);try{let o=await this.checkFile(i);n.push(gu(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let n=[];e.length>0&&n.push(e.join(`
1244
+ `+c.message})})})}function Cu(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>l.info("[ohpm] %s",e))}async function Gs(r,e){try{let t=hn(e);if(!t)return l.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let n=Pu(e);if(!n)return l.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await Eu(t,n,r,e);return Cu(o),i===0?(l.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(l.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),l.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return l.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Js={UNINITIALIZED:-32099,UNKNOWN:-32e3},Ht=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,Js.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,Js.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var st=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,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t){if(l.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return l.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let n=await yi(e,async()=>await Gs(e,t)?await Ys(e,t)?(l.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(l.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(l.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return n.acquired?n.result:(l.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){l.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){l.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new zn(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)l.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:M,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();l.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?Ht.uninitialized(t):Ht.unknown();this.onMessage({jsonrpc:M,method:y.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(l.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:M,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new qn(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Yn(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){l.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let n=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.lspProxy.sendNotification({jsonrpc:M,method:y.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:n}}),this.onMessage({jsonrpc:M,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){l.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var Du=120*1e3,Iu=10080*60*1e3,Au=7200*60*1e3,at=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;constructor(e,t,n){this.projectPath=e,this.devecoPath=t??"",this.nodeMaxOldSpaceSize=n}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:ti.object({files:ti.array(ti.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:n}=this.resolveProjectAndDeveco(),i=ce(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{qr(s,Iu,"[ArkTS-Check]"),qr(o,Au,"[ArkTS-Check]")}),Ms(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let d=te.join(ae(t),"sdk");f.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${ae(t)}, sdkPath: ${d}`),this.manager=new st({sdkPath:d,arktsLangServerPath:n,workspaceRoot:F(i),indexLogPath:s,nodeMaxOldSpaceSize:c}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((u,v)=>{this.initResolve=u,this.initReject=v,this.armInitTimer(At),this.manager.start([]).catch(D=>{let le=D instanceof Error?D:new Error(String(D));this.failInit(le)})})}resolveProjectAndDeveco(){let e=fe(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Oe();if(f.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=gs(t);if(!n)throw new Error("arkts-lang-server path not found");return{harmonyRoot:e,devecoPath:t,arktsLangServerPath:n}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=It(Ne(e)),n=zr(e),i=await ve.promises.readFile(e,"utf8"),s=`deveco.apptool.${te.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((d,u)=>{let v=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},Du);this.diagnosticWaiters.set(t,{resolve:d,reject:u,timer:v})}),c={textDocument:{uri:n,text:i,languageId:s,version:i.length},editorFiles:[n],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${n} content_len=${i.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],n=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
1245
+ `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,n),this.formatCallResult(t,n))}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=te.isAbsolute(o)?o:te.join(n,o);if(!ve.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!ve.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,n){for(let i of e){await ws(500);try{let o=await this.checkFile(i);n.push(ku(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let n=[];e.length>0&&n.push(e.join(`
1246
1246
  `)),t.length>0&&n.push(t.join(`
1247
1247
  `));let i=n.join(`
1248
- `).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(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(hu),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";f.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let n=this.resolveDiagnosticWaiter(t);if(!n)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),n.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;f.debug(`diagnostics received uri=${t} count=${o}`),n.resolve(Array.isArray(i)?i:[])}resolveDiagnosticWaiter(e){let t=Dt(e),n=this.popDiagnosticWaiter(t);if(n)return n;for(let i of fs(e)){let o=this.popDiagnosticWaiter(i);if(o)return o}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,n]of this.diagnosticWaiters)clearTimeout(n.timer),n.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=ee.join(sn(),"ArkTSCheck"),n=ee.join(t,"mapping-config.properties"),i=ms(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=ee.join(t,"lsp-log",String(i),o),a=ee.join(t,"lsp-index",String(i));return ye.mkdirSync(s,{recursive:!0}),ye.mkdirSync(a,{recursive:!0}),{logPath:ce(s),indexPath:ce(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function gu(r,e){if(Array.isArray(e))return e.length===0?`${r} => no diagnostics`:`${r} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${r} diagnostic failed, error_message: ${t}`}return`${r} => diagnostic failed, result: ${JSON.stringify(e)}`}import{spawn as yu}from"child_process";import*as A from"fs";import*as N from"path";import{z as Kr}from"zod";var Fs=60*1e3,vu=30*1e3,wu=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),bu=1e3,Zr=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let n=ce(this.projectPath),i=Ne(n),o=N.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.8.0"},rootPath:n,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,Fs),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=Fs,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(n=>setTimeout(n,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=A.realpathSync(e)}catch{t=e}let n=Ne(t),i=hs(t),o=await A.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(n)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},vu);this.diagnosticWaiters.set(n,{resolve:a,reject:c,timer:d})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,languageId:i,version:1,text:o}})}catch(a){let c=this.diagnosticWaiters.get(n);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(n)),a}try{return await s}finally{await this.closeFile(n).catch(a=>{f.warn(`[CppCheck] didClose failed for ${n}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(n);return}wu.has(e)&&this.queuedDocumentNotifications.push(n)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,n){let i=this.nextRequestId++;return new Promise((o,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(i)&&s(new Error(`Timed out waiting for ${e} response`))},n);this.pendingRequests.set(i,{resolve:o,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:i,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(i)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,n)=>{let i;try{i=JSON.stringify(e)}catch(u){n(new Error(`Failed to encode LSP message: ${u}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
1248
+ `).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(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(At),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";f.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let n=this.resolveDiagnosticWaiter(t);if(!n)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),n.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;f.debug(`diagnostics received uri=${t} count=${o}`),n.resolve(Array.isArray(i)?i:[])}resolveDiagnosticWaiter(e){let t=It(e),n=this.popDiagnosticWaiter(t);if(n)return n;for(let i of Ss(e)){let o=this.popDiagnosticWaiter(i);if(o)return o}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,n]of this.diagnosticWaiters)clearTimeout(n.timer),n.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=te.join(pn(),"ArkTSCheck"),n=te.join(t,"mapping-config.properties"),i=Ps(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=te.join(t,"lsp-log",String(i),o),a=te.join(t,"lsp-index",String(i));return ve.mkdirSync(s,{recursive:!0}),ve.mkdirSync(a,{recursive:!0}),{logPath:ce(s),indexPath:ce(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function ku(r,e){if(Array.isArray(e))return e.length===0?`${r} => no diagnostics`:`${r} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${r} diagnostic failed, error_message: ${t}`}return`${r} => diagnostic failed, result: ${JSON.stringify(e)}`}import{spawn as Tu}from"child_process";import*as k from"fs";import*as N from"path";import{z as ni}from"zod";var Ks=60*1e3,Mu=30*1e3,Ru=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),xu=1e3,ri=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let n=ce(this.projectPath),i=Ne(n),o=N.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"1.2.0"},rootPath:n,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,Ks),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=Ks,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(n=>setTimeout(n,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=k.realpathSync(e)}catch{t=e}let n=Ne(t),i=bs(t),o=await k.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(n)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},Mu);this.diagnosticWaiters.set(n,{resolve:a,reject:c,timer:d})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,languageId:i,version:1,text:o}})}catch(a){let c=this.diagnosticWaiters.get(n);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(n)),a}try{return await s}finally{await this.closeFile(n).catch(a=>{f.warn(`[CppCheck] didClose failed for ${n}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(n);return}Ru.has(e)&&this.queuedDocumentNotifications.push(n)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,n){let i=this.nextRequestId++;return new Promise((o,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(i)&&s(new Error(`Timed out waiting for ${e} response`))},n);this.pendingRequests.set(i,{resolve:o,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:i,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(i)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,n)=>{let i;try{i=JSON.stringify(e)}catch(u){n(new Error(`Failed to encode LSP message: ${u}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
1249
1249
  \r
1250
1250
  `,"ascii"),a=!1,c=u=>{a||(a=!0,u?n(u):t())};if(this.clangdStdin.write(Buffer.concat([s,o]),u=>{u?c(u):a||c()}))c();else{let u=()=>c();this.clangdStdin.once("drain",u)}})}handleClangdData(e){for(this.clangdBuffer=this.clangdBuffer.length===0?e:Buffer.concat([this.clangdBuffer,e]);;){let t=this.clangdBuffer.indexOf(`\r
1251
1251
  \r
1252
- `);if(t<0)return;let n=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(n);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){f.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,n=t.uri;if(!n)return;let i=Su(n),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];f.info(`[CppCheck] Received C++ diagnostics for ${i} (${s.length} entries)`),o.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(n=>{t=n}),await e,t}};function Su(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),Ne(t)}}catch{}return r}function Pu(r){let e=N.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Eu(r,e){let t=N.join(r,e.name);return e.isDirectory()?e.name===".cxx"||$s(t):Pu(t)}function $s(r){if(!A.existsSync(r))return!1;try{return A.readdirSync(r,{withFileTypes:!0}).some(t=>Eu(r,t))}catch{}return!1}function _s(r){let t=new je(r).getAllModuleInfo(),n=[];for(let i of t){let o=i.srcPath.replace(/^\.\//,""),s=N.join(r,o);$s(s)&&n.push(i)}return n}function Du(r){let e=[],n=new je(r).getAllModuleInfo();for(let i of n){let o=i.srcPath.replace(/^\.\//,""),s=N.join(r,o,".cxx");A.existsSync(s)&&Ws(s,e)}return e}function Ws(r,e){try{let t=A.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=N.join(r,n.name);n.isDirectory()?Ws(i,e):n.name==="compile_commands.json"&&e.push(i)}}catch{}}function Iu(r){let e=[];for(let t of r)try{let n=A.readFileSync(t,"utf8"),i=JSON.parse(n);e.push(...i)}catch{}return e}function Cu(r,e){let t=N.join(r,...jr.slice(0,-1));A.mkdirSync(t,{recursive:!0});let n=N.join(t,"compile_commands.json");A.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function Au(r){let e=Du(r);if(e.length>0){let t=Iu(e);Cu(r,t),f.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else f.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function ku(r){let e=new Set;for(let t of r)if(t.file)try{e.add(A.realpathSync(t.file))}catch{e.add(t.file)}return e}function Tu(r,e){try{let t=A.realpathSync(r);if(!e.has(t))return f.info(`[CppCheck] File not covered by compile_commands.json: ${r}`),!1}catch{}return!0}function Mu(r,e){if(!A.existsSync(r))return!1;try{let t=A.readFileSync(r,"utf8"),n=JSON.parse(t),i=ku(n);for(let o of e)if(!Tu(o,i))return!1;return!0}catch(t){return f.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function xu(r,e,t){let n=N.join(ae(e),"sdk"),i=process.execPath||"node",o=N.join(ae(e),"tools");f.info(`CppCheck devecoPath: ${e}, contentRoot: ${ae(e)}, sdkPath: ${n}, toolsDir: ${o}`);let s=N.join(o,"hvigor","bin","hvigorw.js");for(let a of t){let c=["--mode","module","-p",`module=${a.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");f.info(`[CppCheck] Running compileNative for module: ${a.name}`);let d=await Yr(r,i,s,n,c);d.success?f.info(`[CppCheck] compileNative ${a.name} \u6210\u529F`):f.warn(`[CppCheck] compileNative ${a.name} \u5931\u8D25: ${d.output}`)}}async function Ru(r,e){let t=_s(r);if(t.length===0){f.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}f.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(n=>n.name).join(", ")}`),await xu(r,e,t),Au(r)}var lt=class{projectPath;devecoPath;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.devecoPath=rn(t??"")??t??null}static getToolDefinition(){return{name:"check_cpp_files",description:"\u5BF9\u4F20\u5165\u7684 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE clangd \u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Kr.object({files:Kr.array(Kr.string()).describe('\u5F85\u68C0\u67E5\u7684 C/C++ \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.cpp","file2.hpp",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.client!==null&&this.initializedProjectPath!==null}async handleCall(e){let t=[],n=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1252
+ `);if(t<0)return;let n=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(n);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){f.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,n=t.uri;if(!n)return;let i=Ou(n),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];f.info(`[CppCheck] Received C++ diagnostics for ${i} (${s.length} entries)`),o.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(n=>{t=n}),await e,t}};function Ou(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),Ne(t)}}catch{}return r}function Nu(r){let e=N.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Lu(r,e){let t=N.join(r,e.name);return e.isDirectory()?e.name===".cxx"||Xs(t):Nu(t)}function Xs(r){if(!k.existsSync(r))return!1;try{return k.readdirSync(r,{withFileTypes:!0}).some(t=>Lu(r,t))}catch{}return!1}function Zs(r){let t=new je(r).getAllModuleInfo(),n=[];for(let i of t){let o=i.srcPath.replace(/^\.\//,""),s=N.join(r,o);Xs(s)&&n.push(i)}return n}function Hu(r){let e=[],n=new je(r).getAllModuleInfo();for(let i of n){let o=i.srcPath.replace(/^\.\//,""),s=N.join(r,o,".cxx");k.existsSync(s)&&Qs(s,e)}return e}function Qs(r,e){try{let t=k.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=N.join(r,n.name);n.isDirectory()?Qs(i,e):n.name==="compile_commands.json"&&e.push(i)}}catch{}}function ju(r){let e=[];for(let t of r)try{let n=k.readFileSync(t,"utf8"),i=JSON.parse(n);e.push(...i)}catch{}return e}function Fu(r,e){let t=N.join(r,...Br.slice(0,-1));k.mkdirSync(t,{recursive:!0});let n=N.join(t,"compile_commands.json");k.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function $u(r){let e=Hu(r);if(e.length>0){let t=ju(e);Fu(r,t),f.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else f.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function _u(r){let e=new Set;for(let t of r)if(t.file)try{e.add(k.realpathSync(t.file))}catch{e.add(t.file)}return e}function Wu(r,e){try{let t=k.realpathSync(r);if(!e.has(t))return f.info(`[CppCheck] File not covered by compile_commands.json: ${r}`),!1}catch{}return!0}function Uu(r,e){if(!k.existsSync(r))return!1;try{let t=k.readFileSync(r,"utf8"),n=JSON.parse(t),i=_u(n);for(let o of e)if(!Wu(o,i))return!1;return!0}catch(t){return f.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function Bu(r,e,t){let n=N.join(ae(e),"sdk"),i=process.execPath||"node",o=N.join(ae(e),"tools");f.info(`CppCheck devecoPath: ${e}, contentRoot: ${ae(e)}, sdkPath: ${n}, toolsDir: ${o}`);let s=N.join(o,"hvigor","bin","hvigorw.js");for(let a of t){let c=["--mode","module","-p",`module=${a.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");f.info(`[CppCheck] Running compileNative for module: ${a.name}`);let d=await Qr(r,i,s,n,c);d.success?f.info(`[CppCheck] compileNative ${a.name} \u6210\u529F`):f.warn(`[CppCheck] compileNative ${a.name} \u5931\u8D25: ${d.output}`)}}async function Vu(r,e){let t=Zs(r);if(t.length===0){f.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}f.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(n=>n.name).join(", ")}`),await Bu(r,e,t),$u(r)}var ct=class{projectPath;devecoPath;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.devecoPath=dn(t??"")??t??null}static getToolDefinition(){return{name:"check_cpp_files",description:"\u5BF9\u4F20\u5165\u7684 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE clangd \u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:ni.object({files:ni.array(ni.string()).describe('\u5F85\u68C0\u67E5\u7684 C/C++ \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.cpp","file2.hpp",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.client!==null&&this.initializedProjectPath!==null}async handleCall(e){let t=[],n=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
1253
1253
  `):"\u6CA1\u6709\u6709\u6548\u7684 C/C++ \u6587\u4EF6"}],isError:!0};let o;try{o=await this.ensureInitializedWithFiles(i)}catch(a){return t.push(a.message),{content:[{type:"text",text:t.join(`
1254
1254
  `)}],isError:!0}}return await this.runDiagnosticsForFiles(o,i,t,n)&&this.shutdown().catch(a=>{f.warn(`[CppCheck] shutdown after diagnostic failure: ${a}`)}),this.formatCallResult(t,n)}async runDiagnosticsForFiles(e,t,n,i){let o=!1;for(let s of t)try{let a=await e.checkFile(s);a.length===0?i.push(`${s} => \u65E0\u8BCA\u65AD`):i.push(`${s} => Diagnostic: ${JSON.stringify(a)}`)}catch(a){o=!0,n.push(`${s} => \u83B7\u53D6\u8BCA\u65AD\u5931\u8D25: ${a.message}`)}return o}formatCallResult(e,t){let n=e.length>0;return!n&&t.length===0&&t.push("\u6CA1\u6709\u8FD4\u56DE\u4EFB\u4F55\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:[t.join(`
1255
1255
  `),e.join(`
1256
1256
  `)].filter(o=>o.trim().length>0).join(`
1257
- `).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=ce(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??Oe();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,await Ru(t,i)}else if(this.client&&this.initializedProjectPath){let i=ce(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let n=nn(e);return A.existsSync(n)?_s(e).length===0?(f.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Mu(n,t)?(f.info("[CppCheck] All files covered, no initialization needed"),!1):(f.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(f.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new Zr,await this.client.initialize(e),this.initializedProjectPath=e,f.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=he(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ce(e)}startPollingForClangd(e){let t=nn(e);if(A.existsSync(t)){f.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(n=>{f.error(`[CppCheck] Immediate clangd spawn failed: ${n}`)});return}f.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}A.existsSync(t)&&(this.stopPolling(),f.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(n=>{f.error(`[CppCheck] Clangd spawn from poll failed: ${n}`)}))},bu)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:n}=this.resolveClangdPaths(e);f.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let i=this.spawnClangd(t,e,n);this.clangdProcess=i;try{await this.client.connectClangdProcess(i.stdin,i.stdout),this.backendReady=!0,f.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(f.error(`[CppCheck] Failed to connect clangd: ${o}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw o}}resolveClangdPaths(e){let t=this.devecoPath??Oe();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=ds(t);if(!n)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=nn(e),o=N.dirname(i);return{clangdPath:n,compileCommandsDir:o}}spawnClangd(e,t,n){let i=yu(e,[`--compile-commands-dir=${n}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Failed to start clangd: stdio not available");return i.stderr.on("data",o=>{let s=o.toString("utf8").trimEnd();s&&f.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{f.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{f.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=N.isAbsolute(o)?o:N.join(n,o);if(!A.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!A.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!on(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(A.realpathSync(s))}catch{i.push(s)}}return i}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(n){f.warn(`[CppCheck] client.close() failed: ${n}`)}if(t&&!t.killed)try{t.kill()}catch(n){f.warn(`[CppCheck] failed to kill clangd: ${n}`)}}};var Us=(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))(Us||{}),Qr=3,Vn=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";constructor(e={}){this.config=e,Ur(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),f.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",f.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,f.info(`Constructor: using configured path as startPath: '${t}'`));let i=he(t);f.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new Ou({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Nr(),this.registerTools()}registerTools(){this.toolRouter.add({name:"check",description:"\u5BF9\u4F20\u5165\u7684 ArkTS (.ets) \u6216 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002\u5DE5\u5177\u4F1A\u6839\u636E\u6587\u4EF6\u6269\u5C55\u540D\u81EA\u52A8\u9009\u62E9\u68C0\u67E5\u5668\uFF1A.ets \u8D70 ArkTS-Check\uFF0C.c/.cc/.cpp/.cxx/.h/.hh/.hpp/.hxx \u7B49\u8D70 clangd\u3002",inputSchema:Xr.object({files:Xr.array(Xr.string()).describe('\u5F85\u68C0\u67E5\u7684\u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u53EF\u540C\u65F6\u5305\u542B ArkTS (.ets) \u548C C/C++ \u6587\u4EF6\uFF0C\u683C\u5F0F\u4E3A ["src/main.ets","native/foo.cpp",...]')})},async e=>this.handleCheckCall(e))}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=E.isPathContainedWithSymlink(o,t);s.contained||(f.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1258
- `)}],isError:!0}:null}let n=e.filter(i=>dt.isAbsolute(i));return n.length>0?(f.warn(`Absolute paths rejected (no project root): ${n.join(", ")}`),{content:[{type:"text",text:n.map(i=>`\u4E0D\u5141\u8BB8\u4F7F\u7528\u7EDD\u5BF9\u8DEF\u5F84: ${i}`).join(`
1259
- `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(b=>typeof b=="string"):[];if(t.length===0)return f.warn("check tool called with empty files list"),{content:[{type:"text",text:"\u6CA1\u6709\u4F20\u5165\u4EFB\u4F55\u6587\u4EF6"}],isError:!0};let n=this.validateContainment(t);if(n)return n;let{etsFiles:i,cppFiles:o,unsupported:s}=Lu(t);s.length>0&&f.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(b=>`\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B: ${b}\uFF08\u4EC5\u652F\u6301 .ets \u4E0E C/C++ \u6E90/\u5934\u6587\u4EF6\uFF09`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let d=a.length>0;return{content:[{type:"text",text:[c.join(`
1257
+ `).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=ce(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??Oe();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,await Vu(t,i)}else if(this.client&&this.initializedProjectPath){let i=ce(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let n=ln(e);return k.existsSync(n)?Zs(e).length===0?(f.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Uu(n,t)?(f.info("[CppCheck] All files covered, no initialization needed"),!1):(f.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(f.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new ri,await this.client.initialize(e),this.initializedProjectPath=e,f.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=fe(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ce(e)}startPollingForClangd(e){let t=ln(e);if(k.existsSync(t)){f.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(n=>{f.error(`[CppCheck] Immediate clangd spawn failed: ${n}`)});return}f.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}k.existsSync(t)&&(this.stopPolling(),f.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(n=>{f.error(`[CppCheck] Clangd spawn from poll failed: ${n}`)}))},xu)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:n}=this.resolveClangdPaths(e);f.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let i=this.spawnClangd(t,e,n);this.clangdProcess=i;try{await this.client.connectClangdProcess(i.stdin,i.stdout),this.backendReady=!0,f.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(f.error(`[CppCheck] Failed to connect clangd: ${o}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw o}}resolveClangdPaths(e){let t=this.devecoPath??Oe();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=ys(t);if(!n)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=ln(e),o=N.dirname(i);return{clangdPath:n,compileCommandsDir:o}}spawnClangd(e,t,n){let i=Tu(e,[`--compile-commands-dir=${n}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Failed to start clangd: stdio not available");return i.stderr.on("data",o=>{let s=o.toString("utf8").trimEnd();s&&f.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{f.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{f.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=N.isAbsolute(o)?o:N.join(n,o);if(!k.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!k.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!un(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(k.realpathSync(s))}catch{i.push(s)}}return i}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(n){f.warn(`[CppCheck] client.close() failed: ${n}`)}if(t&&!t.killed)try{t.kill()}catch(n){f.warn(`[CppCheck] failed to kill clangd: ${n}`)}}};import*as dt from"fs";import*as lt from"path";var zu=1e3;function ea(r,e){if(e)return l.info(`[SyncGuard] ${P.ENV_FORCE_SYNC}=1, forcing sync`),{required:!0,reason:`${P.ENV_FORCE_SYNC}=1`};let t=lt.join(r,$s);if(!dt.existsSync(t))return l.info(`[SyncGuard] Baseline file not found: ${t}`),{required:!0,reason:"sync baseline file not found: "+t};let n=dt.statSync(t).mtimeMs;l.info(`[SyncGuard] Sync baseline: ${new Date(n).toISOString()} (${t})`);let i=qu(r);if(i===null)return l.warn("[SyncGuard] Failed to parse build-profile.json5, falling back to sync"),{required:!0,reason:"failed to parse build-profile.json5"};let o=lt.join(r,P.OH_PACKAGE_JSON5),s=ii(o,n,"root");if(s.required)return l.info(`[SyncGuard] Root check: ${s.reason}`),s;let a=lt.join(r,"build-profile.json5"),c=ii(a,n,"build-profile");if(c.required)return l.info(`[SyncGuard] Build profile check: ${c.reason}`),c;for(let u of i){let v=lt.join(r,u.srcPath,P.OH_PACKAGE_JSON5),D=ii(v,n,u.name);if(D.required)return l.info(`[SyncGuard] Module '${u.name}' check: ${D.reason}`),D}let d=`all oh-package.json5 files are up-to-date (sync baseline: ${new Date(n).toISOString()})`;return l.info(`[SyncGuard] ${d}`),{required:!1,reason:d}}function ii(r,e,t){if(!dt.existsSync(r))return{required:!1,reason:`${t}: source not found, skip`};let n=dt.statSync(r).mtimeMs;return n-e>zu?{required:!0,reason:`${t}: source mtime (${new Date(n).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function qu(r){let e=lt.join(r,"build-profile.json5");try{let t=W(e);if(typeof t!="object"||t===null)return null;let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):null}catch{return null}}var na=(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))(na||{}),si=3,ta=600*1e3,Xn=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;constructor(e={}){this.config=e,Gr(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),f.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",f.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,f.info(`Constructor: using configured path as startPath: '${t}'`));let i=fe(t);f.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new Yu({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=_r(),this.registerTools()}registerTools(){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:oi.object({files:oi.array(oi.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=C.isPathContainedWithSymlink(o,t);s.contained||(f.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
1258
+ `)}],isError:!0}:null}let n=e.filter(i=>ut.isAbsolute(i));return n.length>0?(f.warn(`Absolute paths rejected (no project root): ${n.join(", ")}`),{content:[{type:"text",text:n.map(i=>`Absolute path is not allowed: ${i}`).join(`
1259
+ `)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(v=>typeof v=="string"):[];if(t.length===0)return f.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let n=this.validateContainment(t);if(n)return n;let{etsFiles:i,cppFiles:o,unsupported:s}=Ju(t);s.length>0&&f.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(v=>`Unsupported file type: ${v} (only .ets and C/C++ source/header files are supported)`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let d=a.length>0;return{content:[{type:"text",text:[c.join(`
1260
1260
  `),a.join(`
1261
- `)].filter(b=>b.trim().length>0).join(`
1262
- `).trim()||"\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"}],isError:d}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${Us[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"\u9879\u76EE\u6B63\u5728\u540C\u6B65\u4E2D\uFF0C\u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0};case 3:return f.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e})}}async handleIdleCheck(){return this.ensureProjectReady(),this.config.projectPath?(f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init`),{content:[{type:"text",text:"\u68C0\u6D4B\u5230\u9E3F\u8499\u5DE5\u7A0B\uFF0C\u6B63\u5728\u540C\u6B65\u4E2D\uFF0C\u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0}):this.workspaceRoot||this.originalProjectPath?(f.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"\u6B63\u5728\u521D\u59CB\u5316, \u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0}):(f.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"\u672A\u68C0\u6D4B\u5230\u9E3F\u8499\u5DE5\u7A0B\uFF0C\u8BF7\u786E\u8BA4\u9879\u76EE\u76EE\u5F55\u662F\u5426\u6B63\u786E\uFF0C\u6216\u5728\u9879\u76EE\u4E2D\u521B\u5EFA\u5DE5\u7A0B\u540E\u91CD\u8BD5"}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Qr?(f.error(`Init retry limit reached (${this.initRetryCount}/${Qr}), will not auto-retry`),{content:[{type:"text",text:"\u9879\u76EE\u521D\u59CB\u5316\u591A\u6B21\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u9879\u76EE\u914D\u7F6E\u540E\u91CD\u542F MCP Server"}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${Qr})`),this.ensureProjectReady(),{content:[{type:"text",text:"\u9879\u76EE\u521D\u59CB\u5316\u5931\u8D25\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF0C\u8BF75\u79D2\u540E\u91CD\u8BD5"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP \u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570\u6216\u8005\u5728DevEco Studio\u4E2D\u6253\u5F00\u9879\u76EE";return f.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,n){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1263
- `);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Nu;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=ws();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let n=he(t);n?(f.info(`Detected project path from client root: ${n}`),this.config.projectPath=n,this.sdkPath=this.computeSdkPath()):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}catch(t){f.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,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{f.error("shutdown failed:",n),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new lt(e,this.config.devecoPath??null),f.info("CppCheckTool created (lazy initialization)")}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=>{f.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?he(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=he(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject())return;if(this.sdkPath||(this.sdkPath=this.computeSdkPath()),this.projectState=2,f.info("Starting project sync..."),!await at.handleSyncProject(this.config.projectPath,this.sdkPath)){f.error("Project sync failed"),this.initRetryCount++,this.projectState=5;return}this.projectState=3,this.arktsCheckTool=new ct(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize);try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,f.info("Project fully initialized, check tool is available")}catch(t){f.error("LSP initialization failed:",t),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}computeSdkPath(){let e=rn(this.config.devecoPath??""),t=ae(e);return dt.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),vs(),ys()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Lu(r){let e=[],t=[],n=[];for(let i of r)dt.extname(i).toLowerCase()===".ets"?e.push(i):on(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function ei(r={}){return new Vn(r)}async function ju(){let r=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE||"8192",n=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await O.new(),o=r,s=e??i.devecoStudioPath,a=ei({projectPath:o,devecoPath:s,nodeMaxOldSpaceSize:t,debug:n}),c=async()=>{await a.shutdown(),process.exit(0)};process.once("SIGINT",c),process.once("SIGTERM",c),process.platform==="win32"&&process.once("SIGBREAK",c);try{await a.start()}catch(d){console.error("Failed to start MCP server:",d),process.exit(1)}}var Bs=new Hu("serve").description("Host bundled auxiliary protocol servers");Bs.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await ju()});var zs=Bs;import{Command as qu,InvalidArgumentError as ri}from"commander";import{red as Lt,dim as Yu}from"colorette";import*as G from"path";import*as te from"fs";import{homedir as Fu}from"os";import{execa as $u}from"execa";import{rgPath as _u}from"@vscode/ripgrep";import Wu from"adm-zip";import{fileURLToPath as Uu}from"url";import Bu from"ora";var Ot=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Nt={"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 zu="deveco-cli",Vu="docs",ti=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=G.join(Fu(),".local","share",zu,Vu),this.versionFile=G.join(this.docsDir,".version")}getDocsDir(){return this.docsDir}async ensureInitialized(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.extractDocsIfNeeded(),await this.initPromise,this.initialized=!0}}async extractDocsIfNeeded(){let e=this.getCurrentVersion();await this.getExistingVersion()!==e&&await this.extractDocs(e)}getCurrentVersion(){return"0.8.0"}async getExistingVersion(){try{return(await te.promises.readFile(this.versionFile,"utf-8")).trim()}catch{return null}}async extractDocs(e){let t=this.findDocsZip();if(!t)throw new Error("docs.zip not found");let n=Bu({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=G.dirname(this.docsDir);await te.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await te.promises.mkdir(this.docsDir,{recursive:!0}),new Wu(t).extractAllTo(this.docsDir,!0),await te.promises.writeFile(this.versionFile,e,"utf-8"),n.succeed("Documentation extracted successfully.")}catch(i){throw n.fail("Failed to extract documentation."),i}}findDocsZip(){let e=import.meta.url,t=Uu(e),n=G.dirname(t),i=[G.join(n,"..","docs.zip")];for(let o of i)if(te.existsSync(o))return o;return null}async cleanOldDocs(){try{await te.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?G.join(this.docsDir,Nt[t]):this.docsDir,i=await this.searchFiles(e,n),o=await this.enrichWithTitleRelevance(i,e),s=this.selectByTiers(o,e.length);return(await Promise.all(s.map(async c=>{let d=this.parseFilePath(c.filePath);if(!d||!c.metadata)return null;let u=await this.readContentPreview(c.filePath);return{title:c.metadata.title,documentId:d,content:u}}))).filter(c=>c!==null)}selectByTiers(e,t){let n=(a,c)=>c.totalMatches-a.totalMatches,i=e.filter(a=>a.titleKeywordCount===t).sort(n),o=e.filter(a=>a.keywordCount===t&&a.titleKeywordCount<t).sort(n),s=e.filter(a=>a.keywordCount<t&&a.titleKeywordCount<t).sort(n);return[...i,...o,...s]}async enrichWithTitleRelevance(e,t){return Promise.all(Array.from(e.entries()).map(async([n,i])=>{let o=await this.readMetadata(n),s=o?t.filter(a=>o.title.toLowerCase().includes(a.toLowerCase())).length:0;return{filePath:n,keywordCount:i.keywordCount,totalMatches:i.totalMatches,titleKeywordCount:s,metadata:o}}))}async searchSingleKeyword(e,t){let i=await $u(_u,["--type","md","--json","--no-messages","-i","-e",e,t],{reject:!1});if(i.exitCode===1)return new Map;if(i.exitCode!==0)throw new Error(i.stderr?.trim()||`Search failed with exit code ${i.exitCode}`);return this.parseSearchResults(i.stdout)}async searchFiles(e,t){let n=await Promise.all(e.map(o=>this.searchSingleKeyword(o,t))),i=new Map;for(let o of n)for(let[s,a]of o){let c=i.get(s);c?(c.keywordCount+=1,c.totalMatches+=a):i.set(s,{keywordCount:1,totalMatches:a})}return i}parseSearchResults(e){let t=e.split(`
1264
- `),n=new Map;for(let i of t){if(!i)continue;let o=this.parseSearchResultLine(i);o&&n.set(o.filePath,o.count)}return n}parseSearchResultLine(e){try{let t=JSON.parse(e);if(t.type==="end"&&t.data?.path?.text){let n=t.data.stats?.matches??0;if(n>0)return{filePath:t.data.path.text,count:n}}}catch{}return null}async readDocument(e){await this.ensureInitialized();let n=[e,`${e}.md`].filter(i=>E.isPathContainedWithSymlink(i,this.docsDir).contained).map(i=>G.join(this.docsDir,i));for(let i of n)try{return await te.promises.readFile(i,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=G.relative(this.docsDir,e);if(!t||t.startsWith("..")||G.isAbsolute(t))return null;let n=t.split(/[/\\]/);if(n.length<2)return null;let i=n[n.length-1];return n[n.length-1]=i.replace(/\.md$/,""),n.join("/")}async readMetadata(e){let t=e.replace(/\.md$/,".json");try{let n=await te.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await te.promises.readFile(e,"utf-8"),n=t.replace(/\n/g," ").trim().slice(0,200);return n.length<t.replace(/\n/g," ").trim().length?n+"...":n}catch{return""}}},ni=new ti;function Vs(...r){return e=>{if(!r.includes(e))throw new ri(`Allowed values: ${r.join(", ")}`);return e}}function Gu(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new ri("Must be a positive integer");return e}var Ju=Vs("json","default"),Ku=Vs("json","default"),qn=new qu("docs").description("Search and read HarmonyOS documentation from local docs directory");qn.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Zu,"all").option("--format <fmt>","Output format (default, json)",Ju,"default").option("--limit <n>","Max number of results",Gu,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error(Lt("Keywords cannot be empty")),process.exit(1)),t.length>10&&(console.error(Lt("Keywords cannot exceed 10")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await ni.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Xu(o)}catch(t){console.error(Lt(t.message)),process.exit(1)}});qn.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error(Lt("Document ID cannot be empty")),process.exit(1));let t=await ni.readDocument(e);console.log(t)}catch(e){console.error(Lt(e.message)),process.exit(1)}});qn.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Ku,"default").action(r=>{if(r.format==="json"){let e=Ot.map(t=>({name:t,title:Nt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Ot)console.log(` ${e.padEnd(20)} ${Yu(Nt[e])}`)});function Zu(r){if(r==="all")return"all";if(!Ot.includes(r))throw new ri(`Invalid catalog "${r}". Allowed: all, ${Ot.join(", ")}`);return r}function Xu(r){for(let e=0;e<r.length;e++){let t=r[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.content&&console.log(` Content: ${t.content}`),e<r.length-1&&console.log()}}var qs=qn;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Qu();U.name("devecocli").description("HarmonyOS application development command line tool").version("0.8.0");U.addCommand(fi);U.addCommand(Pi);U.addCommand(Ci);U.addCommand(Fi);U.addCommand(oo);U.addCommand(No);U.addCommand(Fo);U.addCommand(Go);U.addCommand(ns);U.addCommand(zs);U.addCommand(qs);var ii=process.argv.slice(2);ii.length>=2&&ii[ii.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var tp=new Set(["update"]);U.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==U;)t=t.parent;tp.has(t.name())||await O.checkVersion()});U.parseAsync(process.argv).catch(r=>{let e=r instanceof Error?r.message:String(r??"Unknown error");console.error(ep(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});
1261
+ `)].filter(v=>v.trim().length>0).join(`
1262
+ `).trim()||"No diagnostics collected"}],isError:d}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${na[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.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})}}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"),f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(f.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}):(f.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>=si?(f.error(`Init retry limit reached (${this.initRetryCount}/${si}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${si})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return f.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,n){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1263
+ `);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Gu;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Is();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let n=fe(t);n?(f.info(`Detected project path from client root: ${n}`),this.config.projectPath=n,this.sdkPath=this.computeSdkPath()):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}catch(t){f.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,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{f.error("shutdown failed:",n),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new ct(e,this.config.devecoPath??null),f.info("CppCheckTool created (lazy initialization)")}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=>{f.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?fe(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=fe(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new at(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.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,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ea(e,this.config.forceSync??!1);return t.required?(f.info(`Sync required: ${t.reason}`),this.runSync(e)):(f.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,f.info("Starting project sync...");let t=await st.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let n=Date.now()-this.syncSkipStartedAt,i=Math.round(n/1e3);return n>=ta?(f.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${ta/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=dn(this.config.devecoPath??""),t=ae(e);return ut.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),Ds(),Cs()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Ju(r){let e=[],t=[],n=[];for(let i of r)ut.extname(i).toLowerCase()===".ets"?e.push(i):un(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function ai(r={}){return new Xn(r)}async function Xu(){let r=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=process.env.DEVECO_MCP_FORCE_SYNC==="1",o=await O.new(),s=r,a=e??o.devecoStudioPath,c=ai({projectPath:s,devecoPath:a,nodeMaxOldSpaceSize:t,debug:n,forceSync:i}),d=async()=>{await c.shutdown(),process.exit(0)};process.once("SIGINT",d),process.once("SIGTERM",d),process.platform==="win32"&&process.once("SIGBREAK",d);try{await c.start()}catch(u){console.error("Failed to start MCP server:",u),process.exit(1)}}var ra=new Ku("serve").description("Host bundled auxiliary protocol servers");ra.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Xu()});var ia=ra;import{Command as sp,InvalidArgumentError as di}from"commander";import{red as $t,dim as ap}from"colorette";import*as J from"path";import*as ne from"fs";import{homedir as Zu}from"os";import{execa as Qu}from"execa";import{rgPath as ep}from"@vscode/ripgrep";import tp from"adm-zip";import{fileURLToPath as np}from"url";import rp from"ora";var jt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Ft={"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 ip="deveco-cli",op="docs",ci=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=J.join(Zu(),".local","share",ip,op),this.versionFile=J.join(this.docsDir,".version")}getDocsDir(){return this.docsDir}async ensureInitialized(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.extractDocsIfNeeded(),await this.initPromise,this.initialized=!0}}async extractDocsIfNeeded(){let e=this.getCurrentVersion();await this.getExistingVersion()!==e&&await this.extractDocs(e)}getCurrentVersion(){return"1.2.0"}async getExistingVersion(){try{return(await ne.promises.readFile(this.versionFile,"utf-8")).trim()}catch{return null}}async extractDocs(e){let t=this.findDocsZip();if(!t)throw new Error("docs.zip not found.");let n=rp({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=J.dirname(this.docsDir);await ne.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await ne.promises.mkdir(this.docsDir,{recursive:!0}),new tp(t).extractAllTo(this.docsDir,!0),await ne.promises.writeFile(this.versionFile,e,"utf-8"),n.succeed("Documentation extracted successfully.")}catch(i){throw n.fail("Failed to extract documentation."),i}}findDocsZip(){let e=import.meta.url,t=np(e),n=J.dirname(t),i=[J.join(n,"..","docs.zip")];for(let o of i)if(ne.existsSync(o))return o;return null}async cleanOldDocs(){try{await ne.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?J.join(this.docsDir,Ft[t]):this.docsDir,i=await this.searchFiles(e,n),o=await this.enrichWithTitleRelevance(i,e),s=this.selectByTiers(o,e.length);return(await Promise.all(s.map(async c=>{let d=this.parseFilePath(c.filePath);if(!d||!c.metadata)return null;let u=await this.readContentPreview(c.filePath);return{title:c.metadata.title,documentId:d,content:u}}))).filter(c=>c!==null)}selectByTiers(e,t){let n=(a,c)=>c.totalMatches-a.totalMatches,i=e.filter(a=>a.titleKeywordCount===t).sort(n),o=e.filter(a=>a.keywordCount===t&&a.titleKeywordCount<t).sort(n),s=e.filter(a=>a.keywordCount<t&&a.titleKeywordCount<t).sort(n);return[...i,...o,...s]}async enrichWithTitleRelevance(e,t){return Promise.all(Array.from(e.entries()).map(async([n,i])=>{let o=await this.readMetadata(n),s=o?t.filter(a=>o.title.toLowerCase().includes(a.toLowerCase())).length:0;return{filePath:n,keywordCount:i.keywordCount,totalMatches:i.totalMatches,titleKeywordCount:s,metadata:o}}))}async searchSingleKeyword(e,t){let i=await Qu(ep,["--type","md","--json","--no-messages","-i","-e",e,t],{reject:!1});if(i.exitCode===1)return new Map;if(i.exitCode!==0)throw new Error(i.stderr?.trim()||`Search failed with exit code ${i.exitCode}`);return this.parseSearchResults(i.stdout)}async searchFiles(e,t){let n=await Promise.all(e.map(o=>this.searchSingleKeyword(o,t))),i=new Map;for(let o of n)for(let[s,a]of o){let c=i.get(s);c?(c.keywordCount+=1,c.totalMatches+=a):i.set(s,{keywordCount:1,totalMatches:a})}return i}parseSearchResults(e){let t=e.split(`
1264
+ `),n=new Map;for(let i of t){if(!i)continue;let o=this.parseSearchResultLine(i);o&&n.set(o.filePath,o.count)}return n}parseSearchResultLine(e){try{let t=JSON.parse(e);if(t.type==="end"&&t.data?.path?.text){let n=t.data.stats?.matches??0;if(n>0)return{filePath:t.data.path.text,count:n}}}catch{}return null}async readDocument(e){await this.ensureInitialized();let n=[e,`${e}.md`].filter(i=>C.isPathContainedWithSymlink(i,this.docsDir).contained).map(i=>J.join(this.docsDir,i));for(let i of n)try{return await ne.promises.readFile(i,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=J.relative(this.docsDir,e);if(!t||t.startsWith("..")||J.isAbsolute(t))return null;let n=t.split(/[/\\]/);if(n.length<2)return null;let i=n[n.length-1];return n[n.length-1]=i.replace(/\.md$/,""),n.join("/")}async readMetadata(e){let t=e.replace(/\.md$/,".json");try{let n=await ne.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await ne.promises.readFile(e,"utf-8"),n=t.replace(/\n/g," ").trim().slice(0,200);return n.length<t.replace(/\n/g," ").trim().length?n+"...":n}catch{return""}}},li=new ci;function oa(...r){return e=>{if(!r.includes(e))throw new di(`Allowed values: ${r.join(", ")}`);return e}}function cp(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new di("Must be a positive integer.");return e}var lp=oa("json","default"),dp=oa("json","default"),Zn=new sp("docs").description("Search and read HarmonyOS documentation from local docs directory");Zn.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all : all catalogs)",up,"all").option("--format <fmt>","Output format (default, json)",lp,"default").option("--limit <n>","Max number of results",cp,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error($t("Keywords cannot be empty.")),process.exit(1)),t.length>10&&(console.error($t("Keywords cannot exceed 10.")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await li.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):pp(o)}catch(t){console.error($t(t.message)),process.exit(1)}});Zn.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error($t("Document ID cannot be empty.")),process.exit(1));let t=await li.readDocument(e);console.log(t)}catch(e){console.error($t(e.message)),process.exit(1)}});Zn.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (options: default,json)",dp,"default").action(r=>{if(r.format==="json"){let e=jt.map(t=>({name:t,title:Ft[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of jt)console.log(` ${e.padEnd(20)} ${ap(Ft[e])}`)});function up(r){if(r==="all")return"all";if(!jt.includes(r))throw new di(`Invalid catalog "${r}". Allowed: all, ${jt.join(", ")}`);return r}function pp(r){for(let e=0;e<r.length;e++){let t=r[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.content&&console.log(` Content: ${t.content}`),e<r.length-1&&console.log()}}var sa=Zn;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";hp();B.name("devecocli").description("HarmonyOS application development command line tool").version("1.2.0");B.addCommand(Si);B.addCommand(Ti);B.addCommand(Oi);B.addCommand(zi);B.addCommand(ho);B.addCommand(Wo);B.addCommand(zo);B.addCommand(ts);B.addCommand(ls);B.addCommand(ia);B.addCommand(sa);var ui=process.argv.slice(2);ui.length>=2&&ui[ui.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var mp=new Set(["update"]);B.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==B;)t=t.parent;mp.has(t.name())||await O.checkVersion()});B.parseAsync(process.argv).catch(r=>{let e=r instanceof Error?r.message:String(r??"Unknown error");console.error(fp(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});