@deveco-test/deveco-cli 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +47 -48
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{bootstrap as Cu}from"global-agent";import{program as W}from"commander";import{Command as Qs}from"commander";import{green as ni,red as $n}from"colorette";import $ from"fs";import*as L from"path";import Se from"json5";var Pe=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=L.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=L.join(e,"build-profile.json5");if(!$.existsSync(t))return null;try{let n=$.readFileSync(t,"utf-8"),i=Se.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=L.join(this.rootDir,t.srcPath),i=L.join(n,"src","main","module.json5");if(!$.existsSync(i))return"entry";try{let o=$.readFileSync(i,"utf-8");return Se.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=L.join(this.rootDir,t.srcPath),i=L.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 Se.parse(o)}getBundleName(){let e=L.join(this.rootDir,"AppScope","app.json5");if($.existsSync(e))try{let t=$.readFileSync(e,"utf-8"),n=Se.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=L.join(this.rootDir,n.srcPath),o=L.join(i,"src","main","module.json5");if(!$.existsSync(o))return"EntryAbility";try{let s=$.readFileSync(o,"utf-8"),c=Se.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"}}getModuleDependencies(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)return[];let n=L.join(this.rootDir,t.srcPath,"oh-package.json5");if(!$.existsSync(n))return[];let i=[];try{let o=$.readFileSync(n,"utf-8"),a=Se.parse(o)?.dependencies||{};for(let c of Object.values(a)){if(typeof c!="string")continue;let d=c;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let b=L.resolve(this.rootDir,t.srcPath,d),D=this.profile.modules.find(K=>L.resolve(this.rootDir,K.srcPath)===b);D&&i.push(D.name)}}catch{}return i}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"){let o=this.profile.modules.find(K=>K.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 D=this.buildOutputPath(o.srcPath,i,["outputs",t,u]);if(!$.existsSync(D))throw new Error(`Generated package file does not exist: ${D}`);return D}buildOutputPath(e,t,n){return L.join(this.rootDir,e,"build",t,...n)}parseOutputMetadata(e,t){let n=$.readFileSync(e,"utf-8"),i=Se.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{packageName:o,isSigned:s}}};import{execFileSync as Fn}from"child_process";import M,{existsSync as Kr}from"fs";import*as P from"path";import*as V from"os";import Us from"regedit";import{join as Xr}from"path";import{red as Bs}from"colorette";function w(r){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${r}`)}var Zr="https://developer.huawei.com/consumer/cn/download/",Qr="6.1.0",jn=r=>new Promise((e,t)=>{Us.list(r,(n,i)=>{n?t(n):e(i)})}),x=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=V.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=V.homedir(),t=[P.join(e,"Applications"),"/Applications"],n=[],i=new Set;for(let o of t){if(!M.existsSync(o))continue;let s;try{s=M.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 V.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(!M.existsSync(e)){w(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let n=Fn("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 parseMacInfoPlistVersion(e){let t=r.macInfoPlistPath(e);return r.readMacInfoPlistKey(t,"CFBundleShortVersionString")??r.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(V.platform()==="darwin"){let n=r.parseMacInfoPlistVersion(e);if(n!==void 0)return n}let t=r.productInfoPath(e);if(!M.existsSync(t)){w(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(M.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(`
|
|
2
|
+
import{bootstrap as Hu}from"global-agent";import{program as W}from"commander";import{Command as na}from"commander";import{green as ri,red as Wn,yellow as ii}from"colorette";import $ from"fs";import*as L from"path";import Pe from"json5";var Ee=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=L.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=L.join(e,"build-profile.json5");if(!$.existsSync(t))return null;try{let n=$.readFileSync(t,"utf-8"),i=Pe.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=L.join(this.rootDir,t.srcPath),i=L.join(n,"src","main","module.json5");if(!$.existsSync(i))return"entry";try{let o=$.readFileSync(i,"utf-8");return Pe.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=L.join(this.rootDir,t.srcPath),i=L.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 Pe.parse(o)}getBundleName(){let e=L.join(this.rootDir,"AppScope","app.json5");if($.existsSync(e))try{let t=$.readFileSync(e,"utf-8"),n=Pe.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=L.join(this.rootDir,n.srcPath),o=L.join(i,"src","main","module.json5");if(!$.existsSync(o))return"EntryAbility";try{let s=$.readFileSync(o,"utf-8"),c=Pe.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"}}getModuleDependencies(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)return[];let n=L.join(this.rootDir,t.srcPath,"oh-package.json5");if(!$.existsSync(n))return[];let i=[];try{let o=$.readFileSync(n,"utf-8"),a=Pe.parse(o)?.dependencies||{};for(let c of Object.values(a)){if(typeof c!="string")continue;let d=c;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let b=L.resolve(this.rootDir,t.srcPath,d),A=this.profile.modules.find(Se=>L.resolve(this.rootDir,Se.srcPath)===b);A&&i.push(A.name)}}catch{}return i}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"){let o=this.profile.modules.find(Se=>Se.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 A=this.buildOutputPath(o.srcPath,i,["outputs",t,u]);if(!$.existsSync(A))throw new Error(`Generated package file does not exist: ${A}`);return A}buildOutputPath(e,t,n){return L.join(this.rootDir,e,"build",t,...n)}parseOutputMetadata(e,t){let n=$.readFileSync(e,"utf-8"),i=Pe.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{packageName:o,isSigned:s}}};import{execFileSync as $n}from"child_process";import M,{existsSync as Xr}from"fs";import*as P from"path";import*as V from"os";import Vs from"regedit";import{join as Zr}from"path";import{red as qs}from"colorette";function w(r){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${r}`)}var Qr="https://developer.huawei.com/consumer/cn/download/",ei="6.1.0",_n=r=>new Promise((e,t)=>{Vs.list(r,(n,i)=>{n?t(n):e(i)})}),x=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=V.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 _n([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 _n([t]))[t]?.keys??[];if(i.length===0)return;let o=i.map(a=>`${t}\\${a}`),s=await _n(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=V.homedir(),t=[P.join(e,"Applications"),"/Applications"],n=[],i=new Set;for(let o of t){if(!M.existsSync(o))continue;let s;try{s=M.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 V.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(!M.existsSync(e)){w(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let n=$n("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 parseMacInfoPlistVersion(e){let t=r.macInfoPlistPath(e);return r.readMacInfoPlistKey(t,"CFBundleShortVersionString")??r.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(V.platform()==="darwin"){let n=r.parseMacInfoPlistVersion(e);if(n!==void 0)return n}let t=r.productInfoPath(e);if(!M.existsSync(t)){w(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(M.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(`
|
|
3
3
|
`),i=V.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}.
|
|
4
4
|
Searched locations:
|
|
5
5
|
${n}
|
|
6
6
|
Please reinstall DevEco Studio or download the latest version from:
|
|
7
|
-
`+
|
|
8
|
-
`+
|
|
7
|
+
`+Qr)}return t.reduce((n,i)=>r.compareVersion(i.version,n.version)>0?i:n)}static assertMinVersion(e,t){r.compareVersion(t,ei)>=0||(w(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(qs(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${ei}. Please upgrade to the latest version before using deveco-cli:`)+`
|
|
8
|
+
`+Qr),process.exit(1))}static isExistingDirectory(e){return!!e&&M.existsSync(e)&&M.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=V.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(M.existsSync(o))return o;throw new Error(`hdc executable not found. Searched in:
|
|
9
9
|
${i.join(`
|
|
10
|
-
`)}`)}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(!M.existsSync(n))throw new Error(`Emulator executable not found at: ${n}`);return n}static verifyTools(e,t,n,i){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(n))throw new Error(`hvigor js file not found at: ${n}`);if(!M.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=V.platform(),n;if(t==="win32")n=
|
|
10
|
+
`)}`)}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(!M.existsSync(n))throw new Error(`Emulator executable not found at: ${n}`);return n}static verifyTools(e,t,n,i){if(!M.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!M.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!M.existsSync(n))throw new Error(`hvigor js file not found at: ${n}`);if(!M.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=V.platform(),n;if(t==="win32")n=Zr(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=Zr(e,"Contents","tools","emulator","Emulator");else return;return Xr(n)?n:void 0}static isValidApiLevel(e,t){let n=t??23;return Number.isInteger(e)&&e>=17&&e<=n}static parseApiLevelFromFile(e){if(M.existsSync(e))try{let t=M.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(V.platform()!=="win32")return r._powerShellPath="",r._powerShellPath;let e=P.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return Xr(e)?(w(`[ToolProvider] Found PowerShell at: ${e}`),r._powerShellPath=e,e):(r._powerShellPath="",r._powerShellPath)}static verifySignature(e){if(!M.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=V.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 M.accessSync(e,M.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=M.mkdtempSync(P.join(V.tmpdir(),"deveco-verify-")),t=P.join(e,"Verify-Signature.ps1");return M.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=$n(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{M.rmSync(n,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return $n("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as Ys}from"execa";import*as Mt from"path";var De=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Mt.dirname(e.javaPath)}${Mt.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 Ys(t,n,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as Gs}from"execa";var Ne=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 Gs(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as Js}from"fs/promises";import{dirname as Ks,resolve as Xs}from"path";import{execa as Zs}from"execa";import ti from"proper-lockfile";function ni(r){return Xs(r,".hvigor",".build-lock")}function Qs(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function ea(r){let e=Ks(ni(r));if(await Js(e,{recursive:!0}),process.platform==="win32")try{await Zs("attrib",["+h",e])}catch{}}async function ta(r,e){let t=new AbortController,n=Qs(e);await ea(r);let i={lockfilePath:ni(r),realpath:!1,stale:6e4,update:15e3,onCompromised:()=>t.abort()};try{return{release:await ti(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 ti(r,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function rt(r,e,t){let{release:n,signal:i}=await ta(r,t);try{return await e(i)}finally{await n()}}function ra(r,e){if(e.product&&!r.profile.app.products.some(n=>n.name===e.product))throw new Error(`Product '${e.product}' not found in project build-profile.json5.`);if(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 ia(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 Un(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 it(r,e){let t=e,n=`${r} failed`;console.error(Wn(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 Bn(r,e,t,n,i){console.log(`
|
|
11
11
|
[1/3] Running ohpm install...`);try{await r.installAll()}catch(o){it("ohpm install",o)}console.log(`
|
|
12
12
|
[2/3] Running hvigor sync...`);try{await e.sync(t,n)}catch(o){it("hvigor sync",o)}console.log(`
|
|
13
|
-
[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){it("hvigor build",o)}}var
|
|
14
|
-
`+
|
|
13
|
+
[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){it("hvigor build",o)}}var oi=new na("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=Ee.discover(e);console.warn(ii("Please ensure the project source is trustworthy before proceeding."));let n=await x.new();ra(t,r);let i=r.product||"default",o=r.buildMode||"debug",s;if(r.product&&!r.modules)s={type:"product"};else{let d=ia(t,r),u=Un(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:u}}let a=new Ne(n,t.rootDir),c=new De(n,t.rootDir);await rt(t.rootDir,async()=>Bn(a,c,i,o,s),()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
14
|
+
`+ri("Build completed successfully!"))}catch(e){console.error(Wn(e.message)),process.exit(1)}});oi.command("clean").description("Clean the HarmonyOS project build outputs").action(async()=>{try{let r=process.cwd(),e=Ee.discover(r);console.warn(ii("Please ensure the project source is trustworthy before proceeding."));let t=await x.new(),n=new De(t,e.rootDir);await rt(e.rootDir,async()=>{console.log(`
|
|
15
15
|
[1/2] Running hvigor clean...`);try{await n.clean()}catch(i){it("hvigor clean",i)}console.log(`
|
|
16
16
|
[2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(i){it("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
17
|
-
`+
|
|
17
|
+
`+ri("Clean completed successfully!"))}catch(r){console.error(Wn(r.message)),process.exit(1)}});var si=oi;import{Command as wa}from"commander";import{green as hi,red as ba,yellow as Sa}from"colorette";import{randomUUID as ya}from"crypto";import{execa as va}from"execa";import{execa as ga}from"execa";import{execFile as oa,spawn as sa}from"child_process";import{promisify as aa}from"util";var ca=aa(oa);function ai(r,e,t){let i=r.replace(/\r\n/g,`
|
|
18
18
|
`).split(`
|
|
19
|
-
`),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
|
|
20
|
-
`)){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 He(this.hdcPath,e,[...
|
|
19
|
+
`),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 ci(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function la(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??0}}function da(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function ua(r,e,t,n,i){r.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=ai(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=ai(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,ci(e.stdoutLineBuffer,"stdout",t),ci(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=la(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),n(s)})}async function li(r,e=[],t={}){try{let{stdout:n,stderr:i}=await ca(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();ua(o,s,t,n,i)})}function ui(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var pa=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i],ha=[/\[fail\]/i,/\bfail!/i,/not found/i];function Le(r){return r?pa.some(e=>e.test(r))?"transient":ha.some(e=>e.test(r))?"fatal":"ok":"ok"}var zn=[800,1500,2500];function ma(r){return new Promise(e=>setTimeout(e,r))}async function he(r,e){let t=1+zn.length,n={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){n=await li(r,e);let o=n.exitCode===0?n.stdout:n.stderr||n.stdout;if(Le(o)!=="transient"||i>=t-1)return n;w(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${zn[i]}ms`),await ma(zn[i])}return n}async function qn(r,e,t){let n=await he(r,["-t",e,"shell","param","get",t]);if(n.exitCode!==0)return;let i=n.stdout.trim();if(!(!i||Le(i)!=="ok"))return ui(i)}var Vn="__DEVECO_PARAM_DELIM__";function fa(r,e){let t=new Map,n=r.split(Vn);for(let i=0;i<e.length;i++){let o=(n[i]??"").trim();if(!o||Le(o)!=="ok")continue;let s=ui(o);s&&t.set(e[i],s)}return t}async function He(r,e,t){if(t.length===0)return new Map;if(t.length===1){let o=new Map,s=await qn(r,e,t[0]);return s&&o.set(t[0],s),o}let n=t.map(o=>`param get ${o}`).join(`; echo ${Vn}; `)+`; echo ${Vn}`,i=await he(r,["-t",e,"shell",n]);return i.exitCode!==0?new Map:fa(i.stdout,t)}function ot(r){return r.startsWith("127.0.0.1:")}var pi=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype"],U=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 ga(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
|
|
20
|
+
`)){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 He(this.hdcPath,e,[...pi]);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().includes(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
21
|
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
22
|
-
`)):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 He(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=ot(e),n,i;try{let o=await He(this.hdcPath,e,[...
|
|
23
|
-
`))}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
|
|
22
|
+
`)):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 He(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=ot(e),n,i;try{let o=await He(this.hdcPath,e,[...pi]);n=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:i}}};var xt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=U.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;w(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await va(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/${ya()}`;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 Pa(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 Ea(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(`
|
|
23
|
+
`))}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 Da(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
24
|
Available runnable modules:
|
|
25
25
|
`+t.map(n=>` - ${n.name}`).join(`
|
|
26
|
-
`))}function
|
|
27
|
-
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(
|
|
28
|
-
Application '${t}': ${s}`))}var
|
|
29
|
-
`+
|
|
30
|
-
${r} is already up to date (version ${e})`));return}console.log(
|
|
31
|
-
New version found: ${n} (current: ${e})`)),console.log(
|
|
32
|
-
`+
|
|
33
|
-
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:
|
|
34
|
-
`:"";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=
|
|
26
|
+
`))}function Ia(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 Ca(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(`
|
|
27
|
+
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(hi(`
|
|
28
|
+
Application '${t}': ${s}`))}var Aa=new wa("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 Ta(r)}catch(e){console.error(ba(e.message)),process.exit(1)}});async function ka(r,e,t,n,i,o){let s=new Ne(e,r.rootDir),a=new De(e,r.rootDir),d=r.collectNonHarDependentModuleList(t).map(A=>`${A}@${n}`),u=Un(r,d),b={type:"modules",modulesToBuild:d,moduleTasks:u};await rt(r.rootDir,()=>Bn(s,a,i,o,b),()=>console.log("Another build is already running for this project. Waiting for it to finish...")),console.log(`
|
|
29
|
+
`+hi("Build completed successfully!"))}async function Ta(r){let e=Ee.discover(process.cwd());console.warn(Sa("Please ensure the project source is trustworthy before proceeding."));let t=await x.new(),n=Da(e,r.module),{moduleName:i,targetName:o}=Pa(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 xt(t),c=U.from(t),d=await Ea(c,r.device),u=d.includes("127.0.0.1")||d.includes("localhost"),b=r.product||"default",A=r.buildMode||"debug";r.skipBuild||await ka(e,t,i,o,b,A);let Se=Ia(e,i,o,u,b),jn=e.getBundleName(),Tt=e.getMainAbility(i,r.ability);await Ca(a,d,jn,Se,Tt,!!r.uninstall)}var mi=Aa;import{Command as Ma}from"commander";import{green as fi,red as gi,cyan as Yn}from"colorette";import{execa as yi}from"execa";function xa(){return"@deveco-test/deveco-cli"}function Ra(){return"0.3.2"}var Oa=new Ma("update").description("Update deveco-cli to the latest version").action(async()=>{let r=xa(),e=Ra();console.log(Yn("Checking for updates..."));try{let{stdout:t}=await yi("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(fi(`
|
|
30
|
+
${r} is already up to date (version ${e})`));return}console.log(Yn(`
|
|
31
|
+
New version found: ${n} (current: ${e})`)),console.log(Yn(`Updating ${r}...`)),await yi("npm",["install","-g",`${r}@latest`],{stdio:"inherit"}),console.log(`
|
|
32
|
+
`+fi(`${r} updated successfully to version ${n}!`))}catch(t){let n=t;console.error(gi(`Failed to update ${r}`)),n.message&&console.error(gi(n.message)),process.exit(1)}}),vi=Oa;import{Command as tc}from"commander";import{execa as Zn}from"execa";function H(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Na}from"child_process";var La=2500;function Ha(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 Fa(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,La);r.once("error",u=>c(u.message)),Ha(r,d,s,a,c,o)}function wi(r,e,t){return w(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,i)=>{let o=[],s=Na(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)),Fa(s,o,n,i)})}import*as Fe from"path";function ja(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 $a(r){let e=r.instancePath?.trim();if(e)return Fe.dirname(Fe.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?Fe.dirname(Fe.normalize(t)).replace(/\\/g,"/"):""}function _a(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function Wa(r,e){let t=[["-start",r]],n=$a(e);if(n)for(let i of _a(e.imageRoot))t.push(["-hvd",r,"-path",n,...i]);return ja(t)}async function bi(r,e,t){let n=new Error("No start strategy ran"),i=Wa(r,e);for(let o of i)try{return await t(o),{ok:!0}}catch(s){n=s}return{ok:!1,lastError:n}}async function Gn(r){return(await U.withHdcPath(r).listDevices()).map(t=>t.serial).filter(ot)}async function Jn(r){let e=await Gn(r);return e.length===0?[]:(await Promise.all(e.map(n=>qn(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Si(r,e){return(await Jn(r)).includes(e)}import*as je from"path";import{existsSync as Ua,statSync as Ba}from"fs";function st(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=st(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 Va(r){return st(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function qa(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=je.dirname(je.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=je.join(t,n.name);Ua(i)&&Ba(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function Ya(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=Va(t),i=st(t,["deviceType","DeviceType","devicetype"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:za(t),path:st(t,["path","Path","hvdPath","hvd_path"]),imageRoot:st(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:i||void 0}}).filter(t=>t.name):null}catch{return null}}function Ga(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype)\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())}}return n&&e.push(n),e}function Pi(r){let t=Ya(r)??Ga(r);return qa(t),t}function Kn(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function Ja(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Ka(r){if(!Ja(r))return null;let e=Kn(r,["osVersion","OsVersion","OSVersion"]),t=Kn(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=Kn(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Xn(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=Ka(i);o&&n.push(o)}return n}catch{return[]}}function Ei(r){let t=Xn(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var Di=/no images are available/i;function at(r){return r.normalize("NFKC").trim().toLowerCase()}function Xa(r){let e=r.message||"";return Di.test(e)}var $e=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 Zn(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return wi(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Pi(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";let s=await bi(o,i,a=>this.executeEmulatorDetached(a));if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
33
|
+
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:Si(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 Zn(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(!Xa(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 Ei(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}
|
|
34
|
+
`:"";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=Xn(t),i=at(e.deviceType),o=at(e.osVersion);return n.filter(s=>at(s.deviceType)===i&&(at(s.osVersion)===o||at(s.softwareVersion)===o))}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[Di]})}async runEmulatorChecked(e,t){let{stdout:n,stderr:i,exitCode:o}=await Zn(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(`
|
|
35
35
|
`).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(`
|
|
36
|
-
`)}),!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))try{await this.executeEmulator(["-stop",o])}catch{}return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as
|
|
37
|
-
`)}function
|
|
36
|
+
`)}),!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))try{await this.executeEmulator(["-stop",o])}catch{}return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as Qn,yellow as Ci,gray as Ai}from"colorette";import nc from"ora";import{red as Za}from"colorette";function Rt(r,e){r?r.fail(e):console.error(Za(e)),process.exit(1)}import{green as Qa}from"colorette";function Ii(r,e){return r+" ".repeat(Math.max(0,e-r.length))}function ec(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 ct(r,e){let t=ec(r,e),n=[];n.push(r.map((i,o)=>Ii(i,t[o])).join(" ")),n.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Ii(s??"",t[a])).join(" ").trimEnd();n.push(i.highlight?Qa(o):o)}return n.join(`
|
|
37
|
+
`)}function rc(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 ic=["Name","Serial","Kind","Device Type"];function oc(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 ac(){console.log(Ci(" No active devices.")),console.log(Ai(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function cc(r){let t=[...r].sort(sc).map(oc);console.log(ct(ic,t))}async function lc(r,e){if(!r.some(i=>i.isEmulator)||!e.emulatorPath)return;let n=await $e.from(e).getDeviceTypeByName();rc(r,n)}async function dc(r,e,t){try{let n=await r.getConnectedEntries();await lc(n,e),t?.stop(),n.length===0?ac():cc(n),console.log("")}catch(n){Rt(t,`Failed to list devices: ${n.message}`)}}async function uc(r,e){let t=await r.listDevices();if(!(t.length<2)){console.error(Qn("Multiple devices connected. Please specify a device with:"));for(let n of t){let i=await r.getDeviceName(n.serial);console.error(Ai(` ${e} -t ${n.serial} # ${i}`))}process.exit(1)}}async function pc(r,e){try{e||await uc(r,"devecocli device view");let t=await r.listDevices(),n=await r.getDeviceInfo(t,e);n||(console.log(Ci("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}`),console.log(` Status: ${n.status==="device"?"connected":n.status}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`),console.log("")}catch(t){console.error(Qn(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function ki(){try{let r=await x.new();return{manager:U.from(r),toolProvider:r}}catch(r){console.error(Qn(`Failed to initialize device manager: ${r.message}`)),process.exit(1);return}}var er=new tc("device").description("Manage connected devices");er.command("list").description("List all connected devices").action(async()=>{let{manager:r,toolProvider:e}=await ki(),t=nc({text:"Querying connected devices\u2026",color:"cyan"}).start();await dc(r,e,t)});er.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async r=>{let{manager:e}=await ki();await pc(e,r.target)});var Ti=er;import{Command as or,Option as zi}from"commander";import{green as Nt,cyan as We,red as B,yellow as te,gray as Ue}from"colorette";import xc from"ora";import hc from"readline/promises";import{execa as xi}from"execa";import*as me from"fs/promises";import*as nr from"os";import*as Ie from"path";var tr=`1/4:\r
|
|
38
38
|
---------------------------------------\r
|
|
39
39
|
Statement About HarmonyOS and Privacy\r
|
|
40
40
|
\r
|
|
@@ -1204,54 +1204,53 @@ Part I: Chinese mainland.\r
|
|
|
1204
1204
|
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
|
|
1205
1205
|
\r
|
|
1206
1206
|
Part III: Other countries and regions.\r
|
|
1207
|
-
---------------------------------------\r`;var
|
|
1208
|
-
`),
|
|
1209
|
-
`)}function
|
|
1210
|
-
${t}`);return
|
|
1211
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1207
|
+
---------------------------------------\r`;var mc=new Set,Ot=new Map,rr="HarmonyOS_Software_Service_Agreement",Ri=["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(`
|
|
1208
|
+
`),Oi=Ri,ir="HarmonyOS_SDK_Agreement";function Ni(r,e){return`${r}\0${e}`}function fc(){mc.clear(),Ot.clear()}var gc=Ri,K=class extends Error{constructor(e=gc){super(e),this.name="EmulatorLicenseBlockedError"}};function Li(r,e){return[r??"",e??""].join(`
|
|
1209
|
+
`)}function Hi(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 yc(r){return`Emulator${r.trim()}`}function Fi(r){let e=yc(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 Ie.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Ie.join(nr.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Ie.join(nr.homedir(),".cache");return Ie.join(t,"Huawei",e,".emu_config")}async function vc(r,e,t){let n=Ni(r,e),i=Ot.get(n);if(i!==void 0)return i;let o=await xi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Li(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new K(t);return Ot.set(n,s),s}function wc(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function bc(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 Sc(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=wc(e.slice(n+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Pc(r){let e={};for(let t of r.split(/\r?\n/)){let n=Sc(t);n&&(e[n.key]=n.entry)}return e}function Ec(r){let e=r.trim();if(!e)return{};let t=bc(e);return t||Pc(r)}function Dc(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function ji(r,e,t,n){let i=await vc(r,e,n),o=Hi(i);if(!o)throw new K(n);let s=Fi(o),a;try{a=await me.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new K(n):u}let d=Ec(a)[t];if(!d)throw new K(n);if(d.delimiter==="=")throw new K(n);if(!Dc(d.value))throw new K(n)}async function $i(r,e){await ji(r,e,rr,Oi)}async function _i(r,e){await ji(r,e,ir,Oi)}async function Ic(r,e){let t=await xi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=Li(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=Ni(r,e);return Ot.set(i,n),n}async function Cc(r,e){let t=await Ic(r,e),n=Hi(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1210
|
+
${t}`);return Fi(n)}function Mi(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Ac(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[rr]="agree",n[ir]="agree",await me.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
1211
|
+
`,"utf8"),!0}catch{}return!1}async function kc(r,e){let t=rr,n=ir,i=[{k:t,re:new RegExp(`^\\s*${Mi(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${Mi(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 me.writeFile(r,s.join(`
|
|
1212
1212
|
`)+(s.length>0?`
|
|
1213
|
-
`:""),"utf8")}async function Ic(r){await fe.mkdir(De.dirname(r),{recursive:!0});let e="";try{e=await fe.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Ec(r,e,t)||await Dc(r,e)}async function $i(r,e){return console.log(Qn),0}var Cc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function _i(r,e){if(console.log(Qn),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("devecocli emulator license accept requires an interactive terminal."),1;let n=lc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(Cc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Pc(r,e);await Ic(s),uc()}catch(s){return console.error(s.message),1}return 0}var kc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Tc(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 Mc(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 xc(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(te("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(te("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(B("--os-version does not match any downloaded image (exact string required).")),console.log(te("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 Rc=["Name","Status","Serial","Device Type"];function Oc(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-"],highlight:t}}async function Nc(r,e){let t=await Promise.all(e.map(async n=>{let i=await He(r,n,kc);return[n,i]}));return new Map(t)}async function Lc(r){let e=await qn(r),t=await Nc(r,e);return{serials:e,params:t}}function Hc(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 Fc(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&&Hc(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 jc(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=>Oc(i.emu,i.serial,i.effectiveRunning))}async function $c(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),Lc(e)]);if(n.length===0){t?.stop(),console.log(te(" No emulator instances found.")),console.log(Ue(" You can create an emulator in DevEco Studio."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=Fc(i.serials,i.params,o);t?.stop();let c=jc(n,s,a);console.log(ct(Rc,c)),console.log("")}catch(n){Rt(t,`Failed to list emulators: ${n.message}`)}}function Bi(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(B(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Ue(s.stdout)),s.stderr&&console.error(Ue(s.stderr))}return n}var _c=2e3,Wc=6e4;async function Uc(r,e){let t=H(e);return(await Yn(r)).some(i=>H(i)===t)}async function zi(r,e,t,n=Wc,i=_c){let o=Date.now()+n;for(;Date.now()<o;){if(await Uc(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function Bc(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(te(`Emulator "${t}" is already running.`));return}console.log(We(`Starting emulator "${t}"...`));let i=await zi(e,t,!0);console.log(i?Nt(`Emulator "${t}" started successfully.`):te(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function zc(r,e,t){let n=await Promise.allSettled(t.map(o=>Bc(r,e,o)));Bi(n,t,"start")&&process.exit(1)}async function Vc(r,e){let t=e.trim();if(!ot(t))return t;let n=await U.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 qc(r,e,t){let n=await Vc(e,t);if(console.log(We(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(te(`Emulator "${n}" is already stopped.`));return}let o=await zi(e,n,!1);console.log(o?Nt(`Emulator "${n}" stopped successfully!`):te(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the timeout.`))}async function Yc(r,e,t){let n=await Promise.allSettled(t.map(o=>qc(r,e,o))),i=Bi(n,t,"stop");console.log(""),i&&process.exit(1)}async function ne(){try{let r=await x.new();return{manager:$e.from(r),toolProvider:r}}catch(r){console.error(B(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var ge=new rr("emulator").description("Manage emulator instances"),Gc=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Lt(r){let e=new Ui("--device-type <type>","Emulator device type").choices([...Gc]);return r?e.makeOptionMandatory():e}function _e(r,e){for(let t of e)if(t in r)return r[t]}function lt(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function Wi(r){let e=lt(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Jc=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],Kc="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Vi(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function qi(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=lt(_e(i,["osVersion","OsVersion","OSVersion","os_version"])),s=lt(_e(i,["deviceType","DeviceType","device_type"])),a=Wi(_e(i,["downloaded","Downloaded","isDownloaded"])),c=lt(_e(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=lt(_e(i,["releaseType","ReleaseType","release_type"])),u=Wi(_e(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function Xc(r){let e=r.trim();if(!e)return!0;let t=Vi(e);return t===null?!1:t.length===0?!0:qi(t,!0).length===0}function Zc(r,e){let t=r.trim();if(!t)return"";let n=Vi(t);if(!n)return r.trimEnd();let i=qi(n,e);return ct(Jc,i)}var Ht=new rr("image").description("HarmonyOS emulator system images (download, list, remove)");Ht.command("download").description("Download a system image").addOption(Lt(!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 ne();try{await ji(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof X&&(console.error(B(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(B("error: required option '--device-type <type>' not specified")),process.exit(1)),r.osVersion?.trim()||(console.error(B("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(B(`Failed to download system image: ${n.message}`)),process.exit(1)}});Ht.command("remove").description("Remove a downloaded system image").addOption(Lt(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await ne();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(B(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Ht.command("list").description("List system images").addOption(Lt(!1)).option("--all","List all images (downloaded and not downloaded)").addOption(new Ui("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await ne();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(Xc(n)){console.log(te(Kc));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=Zc(n,r.all===!0);console.log(i)}catch(t){console.error(B(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});ge.addCommand(Ht);var ir=new rr("license").description("HarmonyOS local emulator license");ir.command("view").description("review the agreement text (read-only)").action(async()=>{let{toolProvider:r}=await ne(),e=await $i(r.emulatorPath,r.sdkPath);process.exit(e)});ir.command("accept").description("review and accept the agreements").action(async()=>{let{toolProvider:r}=await ne(),e=await _i(r.emulatorPath,r.sdkPath);process.exit(e)});ge.addCommand(ir);ge.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await ne(),t=Ac({text:"Listing emulators\u2026",color:"cyan"}).start();await $c(r,e.hdcPath,t)});ge.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await ne();try{await Fi(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof X&&(console.error(B(n.message)),process.exit(1)),n}r?.length||(console.error(B("error: missing required argument 'names'")),process.exit(1)),await zc(e,t.hdcPath,r)});ge.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 ne();r?.length||(console.error(B("error: missing required argument 'names'")),process.exit(1)),await Yc(e,t.hdcPath,r)});var Yi=ge.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(Lt(!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");Yi.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1213
|
+
`:""),"utf8")}async function Tc(r){await me.mkdir(Ie.dirname(r),{recursive:!0});let e="";try{e=await me.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Ac(r,e,t)||await kc(r,e)}async function Wi(r,e){return console.log(tr),0}var Mc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Ui(r,e){if(console.log(tr),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("devecocli emulator license accept requires an interactive terminal."),1;let n=hc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(Mc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Cc(r,e);await Tc(s),fc()}catch(s){return console.error(s.message),1}return 0}var Rc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Oc(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 Nc(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 Lc(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(te("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(te("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(B("--os-version does not match any downloaded image (exact string required).")),console.log(te("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 Hc=["Name","Status","Serial","Device Type"];function Fc(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-"],highlight:t}}async function jc(r,e){let t=await Promise.all(e.map(async n=>{let i=await He(r,n,Rc);return[n,i]}));return new Map(t)}async function $c(r){let e=await Gn(r),t=await jc(r,e);return{serials:e,params:t}}function _c(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 Wc(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&&_c(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 Uc(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=>Fc(i.emu,i.serial,i.effectiveRunning))}async function Bc(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),$c(e)]);if(n.length===0){t?.stop(),console.log(te(" No emulator instances found.")),console.log(Ue(" You can create an emulator in DevEco Studio."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=Wc(i.serials,i.params,o);t?.stop();let c=Uc(n,s,a);console.log(ct(Hc,c)),console.log("")}catch(n){Rt(t,`Failed to list emulators: ${n.message}`)}}function Vi(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(B(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Ue(s.stdout)),s.stderr&&console.error(Ue(s.stderr))}return n}var zc=2e3,Vc=6e4;async function qc(r,e){let t=H(e);return(await Jn(r)).some(i=>H(i)===t)}async function qi(r,e,t,n=Vc,i=zc){let o=Date.now()+n;for(;Date.now()<o;){if(await qc(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function Yc(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(te(`Emulator "${t}" is already running.`));return}console.log(We(`Starting emulator "${t}"...`));let i=await qi(e,t,!0);console.log(i?Nt(`Emulator "${t}" started successfully.`):te(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Gc(r,e,t){let n=await Promise.allSettled(t.map(o=>Yc(r,e,o)));Vi(n,t,"start")&&process.exit(1)}async function Jc(r,e){let t=e.trim();if(!ot(t))return t;let n=await U.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 Kc(r,e,t){let n=await Jc(e,t);if(console.log(We(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(te(`Emulator "${n}" is already stopped.`));return}let o=await qi(e,n,!1);console.log(o?Nt(`Emulator "${n}" stopped successfully!`):te(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the timeout.`))}async function Xc(r,e,t){let n=await Promise.allSettled(t.map(o=>Kc(r,e,o))),i=Vi(n,t,"stop");console.log(""),i&&process.exit(1)}async function ne(){try{let r=await x.new();return{manager:$e.from(r),toolProvider:r}}catch(r){console.error(B(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var fe=new or("emulator").description("Manage emulator instances"),Zc=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Lt(r){let e=new zi("--device-type <type>","Emulator device type").choices([...Zc]);return r?e.makeOptionMandatory():e}function _e(r,e){for(let t of e)if(t in r)return r[t]}function lt(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function Bi(r){let e=lt(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Qc=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],el="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function Yi(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function Gi(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=lt(_e(i,["osVersion","OsVersion","OSVersion","os_version"])),s=lt(_e(i,["deviceType","DeviceType","device_type"])),a=Bi(_e(i,["downloaded","Downloaded","isDownloaded"])),c=lt(_e(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=lt(_e(i,["releaseType","ReleaseType","release_type"])),u=Bi(_e(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function tl(r){let e=r.trim();if(!e)return!0;let t=Yi(e);return t===null?!1:t.length===0?!0:Gi(t,!0).length===0}function nl(r,e){let t=r.trim();if(!t)return"";let n=Yi(t);if(!n)return r.trimEnd();let i=Gi(n,e);return ct(Qc,i)}var Ht=new or("image").description("HarmonyOS emulator system images (download, list, remove)");Ht.command("download").description("Download a system image").addOption(Lt(!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 ne();try{await _i(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof K&&(console.error(B(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(B("error: required option '--device-type <type>' not specified")),process.exit(1)),r.osVersion?.trim()||(console.error(B("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(B(`Failed to download system image: ${n.message}`)),process.exit(1)}});Ht.command("remove").description("Remove a downloaded system image").addOption(Lt(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await ne();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(B(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Ht.command("list").description("List system images").addOption(Lt(!1)).option("--all","List all images (downloaded and not downloaded)").addOption(new zi("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await ne();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(tl(n)){console.log(te(el));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=nl(n,r.all===!0);console.log(i)}catch(t){console.error(B(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});fe.addCommand(Ht);var sr=new or("license").description("HarmonyOS local emulator license");sr.command("view").description("review the agreement text (read-only)").action(async()=>{let{toolProvider:r}=await ne(),e=await Wi(r.emulatorPath,r.sdkPath);process.exit(e)});sr.command("accept").description("review and accept the agreements").action(async()=>{let{toolProvider:r}=await ne(),e=await Ui(r.emulatorPath,r.sdkPath);process.exit(e)});fe.addCommand(sr);fe.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await ne(),t=xc({text:"Listing emulators\u2026",color:"cyan"}).start();await Bc(r,e.hdcPath,t)});fe.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await ne();try{await $i(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof K&&(console.error(B(n.message)),process.exit(1)),n}r?.length||(console.error(B("error: missing required argument 'names'")),process.exit(1)),await Gc(e,t.hdcPath,r)});fe.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 ne();r?.length||(console.error(B("error: missing required argument 'names'")),process.exit(1)),await Xc(e,t.hdcPath,r)});var Ji=fe.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(Lt(!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");Ji.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1214
1214
|
${te("Tip: ")}${Ue("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1215
1215
|
${We('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1216
1216
|
${We('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1217
|
-
`)}});
|
|
1218
|
-
${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)}},Ce=new sr;async function $t(){let r=await Ce.get(re.TAGS_API_URL),t=lr(r,"Tags API").data.skill.find(n=>n.name==="HMOS");if(!t)throw new Error("HMOS tag not found");return t.id}async function ar(r){let e=[],t=1,n=re.DEFAULT_PAGE_SIZE;for(;;){let i=await Ce.post(re.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:t,pageSize:n,tagIds:[r]}}),o=lr(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<n)break;t++}return e}async function cr(r,e){let t=await Ce.post(re.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:re.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return lr(t,"Skills API").data.list}function Qi(r){let e=[];for(let[,t]of Object.entries(ae)){let n=Zi.join(tl(),t.path,r);Xi.existsSync(n)&&e.push(t.displayName)}return e.sort()}function lr(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=Ce.parseJson(r);if(t.code!==re.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}import nl from"adm-zip";import to from"fs";import R from"path";import{fileURLToPath as rl}from"url";import{homedir as no}from"os";var ce=to.promises;function dr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function eo(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 ur(r){return R.isAbsolute(r)?r:R.resolve(process.cwd(),r)}async function ro(r){let e=`${re.SKILL_INSTALL_API_BASE}/${r}/install?format=zip`;return await Ce.getBinary(e)}async function il(r,e,t){dr(t);let n=new nl(r),i=n.getEntries();try{await ce.stat(e)}catch{await ce.mkdir(e,{recursive:!0})}let o=R.join(e,t);eo(e,o);for(let s of i){let a=R.join(o,s.entryName);eo(o,a)}n.extractAllTo(o,!0)}async function pr(r){let e=ae[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ae).join(", ")}`);let t=R.join(no(),e.path.replace("/skills",""));try{return await ce.access(t),!0}catch{return!1}}function hr(r){let e=ae[r];return R.join(no(),e.path)}function mr(r,e){return R.join(r,"."+e,"skills")}async function ol(r,e,t){dr(e);let n=R.join(r,e);try{if(await ce.access(n),t)await ce.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 fr(r,e,t){await il(r,e,t),console.log(`Skill ${t} installed to ${R.join(e,t)}`)}async function gr(r,e,t){let n=R.join(e,t);await ce.mkdir(n,{recursive:!0});let i=R.join(n,R.basename(r));await ce.copyFile(r,i),console.log(`Skill ${t} installed to ${n}`)}function io(r,e=""){return{success:!1,error:r instanceof Error?r.message:e}}async function ze(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await ol(i,r,n);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return io(i,"Installation failed")}}async function yr(r,e){try{dr(r);let t=await e(),n=R.join(t,r);try{await ce.access(n)}catch{return console.log(`Skill ${r} does not exist in ${t}`),{success:!0,skipped:!0}}return await ce.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}`),{success:!0}}catch(t){return io(t,"Removal failed")}}async function oo(r,e,t,n=!1){return ze(r,()=>hr(e),i=>fr(t,i,r),n)}async function so(r,e,t,n=!1){return ze(r,()=>t,i=>fr(e,i,r),n)}async function ao(r,e,t,n,i=!1){return ze(r,()=>mr(t,n),o=>fr(e,o,r),i)}async function co(r,e,t,n=!1){return ze(r,()=>hr(t),i=>gr(e,i,r),n)}async function lo(r,e,t,n,i=!1){return ze(r,()=>mr(t,n),o=>gr(e,o,r),i)}async function uo(r,e,t,n=!1){return ze(r,()=>t,i=>gr(e,i,r),n)}async function po(r,e){return yr(r,()=>hr(e))}async function ho(r,e){return yr(r,()=>e)}async function mo(r,e,t){return yr(r,()=>mr(e,t))}function fo(){let e=R.dirname(rl(import.meta.url));for(;;){let t=R.join(e,"SKILL.md");if(to.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 go from"fs";import{cyan as sl}from"colorette";async function dt(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 ut(){let r=[];for(let e of Object.keys(ae))await pr(e)&&r.push(e);return r}function pt(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(sl("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function ve(r,e,t){if(!go.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!go.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function ht(r,e,t){if(r&&(e||t))throw new Error("Cannot use --path with --project or --agent");return{resolvedPath:r?ur(r):void 0,resolvedProject:e?ur(e):void 0}}async function _t(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await dt(r.agent)).map(a=>({project:t,agent:a})):t?i=(await ut()).map(a=>({project:t,agent:a})):r.agent?n=await dt(r.agent):n=await ut(),!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 ll(r){let e=await $t();if(r.all)return(await ar(e)).map(n=>n.enName);{let n=(await cr(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function dl(r,e,t,n){let i=[];if(t.customPath){let o=await so(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await oo(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await ao(r,e,o,s,n);i.push(a)}return i}function ul(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}=ht(r.path,r.project,r.agent);return t&&ve(t,"Project directory",r.force),e&&ve(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function pl(r,e,t){let n=await _t(r,e,t);return{skillNames:await ll(r),targets:n}}async function hl(r,e,t,n){let i=[],o=r.length;for(let s=0;s<r.length;s++){let a=r[s],c=o>1?` (${s+1}/${o})`:"";n.start(`Installing ${a}${c}...`);let d;try{d=await ro(a)}catch(b){let D=b instanceof Error?b.message:"unknown error";n.fail(),console.log(mt(`${a}: Download failed - ${D}`)),i.push({success:!1});continue}let u=await dl(a,d,e,t);i.push(...u)}return i}async function ml(r){let e=new Ie;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=ul(r),{skillNames:i,targets:o}=await pl(r,t,n),s=await hl(i,o,r.force||!1,e);e.stop(),pt(s)}catch(t){throw e.stop(),t}}function fl(r){let{resolvedPath:e,resolvedProject:t}=ht(r.path,r.project,r.agent);return t&&ve(t,"Project directory"),e&&ve(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function gl(r,e){let t=new Ie;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=fl(e),o=await yl(e,r,n,i);t.stop(),pt(o)}catch(n){throw t.stop(),n}}function yo(r,e=""){if(r.length===0)throw new Error(`No agents found. Please install an AI agent (cursor, opencode, etc.) ${e}`)}async function Wt(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await po(r,n.agent):await mo(r,n.project,n.agent);t.push(i)}return t}async function yl(r,e,t,n){if(t)return[await ho(e,t)];if(n&&r.agent){let a=(await dt(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return Wt(e,a)}if(n){let s=await ut();yo(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return Wt(e,a)}if(r.agent){let a=(await dt(r.agent)).map(c=>({type:"agent",agent:c}));return Wt(e,a)}let i=await ut();yo(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Wt(e,o)}var ft=new al("skills").description("Manage HMOS skills");ft.command("list").description("List all available HMOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new Ie;try{e.start("Fetching skills...");let t=await $t(),n=await ar(t);if(n.length===0){e.stop(),console.log(wo("No skills available"));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(vo(i.enName)),console.log(bo(i.description));let o=Qi(i.enName);o.length>0&&console.log(cl(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(mt(t.message)),process.exit(1)}});ft.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new Ie;try{e.start("Searching skills...");let t=await $t(),n=await cr(r,t);if(n.length===0){console.log(wo(`No skills found matching '${r}'`)),e.stop();return}e.succeed(`Found ${n.length} skills`);for(let i of n)console.log(vo(i.enName)),console.log(bo(i.description)),console.log()}catch(t){e.stop(),console.error(mt(t.message)),process.exit(1)}});ft.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); 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 ml(r)}catch(e){console.error(mt(e.message)),process.exit(1)}});ft.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 (e.g. opencode,trae-cn,cursor,qoder,codebuddy); 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 gl(r.skill,r)}catch(e){console.error(mt(e.message)),process.exit(1)}});var So=ft;import{Command as bl,InvalidArgumentError as Do}from"commander";import{cyan as Po,red as vr,yellow as vl}from"colorette";var O=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(`
|
|
1217
|
+
`)}});Ji.action(async(r,e)=>{try{Oc(r),Nc(e.osVersion);let{manager:t}=await ne(),n=await t.listDownloadedImageOsVersions();Lc(e.osVersion,n),console.log(We(`Creating emulator "${r}"...`)),await t.createVirtualDevice({name:r,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Nt(`Emulator "${r}" created successfully.`))}catch(t){console.error(B(`${t.message}`)),process.exit(1)}});fe.command("delete <name>").description("Delete a local emulator instance").action(async r=>{let{manager:e}=await ne();console.log(We(`Deleting emulator "${r}"...`));try{let t=await e.deleteVirtualDevice(r);console.log(Nt(`Emulator "${t}" deleted successfully.`))}catch(t){let n=t;console.error(B(`Failed to delete emulator: ${n.message}`)),n.stdout&&console.error(Ue(n.stdout)),n.stderr&&console.error(Ue(n.stderr)),process.exit(1)}});var Ki=fe;import{Command as fl}from"commander";import{green as gl,red as mt,cyan as So,yellow as Po,dim as Eo}from"colorette";import rl from"ora";var Ce=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=rl(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 Qi from"fs";import*as eo from"path";import{homedir as ol}from"os";import il from"axios";var ar={HTTP_TIMEOUT_MS:2e4},Ft={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 cr="https://matrix.openharmony.cn",X={TAGS_API_URL:`${cr}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${cr}/api/registry/skill/skills`,SKILL_API_BASE:`${cr}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},se={"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"}};import{homedir as Be}from"os";import ge from"path";var re="deveco-mcp";var ie={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:ge.join(Be(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!1,globalConfigPath:"",projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:ge.join(Be(),".cursor","mcp.json"),projectConfigPath:ge.join(Be(),".cursor","mcp.json"),mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!1,globalConfigPath:"",projectConfigPath:ge.join(Be(),".codebuddy","mcp.json"),mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!1,globalConfigPath:"",projectConfigPath:ge.join(process.platform==="win32"?ge.join(process.env.APPDATA??ge.join(Be(),"AppData","Roaming"),"Qoder","SharedClientCache"):ge.join(Be(),".config","Qoder","SharedClientCache"),"mcp.json"),mcpServersKey:"mcpServers",format:"standard"}};function Xi(r,e){let t={PROJECT_PATH:r??".",NODE_MAX_OLD_SPACE_SIZE:"8192"};return e&&(t.DEVECO_PATH=e),{type:"local",command:["devecocli","serve","mcp"],environment:t,enabled:!0}}function Zi(r,e){let t={PROJECT_PATH:r??"${workspaceFolder}",NODE_MAX_OLD_SPACE_SIZE:"8192"};return e&&(t.DEVECO_PATH=e),{type:"stdio",command:"devecocli",args:["serve","mcp"],env:t}}function jt(r,e,t){return r.format==="opencode"?Xi(e,t):Zi(e,t)}var lr=class{client;constructor(){let e={timeout:ar.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ft.USER_AGENT,"accept-language":Ft.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=il.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}
|
|
1218
|
+
${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)}},ye=new lr;async function $t(){let r=await ye.get(X.TAGS_API_URL),t=_t(r,"Tags API").data.skill.find(n=>n.name==="HMOS");if(!t)throw new Error("HMOS tag not found");return t.id}async function dr(r){let e=[],t=1,n=X.DEFAULT_PAGE_SIZE;for(;;){let i=await ye.post(X.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:t,pageSize:n,tagIds:[r]}}),o=_t(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<n)break;t++}return e}async function ur(r,e){let t=await ye.post(X.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:X.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return _t(t,"Skills API").data.list}function to(r){let e=[];for(let[,t]of Object.entries(se)){let n=eo.join(ol(),t.path,r);Qi.existsSync(n)&&e.push(t.displayName)}return e.sort()}function _t(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=ye.parseJson(r);if(t.code!==X.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function no(r){let e=`${X.SKILL_API_BASE}/${r}/checksum`,t=await ye.get(e);return _t(t,"Checksum API").data}import sl from"adm-zip";import al from"crypto";import io from"fs";import R from"path";import{fileURLToPath as cl}from"url";import{homedir as oo}from"os";import{red as ll}from"colorette";var ae=io.promises;function pr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function ro(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 hr(r){return R.isAbsolute(r)?r:R.resolve(process.cwd(),r)}function dl(r){return al.createHash("sha256").update(r).digest("hex")}async function ul(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=dl(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function so(r){let e=`${X.SKILL_API_BASE}/${r}/install?format=zip`,t=await ye.getBinary(e),n=await no(r);return await ul(t,n),t}async function pl(r,e,t){pr(t);let n=new sl(r),i=n.getEntries();try{await ae.stat(e)}catch{await ae.mkdir(e,{recursive:!0})}let o=R.join(e,t);ro(e,o);for(let s of i){let a=R.join(o,s.entryName);ro(o,a)}n.extractAllTo(o,!0)}async function mr(r){let e=se[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(se).join(", ")}`);let t=R.join(oo(),e.path.replace("/skills",""));try{return await ae.access(t),!0}catch{return!1}}function fr(r){let e=se[r];return R.join(oo(),e.path)}function gr(r,e){return R.join(r,"."+e,"skills")}async function hl(r,e,t){pr(e);let n=R.join(r,e);try{if(await ae.access(n),t)await ae.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 yr(r,e,t){await pl(r,e,t),console.log(`Skill ${t} installed to ${R.join(e,t)}`)}async function vr(r,e,t){let n=R.join(e,t);await ae.mkdir(n,{recursive:!0});let i=R.join(n,R.basename(r));await ae.copyFile(r,i),console.log(`Skill ${t} installed to ${n}`)}function ao(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(ll(`Skill ${r} operation failed - ${n}`)),{success:!1,error:n}}async function ze(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await hl(i,r,n);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return ao(r,i,"Installation failed")}}async function wr(r,e){try{pr(r);let t=await e(),n=R.join(t,r);try{await ae.access(n)}catch{return console.log(`Skill ${r} does not exist in ${t}`),{success:!0,skipped:!0}}return await ae.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}`),{success:!0}}catch(t){return ao(r,t,"Removal failed")}}async function co(r,e,t,n=!1){return ze(r,()=>fr(e),i=>yr(t,i,r),n)}async function lo(r,e,t,n=!1){return ze(r,()=>t,i=>yr(e,i,r),n)}async function uo(r,e,t,n,i=!1){return ze(r,()=>gr(t,n),o=>yr(e,o,r),i)}async function po(r,e,t,n=!1){return ze(r,()=>fr(t),i=>vr(e,i,r),n)}async function ho(r,e,t,n,i=!1){return ze(r,()=>gr(t,n),o=>vr(e,o,r),i)}async function mo(r,e,t,n=!1){return ze(r,()=>t,i=>vr(e,i,r),n)}async function fo(r,e){return wr(r,()=>fr(e))}async function go(r,e){return wr(r,()=>e)}async function yo(r,e,t){return wr(r,()=>gr(e,t))}function vo(){let e=R.dirname(cl(import.meta.url));for(;;){let t=R.join(e,"SKILL.md");if(io.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 wo from"fs";import{cyan as ml}from"colorette";async function dt(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await mr(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function ut(){let r=[];for(let e of Object.keys(se))await mr(e)&&r.push(e);return r}function pt(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(ml("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function ve(r,e,t){if(!wo.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!wo.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function ht(r,e,t){if(r&&(e||t))throw new Error("Cannot use --path with --project or --agent");return{resolvedPath:r?hr(r):void 0,resolvedProject:e?hr(e):void 0}}async function Wt(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await dt(r.agent)).map(a=>({project:t,agent:a})):t?i=(await ut()).map(a=>({project:t,agent:a})):r.agent?n=await dt(r.agent):n=await ut(),!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 yl(r){let e=await $t();if(r.all)return(await dr(e)).map(n=>n.enName);{let n=(await ur(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function vl(r,e,t,n){let i=[];if(t.customPath){let o=await lo(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await co(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await uo(r,e,o,s,n);i.push(a)}return i}function wl(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}=ht(r.path,r.project,r.agent);return t&&ve(t,"Project directory",r.force),e&&ve(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function bl(r,e,t){let n=await Wt(r,e,t);return{skillNames:await yl(r),targets:n}}async function Sl(r,e,t,n){let i=[],o=r.length;for(let s=0;s<r.length;s++){let a=r[s],c=o>1?` (${s+1}/${o})`:"";n.start(`Installing ${a}${c}...`);let d;try{d=await so(a)}catch(b){let A=b instanceof Error?b.message:"unknown error";n.fail(),console.log(mt(`${a}: Download failed - ${A}`)),i.push({success:!1});continue}let u=await vl(a,d,e,t);i.push(...u)}return i}async function Pl(r){let e=new Ce;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=wl(r),{skillNames:i,targets:o}=await bl(r,t,n),s=await Sl(i,o,r.force||!1,e);e.stop(),pt(s)}catch(t){throw e.stop(),t}}function El(r){let{resolvedPath:e,resolvedProject:t}=ht(r.path,r.project,r.agent);return t&&ve(t,"Project directory"),e&&ve(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Dl(r,e){let t=new Ce;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=El(e),o=await Il(e,r,n,i);t.stop(),pt(o)}catch(n){throw t.stop(),n}}function bo(r,e=""){if(r.length===0)throw new Error(`No agents found. Please install an AI agent (cursor, opencode, etc.) ${e}`)}async function Ut(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await fo(r,n.agent):await yo(r,n.project,n.agent);t.push(i)}return t}async function Il(r,e,t,n){if(t)return[await go(e,t)];if(n&&r.agent){let a=(await dt(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return Ut(e,a)}if(n){let s=await ut();bo(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return Ut(e,a)}if(r.agent){let a=(await dt(r.agent)).map(c=>({type:"agent",agent:c}));return Ut(e,a)}let i=await ut();bo(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Ut(e,o)}var ft=new fl("skills").description("Manage HMOS skills");ft.command("list").description("List all available HMOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new Ce;try{e.start("Fetching skills...");let t=await $t(),n=await dr(t);if(n.length===0){e.stop(),console.log(Po("No skills available"));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(So(i.enName)),console.log(Eo(i.description));let o=to(i.enName);o.length>0&&console.log(gl(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(mt(t.message)),process.exit(1)}});ft.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new Ce;try{e.start("Searching skills...");let t=await $t(),n=await ur(r,t);if(n.length===0){console.log(Po(`No skills found matching '${r}'`)),e.stop();return}e.succeed(`Found ${n.length} skills`);for(let i of n)console.log(So(i.enName)),console.log(Eo(i.description)),console.log()}catch(t){e.stop(),console.error(mt(t.message)),process.exit(1)}});ft.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); 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 Pl(r)}catch(e){console.error(mt(e.message)),process.exit(1)}});ft.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 (e.g. opencode,trae-cn,cursor,qoder,codebuddy); 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 Dl(r.skill,r)}catch(e){console.error(mt(e.message)),process.exit(1)}});var Do=ft;import{Command as Al,InvalidArgumentError as Ao}from"commander";import{cyan as Bt,red as Io}from"colorette";var O=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(`
|
|
1219
1219
|
`)}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(`
|
|
1220
|
-
`)}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),
|
|
1221
|
-
`);throw new Error(`Device '${e}' not found.
|
|
1220
|
+
`)}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),A=new Date(i,o,s,a,c,d,b);return A.getTime()>t.getTime()+1440*60*1e3&&A.setFullYear(i-1),A}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}`)}};function Ae(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=Le(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 br=[800,1500,2500];function Cl(r){return new Promise(e=>setTimeout(e,r))}var zt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=U.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.includes(t))}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1221
|
+
`)}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(Bt(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return w(Bt(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(n){if(e){let i=this.findDeviceByArg(n,e);if(i)return w(Bt(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(n);throw new Error(`Device '${e}' not found.
|
|
1222
1222
|
Available devices:
|
|
1223
|
-
${
|
|
1224
|
-
`))}}async getConnectedDevices(){try{let e=await this.deviceManager.listDevicesWithName();return e.length===0?(console.error(vr("No running device found.")),console.error("Please ensure:"),console.error(" 1. The physical device is connected via USB and debugging mode is enabled"),console.error(" 2. Or an emulator is running"),null):e}catch(e){return console.error(vr(`Failed to retrieve the device list: ${e.message}`)),null}}async promptDeviceSelection(e){console.log(vl("Multiple devices detected:")),e.forEach((n,i)=>{console.log(` ${i+1}. ${n.name} (${n.serial})`)});let t=await this.getUserInput(e.length);if(t!==null)return e[t].serial}async getUserInput(e){let n=(await import("readline")).createInterface({input:process.stdin,output:process.stdout}),i=await new Promise(s=>{n.question("Please enter the device ID: ",a=>{n.close(),s(a)})}),o=parseInt(i)-1;return o>=0&&o<e?o:(console.error(vr("Invalid device ID")),null)}async getPidForBundle(e,t,n){w(`Trying to get PID for bundle: ${n}`),O.assertBundleName(n);let i=await me(e,["-t",t,"shell","pidof",n]),o=Ae(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 me(e,["-t",t,"shell","hilog","-G",n]),o=Ae(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&&(O.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(O.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(O.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(O.assertHilogKeyword(e.keyword),n.push("-e",O.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,i,o){let a=await ci(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+wr.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(Le(d)!=="transient"||c>=s-1)return a;w(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${wr[c]}ms`),await wl(wr[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 me(e,s),c=Ae(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=O.filterLogsByRelativeWindow(a.stdout||a.stderr,n.fromSeconds,n.toSeconds);d=O.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=Ae(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=O.filterLogsByRelativeWindow(d,n.fromSeconds,n.toSeconds);return u=O.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,(d,u)=>{let b=n.keyword,D=b?d.filter(K=>K.includes(b)):d;if(u!=="stderr")for(let K of D)console.log(K)},d=>{console.error(d.message)},()=>{}),c=Ae(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 me(e,i),s=Ae(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:
|
|
1223
|
+
${o}`)}if(n.length===1){let i=n[0];return w(Bt(`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(){try{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)}catch(e){return console.error(Io(`Failed to retrieve the device list: ${e.message}`)),null}}async getConnectedDevices(){try{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}catch(e){return console.error(Io(`Failed to retrieve the device list: ${e.message}`)),null}}async getPidForBundle(e,t,n){w(`Trying to get PID for bundle: ${n}`),O.assertBundleName(n);let i=await he(e,["-t",t,"shell","pidof",n]),o=Ae(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 he(e,["-t",t,"shell","hilog","-G",n]),o=Ae(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&&(O.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(O.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(O.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(O.assertHilogKeyword(e.keyword),n.push("-e",O.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+br.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(Le(d)!=="transient"||c>=s-1)return a;w(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${br[c]}ms`),await Cl(br[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 he(e,s),c=Ae(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=O.filterLogsByRelativeWindow(a.stdout||a.stderr,n.fromSeconds,n.toSeconds);d=O.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=Ae(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=O.filterLogsByRelativeWindow(d,n.fromSeconds,n.toSeconds);return u=O.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=Ae(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 he(e,i),s=Ae(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
1224
|
${o.stdout}`),o.stdout.split(`
|
|
1226
|
-
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return O.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 me(e,i),s=Ae(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 br,red as Io}from"colorette";function Sl(r){try{return O.parsePositiveInteger(r,"tail")}catch{throw new Do("tail must be a positive integer")}}function Eo(r,e){try{return O.parseDurationToSeconds(r,e)}catch{throw new Do(`${e} must be like 30s, 5m or 2.5m (s/m only; seconds/default must be integers)`)}}function Pl(r){if(r.to&&r.follow)throw new Error("--to cannot be used with --follow");O.assertRelativeTimeRange(r.from,r.to)}var El=new bl("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(Io(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",Sl).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Eo(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Eo(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await Dl(r)});async function Dl(r){try{Pl(r);let e=r.from,t=r.to,n=await x.new(),i=new Ut(n),o=await i.selectDevice(r.device);o||process.exit(1),w(br(`deviceId: ${o}`)),w(br(`type: ${r.crash?"Crash logs":"Common logs"}`)),w(br("Obtaining logs ..."));let s=r.crash?await i.getCrashLog(o,r.bundleName):await i.getHilog(o,{level:r.level,bundleName:r.bundleName,keyword:r.keyword,isFollow:!!r.follow,tail:r.tail,fromSeconds:e,toSeconds:t});r.crash&&s&&(s=O.filterLogsByRelativeWindow(s,e,t),r.tail&&(s=O.getLastLines(s,r.tail))),s&&console.log(s)}catch(e){console.error(Io(e.message)),process.exit(1)}}var Co=El;import yt from"path";import le from"fs";import Pr from"process";import No from"os";import{Command as Hl}from"commander";import{green as Mo,red as Sr,cyan as Fl,yellow as xo}from"colorette";import F from"fs-extra";import k from"path";import*as Ao from"os";import{fileURLToPath as Il}from"url";var Cl={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"}},Al=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function kl(){let r=import.meta.url,e=Il(r);if(e.includes("dist")){let o=k.dirname(e),s=k.dirname(o);return k.join(s,"templates","application")}let t=k.dirname(e),n=k.dirname(t),i=k.dirname(n);return k.join(i,"templates","application")}function ko(r,e){F.mkdirSync(e,{recursive:!0});for(let t of F.readdirSync(r,{withFileTypes:!0})){let n=k.join(r,t.name),i=k.join(e,t.name);if(t.isDirectory()){ko(n,i);continue}F.existsSync(i)||(F.mkdirSync(k.dirname(i),{recursive:!0}),F.copyFileSync(n,i))}}function gt(r,e){let t=F.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&F.writeFileSync(r,n,"utf-8")}function Tl(r,e){if(e===22)return;let t=Cl[e];t&&(gt(k.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),gt(k.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),gt(k.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Ml(r){return Al.filter(t=>!F.existsSync(k.join(r,t))).length===0}function xl(){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 Rl(r){return Ao.platform()==="darwin"?k.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):k.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function Ol(r,e){let t=Rl(e);if(!F.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=k.join(t,i),a=k.join(r,o);F.existsSync(s)&&(F.mkdirSync(k.dirname(a),{recursive:!0}),F.copyFileSync(s,a))}return!0}function Nl(r){let e=xl(),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=k.join(r,n);F.mkdirSync(k.dirname(i),{recursive:!0}),F.writeFileSync(i,e)}}function Ll(r,e){e&&Ol(r,e)||Nl(r)}function To(r,e,t,n,i){let o=kl();if(!F.existsSync(o))throw new Error(`Template directory not found: ${o}`);F.mkdirSync(r,{recursive:!0}),ko(o,r),Ll(r,i),gt(k.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),gt(k.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),Tl(r,n);let s=Ml(r);if(!s)throw new Error("Template integrity check failed");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function jl(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 $l(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 Lo(r){if(No.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function Ro(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=No.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=Lo(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 _l(r){let e=r,t=yt.parse(r).root;for(;e!==t;){if(le.existsSync(e))return e;e=yt.dirname(e)}return le.existsSync(t)?t:null}function Oo(r){let e=_l(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{le.accessSync(e,le.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=yt.join(e,`.deveco_write_test_${Date.now()}`);try{le.writeFileSync(t,"test"),le.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function Wl(r){return`com.example.${r.toLowerCase()}`}function Ul(r,e){if(e){let i=Lo(e),o=yt.resolve(i);if(le.existsSync(o)){if(le.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project in non-empty directory.`)}else Oo(o);return o}let t=Pr.cwd(),n=yt.join(t,r);if(le.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return Oo(n),n}function Bl(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 zl(){try{return await x.new()}catch(r){console.error(xo(`DevEco Studio not found: ${r.message}`)),console.log(xo("Using placeholder API level instead."));return}}var Vl=new Hl("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(Sr("Error: --app-name is required")),Pr.exit(1));let e=r.appName;jl(e);let t=r.bundleName||Wl(e);$l(t),r.projectPath&&Ro(r.projectPath);let n=Ul(e,r.projectPath);Ro(n),console.log(Fl("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await zl(),o=Bl(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=To(n,e,t,o,s);console.log(`
|
|
1227
|
-
`+
|
|
1228
|
-
Failed to create project`)),console.error(Sr(t.message)),Pr.exit(1)}}),Ho=Vl;import{Command as Yl}from"commander";import{red as Bo,cyan as zo}from"colorette";import ql from"fs";import Er from"path";var Dr=ql.promises;async function Fo(r){try{let e=await Dr.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 jo(r,e){let t=Er.dirname(r);await Dr.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Dr.writeFile(r,n,"utf8")}function $o(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function _o(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 Wo(r,e,t,n=!1){let i=oe[r];if(!i)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(oe).join(", ")}`};if(!i.supportsGlobal)return{success:!1,error:`${i.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let o=await Fo(i.globalConfigPath);if($o(o,i.mcpServersKey,ie)&&!n)return console.log(`MCP server ${ie} already configured in ${i.globalConfigPath}`),{success:!0,skipped:!0,configPath:i.globalConfigPath,agentName:r,installType:"global"};let s=jt(i,void 0,t);return _o(o,i.mcpServersKey,ie,s,n),await jo(i.globalConfigPath,o),console.log(`MCP server ${ie} configured in ${i.globalConfigPath}`),{success:!0,configPath:i.globalConfigPath,agentName:r,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${i.displayName}: ${o.message}`}}}async function Ir(r,e,t,n=!1){let i=oe[r];if(!i)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(oe).join(", ")}`};let o=Er.isAbsolute(i.projectConfigPath)?i.projectConfigPath:Er.join(e,i.projectConfigPath);try{let s=await Fo(o);if($o(s,i.mcpServersKey,ie)&&!n)return console.log(`MCP server ${ie} already configured in ${o}`),{success:!0,skipped:!0,configPath:o,agentName:r,installType:"project"};let a=jt(i,e,t);return _o(s,i.mcpServersKey,ie,a,n),await jo(o,s),console.log(`MCP server ${ie} configured in ${o}`),{success:!0,configPath:o,agentName:r,installType:"project"}}catch(s){return{success:!1,error:`Failed to configure MCP for ${i.displayName}: ${s.message}`}}}function Uo(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("MCP Configuration Results:"),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 Cr="deveco-cli";async function Gl(r,e,t){let n=[];if(r.customPath){let i=await uo(Cr,e,r.customPath,t.force);return n.push(i),n}for(let{project:i,agent:o}of r.projectAgents){let s=await lo(Cr,e,i,o,t.force);n.push(s)}for(let i of r.agents){let o=await co(Cr,e,i,t.force);n.push(o)}return n}async function Jl(){try{return(await x.new()).devecoStudioPath}catch{return}}async function Kl(r,e,t,n){let i=[];for(let{project:o,agent:s}of r.projectAgents){let a=await Ir(s,o,t,n);i.push(a)}for(let o of r.agents){let s=await Ir(o,e,t,n);i.push(s)}return i}async function Xl(r,e,t){let n=[];for(let i of r){let o=oe[i];if(!o||!o.supportsGlobal)continue;let s=await Wo(i,process.cwd(),e,t);n.push(s)}return n}async function Zl(r,e,t){let n=await Jl(),i=t.force??!1,o=e?await Kl(r,e,n,i):await Xl(r.agents,n,i);if(o.length>0&&(console.log(zo("MCP Configuration:")),Uo(o)),!e){let s=r.agents.filter(a=>{let c=oe[a];return c&&!c.supportsGlobal});if(s.length>0){let a=s.map(c=>oe[c].displayName);console.error(Bo(`${a.join(" ")} need project path. Use --project to configure project-level MCP: devecocli init --mcp --project <path> --agent ${s[0]}`))}}}async function Ql(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}=ht(r.path,r.project,r.agent);t&&ve(t,"Project directory",r.force),e&&ve(e,"Directory",r.force);let n=await _t(r,e,t);if(r.mcp){await Zl(n,t,r);return}let i=fo(),o=await Gl(n,i,r);console.log(),o.length>0&&(console.log(zo("Skill Installation:")),pt(o))}var ed=new Yl("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); 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 Ql(r)}catch(e){console.error(Bo(e.message)),process.exit(1)}}),Vo=ed;import{Command as lu}from"commander";import{McpServer as su}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as au}from"@modelcontextprotocol/sdk/server/stdio.js";import*as On from"path";import{z as zr}from"zod";var Bt=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 Ar(){return new Bt}import*as he from"fs";import*as Q from"path";import{z as Wr}from"zod";import A from"fs";import*as zt from"os";import*as S from"path";import td from"json5";var kr="Huawei";var nd=3,Jo=3,qo="DevEco Studio",Ko={DevEcoStudio:"deveco_studio"};function Tr(r){if(!A.existsSync(r)||!A.statSync(r).isDirectory())return!1;let e=A.existsSync(S.join(r,"build-profile.json5")),t=A.existsSync(S.join(r,"hvigorfile.js"))||A.existsSync(S.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=A.readFileSync(S.join(r,"build-profile.json5"),"utf-8");return td.parse(n).app!==void 0}catch{return!1}}function Xo(r,e,t){if(e>=t)return null;let n=rd(r),i=id(n);if(i)return i;for(let o of n){let s=Xo(o,e+1,t);if(s)return s}return null}function rd(r){try{let e=A.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(S.join(r,n.name));return t}catch{return[]}}function id(r){for(let e of r)if(Tr(e))return e;return null}function ke(r){if(!r||r.trim()==="")return null;let e=S.resolve(r);if(!A.existsSync(e))return null;if(Tr(e))return e;let t=e;for(let n=1;n<=3;n++){let i=S.dirname(t);if(i===t)break;if(Tr(i))return i;t=i}if(A.statSync(e).isDirectory()){let n=Xo(e,0,nd);if(n)return n}return null}function Zo(r){if(process.platform==="linux")return null;let e=r??Te();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 A.existsSync(n)?t:null}var od=["sdk","default","openharmony","native","llvm","bin","clangd"],Mr=[".idea",".deveco","cxx","compile_commands.json"];function sd(r){return process.platform==="darwin"&&r.endsWith(".app")?S.join(r,"Contents"):r}function Yo(r){let e=new Set,t=[r,sd(r)];for(let n of t){let i=S.join(n,...od);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function Qo(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of Yo(t.trim()))if(e.push(i),A.existsSync(i))return i}let n=r??Te();if(n){for(let i of Yo(n))if(e.push(i),A.existsSync(i))return i}return null}function Vt(r){return S.join(r,...Mr)}function Te(){if(process.platform==="win32"){let r=[S.join("C:\\Program Files",kr,qo),S.join("C:\\Program Files (x86)",kr,qo)];return Go(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",S.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Go(r)}return null}function Go(r){for(let e of r)if(A.existsSync(e))return e;return null}function ad(r){return process.platform==="darwin"?S.join(r,"Contents"):r}function cd(r){if(!r||!A.existsSync(r)||!es(r))return!1;let e=ad(r);return[S.join(e,"plugins","openharmony"),S.join(e,"sdk"),S.join(e,"tools")].some(n=>A.existsSync(n))}function es(r){try{return A.statSync(r).isDirectory()}catch{return!1}}function xr(r,e){return!r||!A.existsSync(r)?!1:e===Ko.DevEcoStudio?cd(r):!1}function qt(r,e=Ko.DevEcoStudio){if(!r)return"";if(xr(r,e))return r;let t=ld(r,e);if(t)return t;let n=dd(r,e);return n||r}function ld(r,e){let t=r;for(let n=0;n<Jo;n++){let i=S.dirname(t);if(!i||i===t)break;if(xr(i,e))return i;t=i}return null}function dd(r,e){if(!A.existsSync(r)||!es(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=Jo)continue;let o=ud(n,i,e,t);if(o)return o}return null}function ud(r,e,t,n){let i;try{i=A.readdirSync(r,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=S.join(r,o.name);if(xr(s,t))return s;n.push({p:s,depth:e+1})}return null}function ts(r){return new Promise(e=>setTimeout(e,r))}var pd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Yt(r){let e=S.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&pd.has(e)}function ns(r){return S.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function se(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Rr(r){return se(r)}function Me(r){let e=Rr(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function vt(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)),Me(t)}}catch{}return r}function rs(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=vt(i);o!==r&&o!==vt(r)&&e.push(o)}}return e}function Gt(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(zt.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(zt.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(zt.homedir(),".local","share","devecocli-mcp-server","logs")}function is(r,e){let t=hd(e),n=md(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=fd(t,r,s);return gd(e,a),i}function hd(r){let e;try{e=A.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function md(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 fd(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{A.mkdirSync(S.dirname(r),{recursive:!0})}catch{}try{A.writeFileSync(r,e.join(`
|
|
1225
|
+
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return O.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 he(e,i),s=Ae(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 Sr,red as ko}from"colorette";import kl from"ora";function Tl(r){try{return O.parsePositiveInteger(r,"tail")}catch{throw new Ao("tail must be a positive integer")}}function Co(r,e){try{return O.parseDurationToSeconds(r,e)}catch{throw new Ao(`${e} must be like 30s, 5m or 2.5m (s/m only; seconds/default must be integers)`)}}function Ml(r){if(r.to&&r.follow)throw new Error("--to cannot be used with --follow");O.assertRelativeTimeRange(r.from,r.to)}async function xl(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 Rl(r,e,t,n){let i=O.filterLogsByRelativeWindow(r,t,n);return e.tail?O.getLastLines(i,e.tail):i}var Ol=new Al("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(ko(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",Tl).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Co(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Co(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await Nl(r)});async function Nl(r){let e=kl({text:"Fetching logs\u2026",color:"cyan"});try{Ml(r);let t=r.from,n=r.to,i=await x.new(),o=new zt(i),s=await o.selectDevice(r.device);s||process.exit(1),w(Sr(`deviceId: ${s}`)),w(Sr(`type: ${r.crash?"Crash logs":"Common logs"}`)),w(Sr("Obtaining logs ...")),e.start(),r.follow&&e.stop();let a=await xl(o,s,r,t,n);e.stop(),r.crash&&a&&(a=Rl(a,r,t,n)),a&&console.log(a)}catch(t){e.stop(),console.error(ko(t.message)),process.exit(1)}}var To=Ol;import yt from"path";import ce from"fs";import Er from"process";import Fo from"os";import{Command as ql}from"commander";import{green as Oo,red as Pr,cyan as Yl,yellow as No}from"colorette";import F from"fs-extra";import k from"path";import*as Mo from"os";import{fileURLToPath as Ll}from"url";var Hl={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"}},Fl=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function jl(){let r=import.meta.url,e=Ll(r);if(e.includes("dist")){let o=k.dirname(e),s=k.dirname(o);return k.join(s,"templates","application")}let t=k.dirname(e),n=k.dirname(t),i=k.dirname(n);return k.join(i,"templates","application")}function xo(r,e){F.mkdirSync(e,{recursive:!0});for(let t of F.readdirSync(r,{withFileTypes:!0})){let n=k.join(r,t.name),i=k.join(e,t.name);if(t.isDirectory()){xo(n,i);continue}F.existsSync(i)||(F.mkdirSync(k.dirname(i),{recursive:!0}),F.copyFileSync(n,i))}}function gt(r,e){let t=F.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&F.writeFileSync(r,n,"utf-8")}function $l(r,e){if(e===22)return;let t=Hl[e];t&&(gt(k.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),gt(k.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),gt(k.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function _l(r){return Fl.filter(t=>!F.existsSync(k.join(r,t))).length===0}function Wl(){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 Ul(r){return Mo.platform()==="darwin"?k.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):k.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function Bl(r,e){let t=Ul(e);if(!F.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=k.join(t,i),a=k.join(r,o);F.existsSync(s)&&(F.mkdirSync(k.dirname(a),{recursive:!0}),F.copyFileSync(s,a))}return!0}function zl(r){let e=Wl(),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=k.join(r,n);F.mkdirSync(k.dirname(i),{recursive:!0}),F.writeFileSync(i,e)}}function Vl(r,e){e&&Bl(r,e)||zl(r)}function Ro(r,e,t,n,i){let o=jl();if(!F.existsSync(o))throw new Error(`Template directory not found: ${o}`);F.mkdirSync(r,{recursive:!0}),xo(o,r),Vl(r,i),gt(k.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),gt(k.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),$l(r,n);let s=_l(r);if(!s)throw new Error("Template integrity check failed");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function Gl(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 Jl(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 jo(r){if(Fo.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function Lo(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=Fo.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=jo(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 Kl(r){let e=r,t=yt.parse(r).root;for(;e!==t;){if(ce.existsSync(e))return e;e=yt.dirname(e)}return ce.existsSync(t)?t:null}function Ho(r){let e=Kl(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{ce.accessSync(e,ce.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=yt.join(e,`.deveco_write_test_${Date.now()}`);try{ce.writeFileSync(t,"test"),ce.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function Xl(r){return`com.example.${r.toLowerCase()}`}function Zl(r,e){if(e){let i=jo(e),o=yt.resolve(i);if(ce.existsSync(o)){if(ce.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project in non-empty directory.`)}else Ho(o);return o}let t=Er.cwd(),n=yt.join(t,r);if(ce.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return Ho(n),n}function Ql(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 ed(){try{return await x.new()}catch(r){console.error(No(`DevEco Studio not found: ${r.message}`)),console.log(No("Using placeholder API level instead."));return}}var td=new ql("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(Pr("Error: --app-name is required")),Er.exit(1));let e=r.appName;Gl(e);let t=r.bundleName||Xl(e);Jl(t),r.projectPath&&Lo(r.projectPath);let n=Zl(e,r.projectPath);Lo(n),console.log(Yl("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await ed(),o=Ql(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Ro(n,e,t,o,s);console.log(`
|
|
1226
|
+
`+Oo("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(Oo("Template integrity check passed"))}catch(e){let t=e;console.error(Pr(`
|
|
1227
|
+
Failed to create project`)),console.error(Pr(t.message)),Er.exit(1)}}),$o=td;import{Command as rd}from"commander";import{red as qo,cyan as Yo}from"colorette";import nd from"fs";import Dr from"path";var Ir=nd.promises;async function _o(r){try{let e=await Ir.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 Wo(r,e){let t=Dr.dirname(r);await Ir.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Ir.writeFile(r,n,"utf8")}function Uo(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function Bo(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,t,n=!1){let i=ie[r];if(!i)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(ie).join(", ")}`};if(!i.supportsGlobal)return{success:!1,error:`${i.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let o=await _o(i.globalConfigPath);if(Uo(o,i.mcpServersKey,re)&&!n)return console.log(`MCP server ${re} already configured in ${i.globalConfigPath}`),{success:!0,skipped:!0,configPath:i.globalConfigPath,agentName:r,installType:"global"};let s=jt(i,void 0,t);return Bo(o,i.mcpServersKey,re,s,n),await Wo(i.globalConfigPath,o),console.log(`MCP server ${re} configured in ${i.globalConfigPath}`),{success:!0,configPath:i.globalConfigPath,agentName:r,installType:"global"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${i.displayName}: ${o.message}`}}}async function Cr(r,e,t,n=!1){let i=ie[r];if(!i)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(ie).join(", ")}`};let o=Dr.isAbsolute(i.projectConfigPath)?i.projectConfigPath:Dr.join(e,i.projectConfigPath);try{let s=await _o(o);if(Uo(s,i.mcpServersKey,re)&&!n)return console.log(`MCP server ${re} already configured in ${o}`),{success:!0,skipped:!0,configPath:o,agentName:r,installType:"project"};let a=jt(i,e,t);return Bo(s,i.mcpServersKey,re,a,n),await Wo(o,s),console.log(`MCP server ${re} configured in ${o}`),{success:!0,configPath:o,agentName:r,installType:"project"}}catch(s){return{success:!1,error:`Failed to configure MCP for ${i.displayName}: ${s.message}`}}}function Vo(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("MCP Configuration Results:"),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 Ar="deveco-cli";async function id(r,e,t){let n=[];if(r.customPath){let i=await mo(Ar,e,r.customPath,t.force);return n.push(i),n}for(let{project:i,agent:o}of r.projectAgents){let s=await ho(Ar,e,i,o,t.force);n.push(s)}for(let i of r.agents){let o=await po(Ar,e,i,t.force);n.push(o)}return n}async function od(){try{return(await x.new()).devecoStudioPath}catch{return}}async function sd(r,e,t,n){let i=[];for(let{project:o,agent:s}of r.projectAgents){let a=await Cr(s,o,t,n);i.push(a)}for(let o of r.agents){let s=await Cr(o,e,t,n);i.push(s)}return i}async function ad(r,e,t){let n=[];for(let i of r){let o=ie[i];if(!o||!o.supportsGlobal)continue;let s=await zo(i,process.cwd(),e,t);n.push(s)}return n}async function cd(r,e,t){let n=await od(),i=t.force??!1,o=e?await sd(r,e,n,i):await ad(r.agents,n,i);if(o.length>0&&(console.log(Yo("MCP Configuration:")),Vo(o)),!e){let s=r.agents.filter(a=>{let c=ie[a];return c&&!c.supportsGlobal});if(s.length>0){let a=s.map(c=>ie[c].displayName);console.error(qo(`${a.join(" ")} need project path. Use --project to configure project-level MCP: devecocli init --mcp --project <path> --agent ${s[0]}`))}}}async function ld(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}=ht(r.path,r.project,r.agent);t&&ve(t,"Project directory",r.force),e&&ve(e,"Directory",r.force);let n=await Wt(r,e,t);if(r.mcp){await cd(n,t,r);return}let i=vo(),o=await id(n,i,r);console.log(),o.length>0&&(console.log(Yo("Skill Installation:")),pt(o))}var dd=new rd("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); 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 ld(r)}catch(e){console.error(qo(e.message)),process.exit(1)}}),Go=dd;import{Command as wu}from"commander";import{McpServer as gu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as yu}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Ln from"path";import{z as Vr}from"zod";var Vt=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 kr(){return new Vt}import*as pe from"fs";import*as Q from"path";import{z as Ur}from"zod";import C from"fs";import*as qt from"os";import*as S from"path";import ud from"json5";var Tr="Huawei";var pd=3,Zo=3,Jo="DevEco Studio",Qo={DevEcoStudio:"deveco_studio"};function Mr(r){if(!C.existsSync(r)||!C.statSync(r).isDirectory())return!1;let e=C.existsSync(S.join(r,"build-profile.json5")),t=C.existsSync(S.join(r,"hvigorfile.js"))||C.existsSync(S.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=C.readFileSync(S.join(r,"build-profile.json5"),"utf-8");return ud.parse(n).app!==void 0}catch{return!1}}function es(r,e,t){if(e>=t)return null;let n=hd(r),i=md(n);if(i)return i;for(let o of n){let s=es(o,e+1,t);if(s)return s}return null}function hd(r){try{let e=C.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(S.join(r,n.name));return t}catch{return[]}}function md(r){for(let e of r)if(Mr(e))return e;return null}function ke(r){if(!r||r.trim()==="")return null;let e=S.resolve(r);if(!C.existsSync(e))return null;if(Mr(e))return e;let t=e;for(let n=1;n<=3;n++){let i=S.dirname(t);if(i===t)break;if(Mr(i))return i;t=i}if(C.statSync(e).isDirectory()){let n=es(e,0,pd);if(n)return n}return null}function ts(r){if(process.platform==="linux")return null;let e=r??Te();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 C.existsSync(n)?t:null}var fd=["sdk","default","openharmony","native","llvm","bin","clangd"],xr=[".idea",".deveco","cxx","compile_commands.json"];function gd(r){return process.platform==="darwin"&&r.endsWith(".app")?S.join(r,"Contents"):r}function Ko(r){let e=new Set,t=[r,gd(r)];for(let n of t){let i=S.join(n,...fd);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function ns(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of Ko(t.trim()))if(e.push(i),C.existsSync(i))return i}let n=r??Te();if(n){for(let i of Ko(n))if(e.push(i),C.existsSync(i))return i}return null}function Yt(r){return S.join(r,...xr)}function Te(){if(process.platform==="win32"){let r=[S.join("C:\\Program Files",Tr,Jo),S.join("C:\\Program Files (x86)",Tr,Jo)];return Xo(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",S.join(process.env.HOME??"","Applications","DevEco Studio.app")];return Xo(r)}return null}function Xo(r){for(let e of r)if(C.existsSync(e))return e;return null}function yd(r){return process.platform==="darwin"?S.join(r,"Contents"):r}function vd(r){if(!r||!C.existsSync(r)||!rs(r))return!1;let e=yd(r);return[S.join(e,"plugins","openharmony"),S.join(e,"sdk"),S.join(e,"tools")].some(n=>C.existsSync(n))}function rs(r){try{return C.statSync(r).isDirectory()}catch{return!1}}function Rr(r,e){return!r||!C.existsSync(r)?!1:e===Qo.DevEcoStudio?vd(r):!1}function Gt(r,e=Qo.DevEcoStudio){if(!r)return"";if(Rr(r,e))return r;let t=wd(r,e);if(t)return t;let n=bd(r,e);return n||r}function wd(r,e){let t=r;for(let n=0;n<Zo;n++){let i=S.dirname(t);if(!i||i===t)break;if(Rr(i,e))return i;t=i}return null}function bd(r,e){if(!C.existsSync(r)||!rs(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=Zo)continue;let o=Sd(n,i,e,t);if(o)return o}return null}function Sd(r,e,t,n){let i;try{i=C.readdirSync(r,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=S.join(r,o.name);if(Rr(s,t))return s;n.push({p:s,depth:e+1})}return null}function is(r){return new Promise(e=>setTimeout(e,r))}var Pd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function Jt(r){let e=S.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&Pd.has(e)}function os(r){return S.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function oe(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Or(r){return oe(r)}function Me(r){let e=Or(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function vt(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)),Me(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=vt(i);o!==r&&o!==vt(r)&&e.push(o)}}return e}function Kt(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(qt.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(qt.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(qt.homedir(),".local","share","devecocli-mcp-server","logs")}function as(r,e){let t=Ed(e),n=Dd(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=Id(t,r,s);return Cd(e,a),i}function Ed(r){let e;try{e=C.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Dd(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 Id(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 Cd(r,e){try{C.mkdirSync(S.dirname(r),{recursive:!0})}catch{}try{C.writeFileSync(r,e.join(`
|
|
1229
1228
|
`)+`
|
|
1230
|
-
`,"utf8")}catch{}}function
|
|
1231
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);
|
|
1229
|
+
`,"utf8")}catch{}}function cs(r,e,t="[Cleanup]"){try{let n=S.dirname(r);if(!C.existsSync(n))return;let i=Date.now();for(let o of C.readdirSync(n,{withFileTypes:!0}))o.isDirectory()&&Ad(S.join(n,o.name),i,e,t)}catch{}}function Ad(r,e,t,n){try{let{mtimeMs:i}=C.statSync(r);if(e-i<=t)return;C.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}`)}}import*as D from"fs";import*as Zt from"path";var ls="mcp-server.log",kd="mcp-server",Td={maxSize:10*1024*1024,maxFiles:4},Nr=class{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;constructor(e,t){this.rotationOptions={...Td,...t},e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Kt(),this.currentLogFile=Zt.join(this.logDir,ls),D.existsSync(this.logDir)||D.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 Zt.join(this.logDir,`${kd}-${e}.log.${t}`)}fileExists(e){try{return D.accessSync(e,D.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=D.readdirSync(this.logDir),t=[];for(let i of e)if(i===ls||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=Zt.join(this.logDir,i),s=D.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{D.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)&&D.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)&&D.renameSync(o,s)}let n=this.getRotatedFileName(e,1);D.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=D.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=D.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{D.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}
|
|
1230
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);D.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{D.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},Y=null;function Lr(r=!1){Y&&Y.dispose(),Y=new Nr(r)}function ds(){Y&&(Y.dispose(),Y=null)}function us(){Y&&Y.flush()}function ps(){return Y?.getLogFilePath()??null}function hs(){return Y?.getLogDirectory()??null}function Xt(){return Y||Lr(!1),Y}var m={debug:(r,...e)=>Xt().debug(r,...e),info:(r,...e)=>Xt().info(r,...e),warn:(r,...e)=>Xt().warn(r,...e),error:(r,...e)=>Xt().error(r,...e)};function ms(r){return"method"in r&&!("id"in r)}import{spawn as xd}from"child_process";import{EventEmitter as Rd}from"events";import*as qe from"fs";import*as bs from"path";import*as fs from"util";var Hr="";function gs(r){if(!r||r==="auto"||r==="stdout"||r==="none"){Hr="";return}Hr=r}function ys(){return Hr||(hs()??"")}function Qt(r,...e){if(e.length===0)return r;try{return fs.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var l={info(r,...e){m.info(`[lsp] ${Qt(r,...e)}`)},warn(r,...e){m.warn(`[lsp] ${Qt(r,...e)}`)},error(r,...e){m.error(`[lsp] ${Qt(r,...e)}`)},debug(r,...e){m.debug(`[lsp] ${Qt(r,...e)}`)}};import*as wt from"fs";import*as Fr from"os";import*as Ve from"path";import Md from"json5";function q(r){if(!wt.existsSync(r))return null;try{let e=wt.readFileSync(r,"utf-8");return e.trim()?Md.parse(e):null}catch{return null}}function le(r){try{let e=Ve.resolve(r),t=new URL(`file://${e}`).toString();if(Fr.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 en(r){return r&&r.replace(/\\/g,"/")}function j(r){let e=Ve.normalize(r).replace(/\\/g,"/");if(Fr.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function vs(){let r=process.platform;return r==="win32"?"Windows":r==="darwin"?"Mac":"Linux"}function ws(r){return Ve.join(r,"build-profile.json5")}var tn=class extends Rd{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;async start(){let t=bs.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=j(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=xd(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
1231
|
\r
|
|
1233
1232
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
|
|
1234
1233
|
\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 en=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 tn=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 Fr(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)}},Fr=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var nn=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 f(r){return typeof r=="object"&&r!==null}function jr(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}var Ed={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"},rn={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={...Ed,...rn},T="2.0",G={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 Dd(r){if(!f(r))return!1;let e=r.textDocument;return f(e)&&typeof e.uri=="string"}function Id(r){return f(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}var on=class r{client;isInitialized=!1;stopOnce=null;callbacks=new nn;requestCallbacks=new en;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new Qt(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:T,method:g.EXIT,params:{}}),G.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:T,method:g.INITIALIZED,params:{editors:e}}),G.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),G.EMPTY)}sendAsyncRequest(e,t,n,i){if(!f(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Dd(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=de(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:T,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(!Id(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method:g.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),g.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!f(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:T,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),G.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=de(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new tn(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,rn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:g.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),G.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=de(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,rn.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:g.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),G.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=de(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:T,method:g.DID_CLOSE,params:{textDocument:{uri:n}}}),G.DID_CLOSE)}getDiagnosticMessage(e){let t=de(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:T,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;f(t)&&f(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:T,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(!f(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 Cn from"path";import*as pn from"path";var sn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var an=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var cn=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var ln=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var dn=class{typeSetting=new cn;parameterNames=new ln};var un=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=j(pn.dirname(t)),this.indexingDataLocation=j(i),this.loggerPath=j(pn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new sn;gutterIconsSetting=new an;inlayHintsSetting=new dn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as vs from"path";var bt=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(j(vs.join(e,"src","main","resources")))}};var Cd="OS",Ye=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${Cd}`;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 bt(e)):this.buildProfileParam=new bt}toString(){return JSON.stringify(this)}};var Ge=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as _ from"path";import*as Xe from"fs";var hn=class{modulePath;dependencies={};dynamicDependencies={}};var xe=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 Je=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 ue from"path";import*as mn from"fs";var Ke=class{name="";version="";storePath="";dependencyPath="";path=""};var E={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"},St=`${E.HVIGOR_CACHE}/${E.DEPENDENCY}`,Re=`${E.DEPENDENCY}${E.JSON5}`;var Pt=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=ue.join(this.dependencyPath,E.OH_PACKAGE_JSON5),n=q(t);n&&(this.dependencies=this.getDependencyList(n,E.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,E.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,E.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!f(e))return n;let i=e[t];if(!f(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 Ke;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=ue.normalize(ue.join(this.modulePath,E.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)),ue.isAbsolute(s)){n.dependencyPath=o;return}i||(o=ue.normalize(ue.join(this.modulePath,s))),mn.existsSync(o)&&mn.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as Et from"fs";import*as we from"path";import Ad from"json5";var fn=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 we.join(this.projectPath,E.OH_MODULES_PATH,E.OHPM_PATH,E.LOCK_JSON5_FILE)}readLockFile(e){if(!Et.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Et.readFileSync(e,"utf8"),n=Ad.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(!f(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,E.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,E.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,E.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!f(e))return t;for(let[n,i]of Object.entries(e)){if(!f(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(!f(e))return[];for(let[i,o]of Object.entries(e))if(f(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(!f(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!f(s))return[];for(let[a,c]of Object.entries(s)){if(!f(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",b=new Ke;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 D=`${a}@${u}`;this.storePathMap.has(D)&&(b.storePath=this.storePathMap.get(D)||""),o.push(b)}return o}parseDependencyPath(e,t,n,i,o){let s=we.normalize(we.join(this.projectPath,t,E.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(we.isAbsolute(c)||(c=we.join(this.projectPath,a)),!Et.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 Oe=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=gs(this.projectRoot);try{let t=q(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 ws(r){return f(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Dt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Oe(this.projectPath)}projectPath;sdkPath;moduleInfoParse;getAllDependencyMap(e){let t=this.projectPath,n=_.join(t,St),i=_.join(n,Re);if(!Xe.existsSync(n)||!Xe.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 Je(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)ws(a)&&this.parseSingleModule(a,n,o,e);return{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=_.join(n,St),o=_.join(i,Re);if(!Xe.existsSync(i)||!Xe.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 Je(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(!ws(d))continue;let u=d.name;if(s&&!s.has(u))continue;let b=d.srcPath,D=_.resolve(this.projectPath,b),K=_.join(i,u),Hn=j(D),Tt=this.buildModuleDependencies(u,Hn,K,a);Tt.moduleName=u,t.push(Tt)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=e.srcPath,a=_.resolve(this.projectPath,s),c=_.join(t,o),d=j(a),u=new Ye(d),b=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=b,u.moduleJsonParam=new Ge(D),i.push(u)}buildModuleDependencies(e,t,n,i){let o=new Je(this.projectPath,e,t);Pt.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 hn;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 xe(o);for(let o of e.finalDynamicDependencies)i[o.name]=new xe(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=_.join(e,E.OH_PACKAGE_JSON5);if(!Xe.existsSync(n))return;Pt.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=new fn(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=_.join(e,"src","main","module.json5"),i=q(n);if(!f(i)||!f(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(f(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)f(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=_.join(e,"src","main","resources","base","profile","main_pages.json"),n=q(t);return!f(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=_.join(this.sdkPath,"default","sdk-pkg.json"),n=q(t);!f(n)||!f(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=_.join(this.projectPath,"build-profile.json5"),n=q(t);if(!f(n)||!f(n.app)||!Array.isArray(n.app.products)||n.app.products.length===0)return;let i=n.app.products[0];if(!f(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!f(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 gn=class{constructor(e=[]){this.valueSet=e}valueSet};var Ze=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var bs=(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))(bs||{}),Ss=()=>Object.values(bs).filter(r=>typeof r=="number");var yn=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var vn=class{applyEdit=!0;workspaceEdit=new yn;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new gn(Ss());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Ze;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var wn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var bn=class{constructor(e=[]){this.valueSet=e}valueSet};var Sn=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Ps=(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))(Ps||{}),Es=()=>Object.values(Ps).filter(r=>typeof r=="number");var Pn=class{completionItemKind=new bn(Es());completionItem=new Sn;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var En=class{synchronization=new wn;completion=new Pn;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 Ze;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Dn=class{workspace=new vn;textDocument=new En;notebookDocument=null;window=null;general=null;experimental=null};var In=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function Qe(r){return f(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function Ds(r){return f(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function Is(r){if(!f(r)||typeof r.text!="string")return!1;let e=r.range;return f(e)?Qe(e.start)&&Qe(e.end):!1}var An=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=Cn.resolve(t,"ace-server","out","index.js"),this.logPath=ms(),this.indexLogPath=i||this.logPath,this.messageHandle=new on({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=de(this.rootUri),o=new un(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Dt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s,this.currentParams=new In(i,o,new Dn),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:T,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=de(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=f(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:T,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:T,id:e,result:f(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Dt(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 xe({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ye(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Ge([]),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=Zt(Cn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Zt(Cn.join(t,"default/openharmony/ets/api")),o=Zt(Cn.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(!f(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!f(n)||typeof n.uri!="string"||!Qe(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,G.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!f(n)||typeof n.uri!="string"||!Qe(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,G.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!f(n)||typeof n.uri!="string"||!Qe(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,G.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!us(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(!f(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!Ds(n)||!jr(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(!f(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!f(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(Is)){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(!f(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!f(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(!f(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(!f(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 pe from"fs";import*as z from"path";import{createHash as kd}from"crypto";import{EventEmitter as Td}from"events";var kn=class extends Td{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(!pe.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=pe.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=z.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=z.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=z.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=z.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=q(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=z.join(this.projectRoot,E.OH_PACKAGE_JSON5);pe.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=z.resolve(this.projectRoot,o.srcPath),a=z.join(s,E.OH_PACKAGE_JSON5);pe.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return z.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=pe.readFileSync(t,"utf-8");return kd("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=pe.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:z.basename(t),relativePath:z.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 be from"fs";import*as Z from"path";import{createHash as Md}from"crypto";import{EventEmitter as xd}from"events";var Tn=class extends xd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=Z.join(t,St)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!be.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=be.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 j(Z.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===E.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Re)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Z.join(this.depMapDir,n);be.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=Z.join(this.depMapDir,E.OH_PACKAGE_JSON5),n=Z.join(this.depMapDir,Re),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:Z.join(this.depMapDir,s.name,E.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!be.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=Z.join(this.depMapDir,Re);try{let n=q(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 j(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=Z.join(this.depMapDir,a.name,E.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=Z.join(this.depMapDir,o,E.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=be.readFileSync(t,"utf-8");return Md("sha256").update(n).digest("hex")}catch{return null}}};import{spawnSync as Cs}from"child_process";import*as xn from"path";import*as Mn from"fs";var As=600*1e3;function $r(r,e,t,n,i,o){try{let s=o==="Windows",a={...process.env,DEVECO_SDK_HOME:n};if(s){let c=/\.(bat|cmd)$/i.test(t),d;c?d=[`$env:DEVECO_SDK_HOME='${n.replace(/'/g,"''")}';`,`cd '${r.replace(/'/g,"''")}';`,`& '${t.replace(/'/g,"''")}' ${i}`].join(" "):d=[`$env:DEVECO_SDK_HOME='${n.replace(/'/g,"''")}';`,`cd '${r.replace(/'/g,"''")}';`,`& '${e.replace(/'/g,"''")}' '${t.replace(/'/g,"''")}' ${i}`].join(" ");let u=Cs("powershell.exe",["-Command",d],{cwd:r,env:a,encoding:"utf8",timeout:As,windowsHide:!0});return ks(u)}else{let c=[`export DEVECO_SDK_HOME='${n.replace(/'/g,"'\\''")}'`,`cd '${r.replace(/'/g,"'\\''")}'`,`'${e.replace(/'/g,"'\\''")}' '${t.replace(/'/g,"'\\''")}' ${i}`].join(" && "),d=Cs("bash",["-c",c],{cwd:r,env:a,encoding:"utf8",timeout:As});return ks(d)}}catch(s){return{success:!1,output:`Build execution exception: ${(s instanceof Error?s:new Error(String(s))).message}`,exitCode:-1}}}function ks(r){let e=r.stdout??"",t=r.stderr??"",n=[e,t].filter(Boolean).join(`
|
|
1234
|
+
`);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 nn=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 rn=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 jr(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)}},jr=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var on=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 f(r){return typeof r=="object"&&r!==null}function $r(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}var Od={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"},sn={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={...Od,...sn},T="2.0",G={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 Nd(r){if(!f(r))return!1;let e=r.textDocument;return f(e)&&typeof e.uri=="string"}function Ld(r){return f(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}var an=class r{client;isInitialized=!1;stopOnce=null;callbacks=new on;requestCallbacks=new nn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new tn(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:T,method:g.EXIT,params:{}}),G.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:T,method:g.INITIALIZED,params:{editors:e}}),G.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),G.EMPTY)}sendAsyncRequest(e,t,n,i){if(!f(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Nd(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=le(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:T,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(!Ld(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method:g.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),g.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!f(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:T,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),G.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=le(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new rn(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,sn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:g.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),G.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=le(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,sn.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:g.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),G.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=le(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:T,method:g.DID_CLOSE,params:{textDocument:{uri:n}}}),G.DID_CLOSE)}getDiagnosticMessage(e){let t=le(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:T,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;f(t)&&f(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:T,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(!f(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 kn from"path";import*as mn from"path";var cn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var ln=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var dn=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var un=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var pn=class{typeSetting=new dn;parameterNames=new un};var hn=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=j(mn.dirname(t)),this.indexingDataLocation=j(i),this.loggerPath=j(mn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new cn;gutterIconsSetting=new ln;inlayHintsSetting=new pn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Ss from"path";var bt=class{productName="default";buildModeName="debug";targetName="default";arkTSVersion="1.1";resourceDirectories=[];targetESVersion="ES2021";maxFlowDepth=2e3;caseSensitiveCheck=!0;tsImportSendable=!1;compatibleSdkVersionStage="";useNormalizedOHMUrl=!0;reExportCheckMode="noCheck";skipOhModulesLint=!1;byteCodeHar=!0;obfuscationRuleOptionsEnable=!1;enableStrictCheckOHModules=!1;sourceRoots=[];constructor(e){e&&this.resourceDirectories.push(j(Ss.join(e,"src","main","resources")))}};var Hd="OS",Ye=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${Hd}`;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 bt(e)):this.buildProfileParam=new bt}toString(){return JSON.stringify(this)}};var Ge=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as _ from"path";import*as Xe from"fs";var fn=class{modulePath;dependencies={};dynamicDependencies={}};var xe=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 Je=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 de from"path";import*as gn from"fs";var Ke=class{name="";version="";storePath="";dependencyPath="";path=""};var E={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"},St=`${E.HVIGOR_CACHE}/${E.DEPENDENCY}`,Re=`${E.DEPENDENCY}${E.JSON5}`;var Pt=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=de.join(this.dependencyPath,E.OH_PACKAGE_JSON5),n=q(t);n&&(this.dependencies=this.getDependencyList(n,E.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,E.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,E.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!f(e))return n;let i=e[t];if(!f(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 Ke;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=de.normalize(de.join(this.modulePath,E.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)),de.isAbsolute(s)){n.dependencyPath=o;return}i||(o=de.normalize(de.join(this.modulePath,s))),gn.existsSync(o)&&gn.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as Et from"fs";import*as we from"path";import Fd from"json5";var yn=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 we.join(this.projectPath,E.OH_MODULES_PATH,E.OHPM_PATH,E.LOCK_JSON5_FILE)}readLockFile(e){if(!Et.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Et.readFileSync(e,"utf8"),n=Fd.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(!f(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,E.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,E.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,E.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!f(e))return t;for(let[n,i]of Object.entries(e)){if(!f(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(!f(e))return[];for(let[i,o]of Object.entries(e))if(f(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(!f(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!f(s))return[];for(let[a,c]of Object.entries(s)){if(!f(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",b=new Ke;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 A=`${a}@${u}`;this.storePathMap.has(A)&&(b.storePath=this.storePathMap.get(A)||""),o.push(b)}return o}parseDependencyPath(e,t,n,i,o){let s=we.normalize(we.join(this.projectPath,t,E.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(we.isAbsolute(c)||(c=we.join(this.projectPath,a)),!Et.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 Oe=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=ws(this.projectRoot);try{let t=q(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 Ps(r){return f(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Dt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Oe(this.projectPath)}projectPath;sdkPath;moduleInfoParse;getAllDependencyMap(e){let t=this.projectPath,n=_.join(t,St),i=_.join(n,Re);if(!Xe.existsSync(n)||!Xe.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 Je(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)Ps(a)&&this.parseSingleModule(a,n,o,e);return{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=_.join(n,St),o=_.join(i,Re);if(!Xe.existsSync(i)||!Xe.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 Je(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(!Ps(d))continue;let u=d.name;if(s&&!s.has(u))continue;let b=d.srcPath,A=_.resolve(this.projectPath,b),Se=_.join(i,u),jn=j(A),Tt=this.buildModuleDependencies(u,jn,Se,a);Tt.moduleName=u,t.push(Tt)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=e.srcPath,a=_.resolve(this.projectPath,s),c=_.join(t,o),d=j(a),u=new Ye(d),b=this.buildModuleDependencies(o,d,c,n);this.parseModuleJson5(d,u);let A=this.parseMainPages(d);this.parseSdkJson(u),this.parseCompatibleSdkVersion(u),u.moduleName=o,u.moduleType=o,u.packageName=o,u.moduleDependencies=b,u.moduleJsonParam=new Ge(A),i.push(u)}buildModuleDependencies(e,t,n,i){let o=new Je(this.projectPath,e,t);Pt.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 fn;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 xe(o);for(let o of e.finalDynamicDependencies)i[o.name]=new xe(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=_.join(e,E.OH_PACKAGE_JSON5);if(!Xe.existsSync(n))return;Pt.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=new yn(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=_.join(e,"src","main","module.json5"),i=q(n);if(!f(i)||!f(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(f(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)f(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=_.join(e,"src","main","resources","base","profile","main_pages.json"),n=q(t);return!f(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=_.join(this.sdkPath,"default","sdk-pkg.json"),n=q(t);!f(n)||!f(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=_.join(this.projectPath,"build-profile.json5"),n=q(t);if(!f(n)||!f(n.app)||!Array.isArray(n.app.products)||n.app.products.length===0)return;let i=n.app.products[0];if(!f(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!f(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 vn=class{constructor(e=[]){this.valueSet=e}valueSet};var Ze=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Es=(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))(Es||{}),Ds=()=>Object.values(Es).filter(r=>typeof r=="number");var wn=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var bn=class{applyEdit=!0;workspaceEdit=new wn;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new vn(Ds());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Ze;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Sn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Pn=class{constructor(e=[]){this.valueSet=e}valueSet};var En=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Is=(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))(Is||{}),Cs=()=>Object.values(Is).filter(r=>typeof r=="number");var Dn=class{completionItemKind=new Pn(Cs());completionItem=new En;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var In=class{synchronization=new Sn;completion=new Dn;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 Ze;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Cn=class{workspace=new bn;textDocument=new In;notebookDocument=null;window=null;general=null;experimental=null};var An=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function Qe(r){return f(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function As(r){return f(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function ks(r){if(!f(r)||typeof r.text!="string")return!1;let e=r.range;return f(e)?Qe(e.start)&&Qe(e.end):!1}var Tn=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=kn.resolve(t,"ace-server","out","index.js"),this.logPath=ys(),this.indexLogPath=i||this.logPath,this.messageHandle=new an({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=le(this.rootUri),o=new hn(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Dt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s,this.currentParams=new An(i,o,new Cn),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:T,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=le(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=f(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:T,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:T,id:e,result:f(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Dt(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 xe({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Ye(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new Ge([]),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=en(kn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=en(kn.join(t,"default/openharmony/ets/api")),o=en(kn.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(!f(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!f(n)||typeof n.uri!="string"||!Qe(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,G.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!f(n)||typeof n.uri!="string"||!Qe(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,G.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!f(n)||typeof n.uri!="string"||!Qe(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,G.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!ms(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(!f(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!As(n)||!$r(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(!f(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!f(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(ks)){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(!f(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!f(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(!f(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(!f(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 ue from"fs";import*as z from"path";import{createHash as jd}from"crypto";import{EventEmitter as $d}from"events";var Mn=class extends $d{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(!ue.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=ue.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=z.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=z.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=z.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=z.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=q(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=z.join(this.projectRoot,E.OH_PACKAGE_JSON5);ue.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=z.resolve(this.projectRoot,o.srcPath),a=z.join(s,E.OH_PACKAGE_JSON5);ue.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return z.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=ue.readFileSync(t,"utf-8");return jd("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=ue.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:z.basename(t),relativePath:z.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 be from"fs";import*as Z from"path";import{createHash as _d}from"crypto";import{EventEmitter as Wd}from"events";var xn=class extends Wd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=Z.join(t,St)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!be.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=be.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 j(Z.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===E.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Re)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Z.join(this.depMapDir,n);be.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=Z.join(this.depMapDir,E.OH_PACKAGE_JSON5),n=Z.join(this.depMapDir,Re),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:Z.join(this.depMapDir,s.name,E.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!be.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=Z.join(this.depMapDir,Re);try{let n=q(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 j(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=Z.join(this.depMapDir,a.name,E.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=Z.join(this.depMapDir,o,E.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=be.readFileSync(t,"utf-8");return _d("sha256").update(n).digest("hex")}catch{return null}}};import{spawnSync as Ts}from"child_process";import*as On from"path";import*as Rn from"fs";var Ms=600*1e3;function _r(r,e,t,n,i,o){try{let s=o==="Windows",a={...process.env,DEVECO_SDK_HOME:n};if(s){let c=/\.(bat|cmd)$/i.test(t),d;c?d=[`$env:DEVECO_SDK_HOME='${n.replace(/'/g,"''")}';`,`cd '${r.replace(/'/g,"''")}';`,`& '${t.replace(/'/g,"''")}' ${i}`].join(" "):d=[`$env:DEVECO_SDK_HOME='${n.replace(/'/g,"''")}';`,`cd '${r.replace(/'/g,"''")}';`,`& '${e.replace(/'/g,"''")}' '${t.replace(/'/g,"''")}' ${i}`].join(" ");let u=Ts("powershell.exe",["-Command",d],{cwd:r,env:a,encoding:"utf8",timeout:Ms,windowsHide:!0});return xs(u)}else{let c=[`export DEVECO_SDK_HOME='${n.replace(/'/g,"'\\''")}'`,`cd '${r.replace(/'/g,"'\\''")}'`,`'${e.replace(/'/g,"'\\''")}' '${t.replace(/'/g,"'\\''")}' ${i}`].join(" && "),d=Ts("bash",["-c",c],{cwd:r,env:a,encoding:"utf8",timeout:Ms});return xs(d)}}catch(s){return{success:!1,output:`Build execution exception: ${(s instanceof Error?s:new Error(String(s))).message}`,exitCode:-1}}}function xs(r){let e=r.stdout??"",t=r.stderr??"",n=[e,t].filter(Boolean).join(`
|
|
1236
1235
|
`).trim()||"";if(r.signal)return{success:!1,output:`Build process timeout after 10 minutes. The build may be hanging or taking too long.
|
|
1237
1236
|
Output so far:
|
|
1238
|
-
`+n,exitCode:-1};let i=r.status??-1;return{success:i===0,output:n,exitCode:i}}function
|
|
1239
|
-
`);return{exitCode:s.status??-1,output:d}}function
|
|
1240
|
-
`):"\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=Q.isAbsolute(o)?o:Q.join(n,o);if(!
|
|
1237
|
+
`+n,exitCode:-1};let i=r.status??-1;return{success:i===0,output:n,exitCode:i}}function Ud(r){let e=On.join(On.dirname(r),"tools","hvigor","bin","hvigorw.js");return{node_path:process.execPath??"node",hvigor_path:e,sdk_path:r}}function Bd(r){return!r.node_path||!Rn.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!Rn.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!Rn.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var zd="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";function Rs(r,e){try{let t=Ud(e),n=Bd(t);if(n!=null)return l.info(`Config validation failed: ${n}`),!1;let i=t.node_path,o=t.hvigor_path,s=vs();return _r(r,i,o,e,zd,s).success}catch(t){return l.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawnSync as Os}from"child_process";import*as Wr from"fs";import*as It from"path";function Vd(){let r=process.platform;return r==="win32"?"Windows":r==="darwin"?"Mac":"Linux"}var Ns="install --all --registry https://ohpm.openharmony.cn/ohpm/ --strict_ssl true";function qd(r,e){let t=r.replace(/sdk\/?$/i,"tools"),n=e==="Windows"?"ohpm.bat":"ohpm",i=It.join(t,"ohpm","bin",n);if(Wr.existsSync(i))return i;let o=r.toLowerCase().endsWith("sdk")?It.dirname(r):r;return i=It.join(o,"ohpm","bin",n),Wr.existsSync(i)?i:null}function Yd(r,e,t){let n=t==="Windows",i=e.replace(/'/g,n?"''":"'\\''"),o=r.replace(/'/g,n?"''":"'\\''"),s=n?Os("powershell.exe",["-Command",`cd '${i}'; & '${o}' ${Ns}`],{cwd:e,encoding:"utf8",windowsHide:!0}):Os("bash",["-c",`cd '${i}' && '${o}' ${Ns}`],{cwd:e,encoding:"utf8"}),a=s.stdout??"",c=s.stderr??"",d=[a,c].filter(Boolean).join(`
|
|
1238
|
+
`);return{exitCode:s.status??-1,output:d}}function Gd(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>l.info("[ohpm] %s",e))}function Ls(r,e){try{let t=Vd(),n=qd(e,t);if(!n)return l.error("ohpm \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=Yd(n,r,t);return Gd(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 Hs={UNINITIALIZED:-32099,UNKNOWN:-32e3},Ct=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,Hs.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,Hs.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var et=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(!Ls(e,t))return l.error("[ArktsLspManager] ohpm install failed"),!1;let i=Rs(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 Tn(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:T,method:g.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();l.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?Ct.uninitialized(t):Ct.unknown();this.onMessage({jsonrpc:T,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:T,method:g.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Mn(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new xn(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:T,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:n}}),this.onMessage({jsonrpc:T,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:T,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 Jd=120*1e3,Kd=300*1e3,Xd=180*1e3,Zd=10080*60*1e3,tt=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:Ur.object({files:Ur.array(Ur.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=oe(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>cs(s,Zd,"[ArkTS-Check]")),gs(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;this.manager=new et({sdkPath:Q.join(t,"sdk"),arktsLangServerPath:n,workspaceRoot:j(i),indexLogPath:s,nodeMaxOldSpaceSize:c}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),await new Promise((d,u)=>{this.initResolve=d,this.initReject=u,this.armInitTimer(Kd),this.manager.start([]).catch(b=>{let A=b instanceof Error?b:new Error(String(b));this.failInit(A)})})}resolveProjectAndDeveco(){let e=ke(this.projectPath);if(!e)throw new Error(`Failed to find Harmony project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Te();if(m.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=ts(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=vt(Me(e)),n=Or(e),i=await pe.promises.readFile(e,"utf8"),s=`deveco.apptool.${Q.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((d,u)=>{let b=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},Jd);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};m.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(`
|
|
1239
|
+
`):"\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=Q.isAbsolute(o)?o:Q.join(n,o);if(!pe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!pe.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 is(500);try{let o=await this.checkFile(i);n.push(Qd(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(`
|
|
1241
1240
|
`)),t.length>0&&n.push(t.join(`
|
|
1242
1241
|
`));let i=n.join(`
|
|
1243
|
-
`).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){m.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(
|
|
1242
|
+
`).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){m.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(Xd),m.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{m.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";m.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"){m.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;m.debug(`diagnostics received uri=${t} count=${o}`),n.resolve(Array.isArray(i)?i:[])}resolveDiagnosticWaiter(e){let t=vt(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=Q.join(Kt(),"ArkTSCheck"),n=Q.join(t,"mapping-config.properties"),i=as(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Q.join(t,"lsp-log",String(i),o),a=Q.join(t,"lsp-index",String(i));return pe.mkdirSync(s,{recursive:!0}),pe.mkdirSync(a,{recursive:!0}),{logPath:oe(s),indexPath:oe(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function Qd(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 eu}from"child_process";import*as I from"fs";import*as N from"path";import{z as Br}from"zod";var Fs=60*1e3,tu=30*1e3,nu=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),ru=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=>{m.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=oe(this.projectPath),i=Me(n),o=N.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.3.2"},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,m.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=I.realpathSync(e)}catch{t=e}let n=Me(t),i=os(t),o=await I.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}`))},tu);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=>{m.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){m.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){m.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){m.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}nu.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
|
|
1244
1243
|
\r
|
|
1245
1244
|
`,"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
|
|
1246
1245
|
\r
|
|
1247
|
-
`);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){m.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=
|
|
1246
|
+
`);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){m.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=iu(n),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];m.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 iu(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)),Me(t)}}catch{}return r}function ou(r){let e=N.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function su(r,e){let t=N.join(r,e.name);return e.isDirectory()?e.name===".cxx"||js(t):ou(t)}function js(r){if(!I.existsSync(r))return!1;try{return I.readdirSync(r,{withFileTypes:!0}).some(t=>su(r,t))}catch{}return!1}function $s(r){let t=new Oe(r).getAllModuleInfo(),n=[];for(let i of t){let o=i.srcPath.replace(/^\.\//,""),s=N.join(r,o);js(s)&&n.push(i)}return n}function au(r){let e=[],n=new Oe(r).getAllModuleInfo();for(let i of n){let o=i.srcPath.replace(/^\.\//,""),s=N.join(r,o,".cxx");I.existsSync(s)&&_s(s,e)}return e}function _s(r,e){try{let t=I.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=N.join(r,n.name);n.isDirectory()?_s(i,e):n.name==="compile_commands.json"&&e.push(i)}}catch{}}function cu(r){let e=[];for(let t of r)try{let n=I.readFileSync(t,"utf8"),i=JSON.parse(n);e.push(...i)}catch{}return e}function lu(r,e){let t=N.join(r,...xr.slice(0,-1));I.mkdirSync(t,{recursive:!0});let n=N.join(t,"compile_commands.json");I.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function du(r){let e=au(r);if(e.length>0){let t=cu(e);lu(r,t),m.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else m.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function uu(r){let e=new Set;for(let t of r)if(t.file)try{e.add(I.realpathSync(t.file))}catch{e.add(t.file)}return e}function pu(r,e){try{let t=I.realpathSync(r);if(!e.has(t))return m.info(`[CppCheck] File not covered by compile_commands.json: ${r}`),!1}catch{}return!0}function hu(r,e){if(!I.existsSync(r))return!1;try{let t=I.readFileSync(r,"utf8"),n=JSON.parse(t),i=uu(n);for(let o of e)if(!pu(o,i))return!1;return!0}catch(t){return m.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}function mu(r,e,t){let n=N.join(e,"sdk"),i=process.platform==="win32"?"Windows":process.platform==="darwin"?"Mac":"Linux",o=process.execPath||"node",s=N.join(e,process.platform==="darwin"?"Contents":"","tools"),a=process.platform==="win32"?N.join(s,"hvigor","bin","hvigorw.bat"):N.join(s,"hvigor","bin","hvigorw.js");for(let c of t){let d=["--mode","module","-p",`module=${c.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");m.info(`[CppCheck] Running compileNative for module: ${c.name}`);let u=_r(r,o,a,n,d,i);u.success?m.info(`[CppCheck] compileNative ${c.name} \u6210\u529F`):m.warn(`[CppCheck] compileNative ${c.name} \u5931\u8D25: ${u.output}`)}}function fu(r,e){let t=$s(r);if(t.length===0){m.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}m.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(n=>n.name).join(", ")}`),mu(r,e,t),du(r)}var nt=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=Gt(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:Br.object({files:Br.array(Br.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(`
|
|
1248
1247
|
`):"\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(`
|
|
1249
1248
|
`)}],isError:!0}}return await this.runDiagnosticsForFiles(o,i,t,n)&&this.shutdown().catch(a=>{m.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(`
|
|
1250
1249
|
`),e.join(`
|
|
1251
1250
|
`)].filter(o=>o.trim().length>0).join(`
|
|
1252
|
-
`).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=
|
|
1251
|
+
`).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=oe(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(m.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??Te();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,fu(t,i)}else if(this.client&&this.initializedProjectPath){let i=oe(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let n=Yt(e);return I.existsSync(n)?$s(e).length===0?(m.info("[CppCheck] No cpp modules found, no initialization needed"),!1):hu(n,t)?(m.info("[CppCheck] All files covered, no initialization needed"),!1):(m.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(m.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,m.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=ke(this.projectPath);if(!e)throw new Error(`Failed to find Harmony project from path: ${this.projectPath}`);return this.projectPath=e,oe(e)}startPollingForClangd(e){let t=Yt(e);if(I.existsSync(t)){m.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(n=>{m.error(`[CppCheck] Immediate clangd spawn failed: ${n}`)});return}m.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}I.existsSync(t)&&(this.stopPolling(),m.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(n=>{m.error(`[CppCheck] Clangd spawn from poll failed: ${n}`)}))},ru)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:n}=this.resolveClangdPaths(e);m.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,m.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(m.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??Te();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=ns(t);if(!n)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=Yt(e),o=N.dirname(i);return{clangdPath:n,compileCommandsDir:o}}spawnClangd(e,t,n){let i=eu(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&&m.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{m.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{m.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(!I.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!I.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!Jt(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(I.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){m.warn(`[CppCheck] client.close() failed: ${n}`)}if(t&&!t.killed)try{t.kill()}catch(n){m.warn(`[CppCheck] failed to kill clangd: ${n}`)}}};var Nn=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;constructor(e={}){this.config=e,Lr(e.debug??!1);let t,n=e.projectPath?.trim()??"";n===""||n==="."?t=process.cwd():t=n,this.config.projectPath=ke(t)??void 0,this.server=new gu({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=kr(),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:Vr.object({files:Vr.array(Vr.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))}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(u=>typeof u=="string"):[];if(t.length===0)return{content:[{type:"text",text:"\u6CA1\u6709\u4F20\u5165\u4EFB\u4F55\u6587\u4EF6"}],isError:!0};let{etsFiles:n,cppFiles:i,unsupported:o}=vu(t),s=o.map(u=>`\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B: ${u}\uFF08\u4EC5\u652F\u6301 .ets \u4E0E C/C++ \u6E90/\u5934\u6587\u4EF6\uFF09`),a=[];n.length>0&&this.mergeCheckResult(await this.callArktsCheck(n),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1253
1252
|
`),s.join(`
|
|
1254
1253
|
`)].filter(u=>u.trim().length>0).join(`
|
|
1255
1254
|
`).trim()||"\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"}],isError:c}}async callArktsCheck(e){return!this.arktsCheckTool||!this.arktsCheckTool.isInitialized()?{content:[{type:"text",text:this.arktsCheckTool?.isInitializing()?"ArkTS LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.config.projectPath?"ArkTS LSP \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5C1D\u8BD5\u91CD\u65B0\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570\u6216\u8005\u5728DevEco Studio\u4E2D\u6253\u5F00\u9879\u76EE"}],isError:!0}:this.arktsCheckTool.handleCall({files:e})}async callCppCheck(e){return this.cppCheckTool?this.cppCheckTool.handleCall({files:e}):{content:[{type:"text",text: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"}],isError:!0}}mergeCheckResult(e,t,n){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1256
|
-
`);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,process.env.PROJECT_PATH=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(()=>{}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(()=>{}),this.cppCheckTool=null)}async start(){this.toolRouter.registerToServer(this.server);let e=new
|
|
1257
|
-
`),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 t=[J.join(this.docsDir,e),J.join(this.docsDir,`${e}.md`)];for(let n of t)try{return await ee.promises.readFile(n,"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(".."))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 ee.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await ee.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""}}},
|
|
1255
|
+
`);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,process.env.PROJECT_PATH=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(()=>{}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(()=>{}),this.cppCheckTool=null)}async start(){this.toolRouter.registerToServer(this.server);let e=new yu;if(await this.server.connect(e),m.info("devecocli-mcp-server started"),!this.config.debug){let t=ps();t&&m.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),!this.config.projectPath){let t=await this.getProjectRootFromClient();if(t){let n=ke(t);n?(m.info(`Detected project path from client root: ${n}`),this.setProjectPath(n)):m.warn(`Client root '${t}' is not a Harmony project`)}else m.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.config.projectPath?(await this.initializeArktsCheck(),this.initializeCppCheck()):m.warn("No valid Harmony project path found, LSP tools will be unavailable")}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return m.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return m.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{}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,m.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{m.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{m.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){m.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new nt(e,this.config.devecoPath??null),m.info("CppCheckTool created (lazy initialization)")}async initializeArktsCheck(){let e=this.config.projectPath;if(!e){m.warn("LSP initialization skipped: project path is not configured");return}m.info("Initializing ArkTS LSP..."),this.config.devecoPath=Gt(this.config.devecoPath??""),this.arktsCheckTool=new tt(e,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),await et.handleSyncProject(e,Ln.join(this.config.devecoPath,"sdk"));try{await this.arktsCheckTool.initialize(),m.info("ArkTS LSP initialized successfully")}catch(t){m.error("ArkTS LSP initialization failed:",t),this.arktsCheckTool=null}}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){m.warn("Failed to close MCP server connection:",e)}m.info("devecocli-mcp-server stopped"),us(),ds()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function vu(r){let e=[],t=[],n=[];for(let i of r)Ln.extname(i).toLowerCase()===".ets"?e.push(i):Jt(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function qr(r={}){return new Nn(r)}async function bu(){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 x.new(),o=r,s=e??i.devecoStudioPath,a=qr({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 Ws=new wu("serve").description("Host bundled auxiliary protocol servers");Ws.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await bu()});var Us=Ws;import{Command as Tu,InvalidArgumentError as Jr}from"commander";import{red as Hn,dim as Mu}from"colorette";import*as J from"path";import*as ee from"fs";import{homedir as Su}from"os";import{execa as Pu}from"execa";import{rgPath as Eu}from"@vscode/ripgrep";import Du from"adm-zip";import{fileURLToPath as Iu}from"url";import Cu from"ora";var At=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],kt={"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 Au="deveco-cli",ku="docs",Yr=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=J.join(Su(),".local","share",Au,ku),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"0.3.2"}async getExistingVersion(){try{return(await ee.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=Cu({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=J.dirname(this.docsDir);await ee.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await ee.promises.mkdir(this.docsDir,{recursive:!0}),new Du(t).extractAllTo(this.docsDir,!0),await ee.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=Iu(e),n=J.dirname(t),i=[J.join(n,"..","docs.zip")];for(let o of i)if(ee.existsSync(o))return o;return null}async cleanOldDocs(){try{await ee.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?J.join(this.docsDir,kt[t]):this.docsDir,i=await this.searchFiles(e,n),o=Array.from(i.entries()).sort((a,c)=>c[1]-a[1]).map(([a])=>a);return(await Promise.all(o.map(async a=>{let c=this.parseFilePath(a);if(!c)return null;let d=await this.readMetadata(a);if(!d)return null;let u=await this.readContentPreview(a);return{title:d.title,documentId:c,content:u}}))).filter(a=>a!==null)}async searchFiles(e,t){let n=["--type","md","--json","--no-messages"];for(let o of e)n.push("-e",o);n.push(t);let i=await Pu(Eu,n,{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)}parseSearchResults(e){let t=e.split(`
|
|
1256
|
+
`),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 t=[J.join(this.docsDir,e),J.join(this.docsDir,`${e}.md`)];for(let n of t)try{return await ee.promises.readFile(n,"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(".."))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 ee.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await ee.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""}}},Gr=new Yr;function Bs(...r){return e=>{if(!r.includes(e))throw new Jr(`Allowed values: ${r.join(", ")}`);return e}}function xu(r){let e=parseInt(r,10);if(isNaN(e)||e<=0)throw new Jr("Must be a positive integer");return e}var Ru=Bs("json","default"),Ou=Bs("json","default"),Fn=new Tu("doc").description("Search and read Harmony documentation from local docs directory");Fn.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Nu,"all").option("--format <fmt>","Output format (default, json)",Ru,"default").option("--limit <n>","Max number of results",xu,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error(Hn("Keywords cannot be empty")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await Gr.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Lu(o)}catch(t){console.error(Hn(t.message)),process.exit(1)}});Fn.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error(Hn("Document ID cannot be empty")),process.exit(1));let t=await Gr.readDocument(e);console.log(t)}catch(e){console.error(Hn(e.message)),process.exit(1)}});Fn.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Ou,"default").action(r=>{if(r.format==="json"){let e=At.map(t=>({name:t,title:kt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of At)console.log(` ${e.padEnd(20)} ${Mu(kt[e])}`)});function Nu(r){if(r==="all")return"all";if(!At.includes(r))throw new Jr(`Invalid catalog "${r}". Allowed: all, ${At.join(", ")}`);return r}function Lu(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 zs=Fn;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Hu();W.name("devecocli").description("HarmonyOS application development command line tool").version("0.3.2");W.addCommand(si);W.addCommand(mi);W.addCommand(vi);W.addCommand(Ti);W.addCommand(Ki);W.addCommand(Do);W.addCommand(To);W.addCommand($o);W.addCommand(Go);W.addCommand(Us);W.addCommand(zs);var Kr=process.argv.slice(2);Kr.length>=2&&Kr[Kr.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Fu=new Set(["update"]);W.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==W;)t=t.parent;Fu.has(t.name())||await x.checkVersion()});W.parseAsync(process.argv).catch(r=>{console.error(r),process.exit(1)});
|