@deveco-test/deveco-cli 1.2.0-Test.3 → 1.2.0-Test.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{bootstrap as
|
|
2
|
+
import{bootstrap as bp}from"global-agent";import{program as U}from"commander";import{red as Sp}from"colorette";import{Command as Da}from"commander";import{green as Ci,red as lr,yellow as Di}from"colorette";import F from"fs";import*as W from"path";import Re from"json5";import*as rr from"fs";import*as j from"path";function m(r){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${r}`)}var S=class r{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let n=e.trim();if(!/^\d+$/.test(n))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(n,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
3
|
`)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return r.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,n,i=new Date){if(!t&&!n)return e;let[o,s]=r.resolveTimeBounds(t,n,i),a=e.split(/\r?\n/),c=[],d=!1;for(let u of a){let y=r.extractTimestampFromLogLine(u,i);y&&(d=r.isWithinBounds(y,o,s)),d&&c.push(u)}return c.join(`
|
|
4
|
-
`)}static resolveTimeBounds(e,t,n){let i=e?new Date(n.getTime()-e*1e3):null,o=t?new Date(n.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,n]:o?[null,o]:[null,null]}static isWithinBounds(e,t,n){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=n?Math.floor(n.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let n=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!n)return null;let i=t.getFullYear(),o=Number.parseInt(n[1],10)-1,s=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),c=Number.parseInt(n[4],10),d=Number.parseInt(n[5],10),u=n[6]??"0",y=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),k=new Date(i,o,s,a,c,d,y);return k.getTime()>t.getTime()+1440*60*1e3&&k.setFullYear(i-1),k}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(n=>{let i=n.charCodeAt(0);return i<=r.ASCII_CONTROL_MAX||i===r.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let n=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${n}`),n}static assertCrashFilename(e){if(!/^\w+-.+\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(N.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=N.resolve(N.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=N.normalize(e),i=N.relative(n,t);if(i.split(N.sep)[0]===".."||N.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||N.isAbsolute(e)}static isPathContained(e,t){let n=N.resolve(t,e),i=N.relative(t,n);return r.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(N.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let n=r.isPathContained(e,t);if(!n.contained)return n;let i;try{i=nr.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=N.resolve(i,e),s;try{s=nr.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return r.isPathContained(s,i)}};var Me=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=W.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=W.join(e,"build-profile.json5");if(!H.existsSync(t))return null;try{let n=H.readFileSync(t,"utf-8"),i=Te.parse(n);return i.app?i:null}catch(n){return console.error(`Error parsing ${t}:`,n),null}}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let n=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=W.join(n,"src","main","module.json5");if(!H.existsSync(i))return"entry";try{let o=H.readFileSync(i,"utf-8");return Te.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let n=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=W.join(n,"build-profile.json5");if(!H.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=H.readFileSync(i,"utf-8");return Te.parse(o)}getBundleName(){let e=W.join(this.rootDir,"AppScope","app.json5");if(H.existsSync(e))try{let t=H.readFileSync(e,"utf-8"),n=Te.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=S.resolvePathWithinRoot(this.rootDir,n.srcPath),o=W.join(i,"src","main","module.json5");if(!H.existsSync(o))return"EntryAbility";try{let s=H.readFileSync(o,"utf-8"),c=Te.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let d=c.find(u=>u.name==="EntryAbility");return d?d.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(n=>n.name===e)){let n=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${n}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let n=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=W.join(n,"oh-package.json5");if(!H.existsSync(i))return[];let o=[];try{let s=H.readFileSync(i,"utf-8"),c=Te.parse(s)?.dependencies||{};for(let d of Object.values(c)){if(typeof d!="string")continue;let u=d;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let k=W.join(t.srcPath,u),_=S.resolvePathWithinRoot(this.rootDir,k),J=this.profile.modules.find(tr=>W.resolve(this.rootDir,tr.srcPath)===_);J&&o.push(J.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],n=[],i=new Set;for(n.push(e),i.add(e);n.length>0;){let o=n.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(n.push(c),i.add(c))}return t}findArtifactPath(e,t,n,i="default"){this.validateProduct(i);let o=this.profile.modules.find(J=>J.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(!H.existsSync(d))throw new Error(`Build metadata not found for module '${e}' at ${d}. Build the project first.`);let{packageName:u,isSigned:y}=this.parseOutputMetadata(d,c),k=u;if(!y){let J=this.getSignedHapName(u,o.srcPath,i,t);J&&(k=J)}if(!n&&!k.endsWith("-signed.hap"))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let _=this.buildOutputPath(o.srcPath,i,["outputs",t,k]);if(!H.existsSync(_))throw new Error(`Generated package file not found in ${_}.`);return _}getSignedHapName(e,t,n,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,n,["outputs",i,o]);return H.existsSync(s)?o:null}buildOutputPath(e,t,n){let i=S.resolvePathWithinRoot(this.rootDir,e),o=W.resolve(i,"build",t,...n);return S.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let n=H.readFileSync(e,"utf-8"),i=Te.parse(n),o,s=!1;if(Array.isArray(i)){let a=i[0];a&&(o=a[t],s=a.isSigned===!0)}else i&&typeof i=="object"&&(o=i[t],s=i.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(o),{packageName:o,isSigned:s}}validatePackageName(e){let t=W.basename(e);if(t!==e)throw new Error(`Invalid traversal name: '${e}'. It must contain path characters.`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name '${t}'.It must be a .hap or .hsp file.`)}};import{execFileSync as rr}from"child_process";import R,{existsSync as fi}from"fs";import*as E from"path";import*as z from"os";import la from"regedit";import{join as mi}from"path";import{red as da}from"colorette";var gi="https://developer.huawei.com/consumer/cn/download/",yi="6.1.0",_t=r=>new Promise((e,t)=>{la.list(r,(n,i)=>{n?t(n):e(i)})}),O=class r{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){r._verifiedPaths.has(e)||(r.verifySignature(e),r._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return r.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return r.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return r.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return r.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&r.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,n,i,o,s,a,c,d){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=n,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=d}static enforceStudioMinVersion(e){let t=r.parseProductInfoVersion(e);if(t===void 0)throw new Error(`Failed to determine DevEco Studio version at ${e}`);r.assertMinVersion(e,t)}static async checkVersion(){let e=await r.findDevEcoStudio();r.enforceStudioMinVersion(e)}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 m(`[ToolProvider] findDevEcoStudio: cache hit -> ${r._cachedInstallRoot}`),r._cachedInstallRoot;let e=z.platform(),t=e==="win32"?await r.collectCandidatesWindows():e==="darwin"?r.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return r._cachedInstallRoot=r.pickLatestByProductInfo(t),r._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],n=(i,o)=>{if(!r.isExistingDirectory(i))return;let s=E.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),m(`[ToolProvider] Found via ${o}: ${i}`))};if(await r.addFromUninstallKey(n),await r.addFromHuaweiStudioKeys(n),r.addFromDefaultWindowsPath(n),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of r.UNINSTALL_REGISTRY_PARENTS)try{let o=((await _t([t]))[t]?.keys??[]).filter(r.isDevEcoStudioUninstallSubkey);if(o.length===0)continue;let s=o.map(c=>`${t}\\${c}`),a=await _t(s);for(let c of s){let d=a[c]?.values?.InstallLocation?.value;e(d,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,n){try{let o=(await _t([t]))[t]?.keys??[];if(o.length===0)return;let s=o.map(c=>`${t}\\${c}`),a=await _t(s);for(let c of s){let d=a[c]?.values?.[""]?.value;e(d,`${n} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of r.HUAWEI_STUDIO_REGISTRY_KEYS){let n=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await r.addFromHuaweiStudioRegistryKey(e,t,n)}}static addFromDefaultWindowsPath(e){let t=E.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=z.homedir(),t=[E.join(e,"Applications"),"/Applications"],n=[],i=new Set;for(let o of t){if(!R.existsSync(o))continue;let s;try{s=R.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let d=E.join(o,a);r.isExistingDirectory(d)&&(i.has(d)||(i.add(d),n.push(d),m(`[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 z.platform()==="darwin"?E.join(e,"Contents","product-info.json"):E.join(e,"product-info.json")}static macInfoPlistPath(e){return E.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!R.existsSync(e)){m(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let n=rr("defaults",["read",e,t],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(n.length>0&&n!=="(null)")return n}catch{m(`[ToolProvider] defaults read failed for ${e} key ${t}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(n=>/^\d+$/.test(n))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let n=r.compactPrefixFromShortVersion(e),i=r.extractCompactBuildCode(t);if(n===void 0||i===void 0)return;if(!i.startsWith(n)){m(`[ToolProvider] CFBundleVersion suffix ${i} does not match short-version prefix ${n} (${e})`);return}let o=i.slice(n.length);if(!(o.length===0||!/^\d+$/.test(o)))return o}static readMacFourthSegmentFromPlist(e,t){let n=r.readMacInfoPlistKey(e,"CFBundleVersion");if(n!==void 0){let s=r.extractFourthSegmentMatchingShortVersion(t,n);if(s!==void 0)return s}let i=r.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(i===void 0)return;let o=i.match(/DS-[\d.]+/);if(o!==null)return r.extractFourthSegmentMatchingShortVersion(t,o[0])}static parseMacInfoPlistVersion(e){let t=r.macInfoPlistPath(e),n=r.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(n!==void 0){let i=r.readMacFourthSegmentFromPlist(t,n);return i!==void 0?`${n}.${i}`:n}return r.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(z.platform()==="darwin"){let n=r.parseMacInfoPlistVersion(e);if(n!==void 0)return n}let t=r.productInfoPath(e);if(!R.existsSync(t)){m(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(R.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){m(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch{m(`[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 m(`[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}),m(`[ToolProvider] ${n} => version ${i}`)):m(`[ToolProvider] Skipping ${n}: could not read version (Info.plist / product-info.json).`)}if(t.length===0){let n=e.join(`
|
|
4
|
+
`)}static resolveTimeBounds(e,t,n){let i=e?new Date(n.getTime()-e*1e3):null,o=t?new Date(n.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,n]:o?[null,o]:[null,null]}static isWithinBounds(e,t,n){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=n?Math.floor(n.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let n=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!n)return null;let i=t.getFullYear(),o=Number.parseInt(n[1],10)-1,s=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),c=Number.parseInt(n[4],10),d=Number.parseInt(n[5],10),u=n[6]??"0",y=Number.parseInt(u.padEnd(3,"0").slice(0,3),10),k=new Date(i,o,s,a,c,d,y);return k.getTime()>t.getTime()+1440*60*1e3&&k.setFullYear(i-1),k}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(n=>{let i=n.charCodeAt(0);return i<=r.ASCII_CONTROL_MAX||i===r.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let n=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${n}`),n}static assertCrashFilename(e){if(!/^\w+-.+\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(j.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let n=j.resolve(j.normalize(e),t);return r.ensurePathWithinRoot(e,n)}static ensurePathWithinRoot(e,t){let n=j.normalize(e),i=j.relative(n,t);if(i.split(j.sep)[0]===".."||j.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||j.isAbsolute(e)}static isPathContained(e,t){let n=j.resolve(t,e),i=j.relative(t,n);return r.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){if(j.isAbsolute(e))return{contained:!1,reason:`Absolute path is not allowed: ${e}`};let n=r.isPathContained(e,t);if(!n.contained)return n;let i;try{i=rr.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=j.resolve(i,e),s;try{s=rr.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return r.isPathContained(s,i)}};var xe=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=W.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=W.join(e,"build-profile.json5");if(!F.existsSync(t))return null;try{let n=F.readFileSync(t,"utf-8"),i=Re.parse(n);return i.app?i:null}catch(n){return console.error(`Error parsing ${t}:`,n),null}}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let n=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=W.join(n,"src","main","module.json5");if(!F.existsSync(i))return"entry";try{let o=F.readFileSync(i,"utf-8");return Re.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let n=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=W.join(n,"build-profile.json5");if(!F.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);let o=F.readFileSync(i,"utf-8");return Re.parse(o)}getBundleName(){let e=W.join(this.rootDir,"AppScope","app.json5");if(F.existsSync(e))try{let t=F.readFileSync(e,"utf-8"),n=Re.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=S.resolvePathWithinRoot(this.rootDir,n.srcPath),o=W.join(i,"src","main","module.json5");if(!F.existsSync(o))return"EntryAbility";try{let s=F.readFileSync(o,"utf-8"),c=Re.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let d=c.find(u=>u.name==="EntryAbility");return d?d.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(n=>n.name===e)){let n=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${n}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let n=S.resolvePathWithinRoot(this.rootDir,t.srcPath),i=W.join(n,"oh-package.json5");if(!F.existsSync(i))return[];let o=[];try{let s=F.readFileSync(i,"utf-8"),c=Re.parse(s)?.dependencies||{};for(let d of Object.values(c)){if(typeof d!="string")continue;let u=d;if(!(u.startsWith("file:")||u.startsWith(".")||u.startsWith("..")))continue;u.startsWith("file:")&&(u=u.substring(5));let k=W.join(t.srcPath,u),H=S.resolvePathWithinRoot(this.rootDir,k),J=this.profile.modules.find(Te=>W.resolve(this.rootDir,Te.srcPath)===H);J&&o.push(J.name)}}catch{}return o}collectNonHarDependentModuleList(e){let t=[],n=[],i=new Set;for(n.push(e),i.add(e);n.length>0;){let o=n.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(n.push(c),i.add(c))}return t}findArtifactPath(e,t,n,i="default"){this.validateProduct(i);let o=this.profile.modules.find(J=>J.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(!F.existsSync(d))throw new Error(`Build metadata not found for module '${e}' at ${d}. Build the project first.`);let{packageName:u,isSigned:y}=this.parseOutputMetadata(d,c),k=u;if(!y){let J=this.getSignedHapName(u,o.srcPath,i,t);J&&(k=J)}if(!n&&!k.endsWith("-signed.hap"))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let H=this.buildOutputPath(o.srcPath,i,["outputs",t,k]);if(!F.existsSync(H))throw new Error(`Generated package file not found in ${H}.`);return H}getSignedHapName(e,t,n,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,n,["outputs",i,o]);return F.existsSync(s)?o:null}buildOutputPath(e,t,n){let i=S.resolvePathWithinRoot(this.rootDir,e),o=W.resolve(i,"build",t,...n);return S.ensurePathWithinRoot(this.rootDir,o)}parseOutputMetadata(e,t){let n=F.readFileSync(e,"utf-8"),i=Re.parse(n),o,s=!1;if(Array.isArray(i)){let a=i[0];a&&(o=a[t],s=a.isSigned===!0)}else i&&typeof i=="object"&&(o=i[t],s=i.isSigned===!0);if(!o)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);return this.validatePackageName(o),{packageName:o,isSigned:s}}validatePackageName(e){let t=W.basename(e);if(t!==e)throw new Error(`Invalid traversal name: '${e}'. It must contain path characters.`);if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new Error(`Invalid package name '${t}'.It must be a .hap or .hsp file.`)}};import{execFileSync as ir}from"child_process";import R,{existsSync as mi}from"fs";import*as E from"path";import*as z from"os";import pa from"regedit";import{join as gi}from"path";import{red as ha}from"colorette";var yi="https://developer.huawei.com/consumer/cn/download/",vi="6.1.0",Ut=r=>new Promise((e,t)=>{pa.list(r,(n,i)=>{n?t(n):e(i)})}),O=class r{_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_emulatorLauncherPath;static _verifiedPaths=new Set;static _powerShellPath;static verifyAndCache(e){r._verifiedPaths.has(e)||(r.verifySignature(e),r._verifiedPaths.add(e))}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return r.verifyAndCache(this._nodePath),this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get javaPath(){return r.verifyAndCache(this._javaPath),this._javaPath}get sdkPath(){return this._sdkPath}get hdcPath(){return r.verifyAndCache(this._hdcPath),this._hdcPath}get emulatorPath(){return r.verifyAndCache(this._emulatorPath),this._emulatorPath}get emulatorLauncherPath(){return this._emulatorLauncherPath&&r.verifyAndCache(this._emulatorLauncherPath),this._emulatorLauncherPath}constructor(e,t,n,i,o,s,a,c,d){this._devecoStudioPath=e,this._nodePath=t,this._ohpmJsPath=n,this._hvigorJsPath=i,this._javaPath=o,this._sdkPath=s,this._hdcPath=a,this._emulatorPath=c,this._emulatorLauncherPath=d}static enforceStudioMinVersion(e){let t=r.parseProductInfoVersion(e);if(t===void 0)throw new Error(`Failed to determine DevEco Studio version at ${e}`);r.assertMinVersion(e,t)}static async checkVersion(){let e=await r.findDevEcoStudio();r.enforceStudioMinVersion(e)}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 m(`[ToolProvider] findDevEcoStudio: cache hit -> ${r._cachedInstallRoot}`),r._cachedInstallRoot;let e=z.platform(),t=e==="win32"?await r.collectCandidatesWindows():e==="darwin"?r.collectCandidatesMac():(()=>{throw new Error("Linux is not fully supported yet for automatic DevEco Studio detection.")})();return r._cachedInstallRoot=r.pickLatestByProductInfo(t),r._cachedInstallRoot}static async collectCandidatesWindows(){let e=new Set,t=[],n=(i,o)=>{if(!r.isExistingDirectory(i))return;let s=E.normalize(i).toLowerCase();e.has(s)||(e.add(s),t.push(i),m(`[ToolProvider] Found via ${o}: ${i}`))};if(await r.addFromUninstallKey(n),await r.addFromHuaweiStudioKeys(n),r.addFromDefaultWindowsPath(n),t.length===0)throw new Error("DevEco Studio installation not found in registry or default locations.");return t}static UNINSTALL_REGISTRY_PARENTS=["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"];static HUAWEI_STUDIO_REGISTRY_KEYS=["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"];static isDevEcoStudioUninstallSubkey(e){return e.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio")}static async addFromUninstallKey(e){for(let t of r.UNINSTALL_REGISTRY_PARENTS)try{let o=((await Ut([t]))[t]?.keys??[]).filter(r.isDevEcoStudioUninstallSubkey);if(o.length===0)continue;let s=o.map(c=>`${t}\\${c}`),a=await Ut(s);for(let c of s){let d=a[c]?.values?.InstallLocation?.value;e(d,`Uninstall registry key (${c})`)}}catch{}}static async addFromHuaweiStudioRegistryKey(e,t,n){try{let o=(await Ut([t]))[t]?.keys??[];if(o.length===0)return;let s=o.map(c=>`${t}\\${c}`),a=await Ut(s);for(let c of s){let d=a[c]?.values?.[""]?.value;e(d,`${n} subkey ${c}`)}}catch{}}static async addFromHuaweiStudioKeys(e){for(let t of r.HUAWEI_STUDIO_REGISTRY_KEYS){let n=t.includes("WOW6432Node")?"Huawei DevEco Studio (WOW6432Node)":"Huawei DevEco Studio";await r.addFromHuaweiStudioRegistryKey(e,t,n)}}static addFromDefaultWindowsPath(e){let t=E.join("C:","Program Files","Huawei","DevEco Studio");e(t,"default installation path")}static collectCandidatesMac(){let e=z.homedir(),t=[E.join(e,"Applications"),"/Applications"],n=[],i=new Set;for(let o of t){if(!R.existsSync(o))continue;let s;try{s=R.readdirSync(o)}catch{continue}for(let a of s){if(!a.endsWith(".app")||!a.toLowerCase().includes("deveco"))continue;let d=E.join(o,a);r.isExistingDirectory(d)&&(i.has(d)||(i.add(d),n.push(d),m(`[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 z.platform()==="darwin"?E.join(e,"Contents","product-info.json"):E.join(e,"product-info.json")}static macInfoPlistPath(e){return E.join(e,"Contents","Info.plist")}static readMacInfoPlistKey(e,t){if(!R.existsSync(e)){m(`[ToolProvider] Info.plist not found at: ${e}`);return}try{let n=ir("defaults",["read",e,t],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5e3}).trim();if(n.length>0&&n!=="(null)")return n}catch{m(`[ToolProvider] defaults read failed for ${e} key ${t}`)}}static extractCompactBuildCode(e){let t=e.split(".").at(-1);if(t!==void 0&&/^\d+$/.test(t))return t}static compactPrefixFromShortVersion(e){let t=e.split(".").slice(0,3);if(!(t.length<3||!t.every(n=>/^\d+$/.test(n))))return t.join("")}static extractFourthSegmentMatchingShortVersion(e,t){let n=r.compactPrefixFromShortVersion(e),i=r.extractCompactBuildCode(t);if(n===void 0||i===void 0)return;if(!i.startsWith(n)){m(`[ToolProvider] CFBundleVersion suffix ${i} does not match short-version prefix ${n} (${e})`);return}let o=i.slice(n.length);if(!(o.length===0||!/^\d+$/.test(o)))return o}static readMacFourthSegmentFromPlist(e,t){let n=r.readMacInfoPlistKey(e,"CFBundleVersion");if(n!==void 0){let s=r.extractFourthSegmentMatchingShortVersion(t,n);if(s!==void 0)return s}let i=r.readMacInfoPlistKey(e,"CFBundleGetInfoString");if(i===void 0)return;let o=i.match(/DS-[\d.]+/);if(o!==null)return r.extractFourthSegmentMatchingShortVersion(t,o[0])}static parseMacInfoPlistVersion(e){let t=r.macInfoPlistPath(e),n=r.readMacInfoPlistKey(t,"CFBundleShortVersionString");if(n!==void 0){let i=r.readMacFourthSegmentFromPlist(t,n);return i!==void 0?`${n}.${i}`:n}return r.readMacInfoPlistKey(t,"CFBundleVersion")}static parseProductInfoVersion(e){if(z.platform()==="darwin"){let n=r.parseMacInfoPlistVersion(e);if(n!==void 0)return n}let t=r.productInfoPath(e);if(!R.existsSync(t)){m(`[ToolProvider] product-info.json not found at: ${t}`);return}try{let i=JSON.parse(R.readFileSync(t,"utf-8"))?.version;if(typeof i!="string"||i.trim()===""){m(`[ToolProvider] product-info.json at ${t} has no valid "version" field`);return}return i.trim()}catch{m(`[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 m(`[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}),m(`[ToolProvider] ${n} => version ${i}`)):m(`[ToolProvider] Skipping ${n}: could not read version (Info.plist / product-info.json).`)}if(t.length===0){let n=e.join(`
|
|
5
5
|
`),i=z.platform()==="darwin"?"Contents/Info.plist (CFBundleShortVersionString / CFBundleVersion) and Contents/product-info.json":"product-info.json";throw new Error(`Failed to determine DevEco Studio version from ${i}.
|
|
6
6
|
Searched locations:
|
|
7
7
|
${n}
|
|
8
8
|
Please reinstall DevEco Studio or download the latest version from:
|
|
9
|
-
`+
|
|
10
|
-
`+
|
|
9
|
+
`+yi)}return t.reduce((n,i)=>r.compareVersion(i.version,n.version)>0?i:n)}static assertMinVersion(e,t){r.compareVersion(t,vi)>=0||(m(`[ToolProvider] Selected DevEco Studio ${t} at ${e} \u2014 below minimum`),console.error(ha(`Error: The detected DevEco Studio version is ${t}, which is below the minimum required version ${vi}. Upgrade to the latest version before using deveco-cli:`)+`
|
|
10
|
+
`+yi),process.exit(1))}static isExistingDirectory(e){return!!e&&R.existsSync(e)&&R.statSync(e).isDirectory()}static resolveWindowsTools(e){let t=E.join(e,"tools");return{nodePath:E.join(t,"node","node.exe"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"jbr","bin","java.exe"),sdkPath:E.join(e,"sdk")}}static resolveMacTools(e){let t=E.join(e,"Contents","tools");return{nodePath:E.join(t,"node","bin","node"),ohpmJsPath:E.join(t,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(t,"hvigor","bin","hvigorw.js"),javaPath:E.join(e,"Contents","jbr","Contents","Home","bin","java"),sdkPath:E.join(e,"Contents","sdk")}}static resolveTools(e){let t=z.platform(),n=t==="win32"?r.resolveWindowsTools(e):t==="darwin"?r.resolveMacTools(e):(()=>{throw new Error("Linux is not fully supported yet.")})();r.verifyTools(n.nodePath,n.ohpmJsPath,n.hvigorJsPath,n.javaPath);let i=r.resolveHdcPath(n.sdkPath,t),o=r.resolveEmulatorPath(e,t);return{...n,hdcPath:i,emulatorPath:o}}static resolveHdcPath(e,t){let n=t==="win32"?".exe":"",i=[E.join(e,"default","openharmony","toolchains",`hdc${n}`),E.join(e,"toolchains",`hdc${n}`)];for(let o of i)if(R.existsSync(o))return o;throw new Error(`hdc executable not found. Searched in:
|
|
11
11
|
${i.join(`
|
|
12
|
-
`)}`)}static resolveEmulatorPath(e,t){let n;if(t==="win32")n=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!R.existsSync(n))throw new Error(`Emulator executable not found at: ${n}`);return n}static verifyTools(e,t,n,i){if(!R.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!R.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!R.existsSync(n))throw new Error(`hvigor js file not found at: ${n}`);if(!R.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=z.platform(),n;if(t==="win32")n=mi(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=mi(e,"Contents","tools","emulator","Emulator");else return;return fi(n)?n:void 0}static isValidApiLevel(e,t){let n=t??23;return Number.isInteger(e)&&e>=17&&e<=n}static parseApiLevelFromFile(e){if(R.existsSync(e))try{let t=R.readFileSync(e,"utf-8"),n=JSON.parse(t),i=n?.apiVersion??n?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return r.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let n of t){let i=r.parseApiLevelFromFile(n);if(i!==void 0)return i}}getMaxApiLevel(){let e=r.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=r.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(r._powerShellPath)return r._powerShellPath;if(z.platform()!=="win32")return r._powerShellPath="",r._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return fi(e)?(m(`[ToolProvider] Found PowerShell at: ${e}`),r._powerShellPath=e,e):(r._powerShellPath="",r._powerShellPath)}static verifySignature(e){if(!R.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=z.platform();if(r.isExecutableFile(e,t)){if(t==="win32"){if(!r.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!r.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return R.accessSync(e,R.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=R.mkdtempSync(E.join(z.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return R.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=r.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:n,scriptPath:i}=r.createSignatureScript();try{let o=rr(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 m(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{R.rmSync(n,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return rr("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as ua}from"execa";import*as Wt from"path";var Re=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Wt.dirname(e.javaPath)}${Wt.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async sync(e,t){let n=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(n)}async buildProduct(e,t){let n=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(n)}async buildModules(e,t,n,i){let o=[...Array.from(i),"--mode","module","-p",`module=${n.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async runHvigor(e){let t=this.toolProvider.nodePath,n=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${n.join(" ")}`),await ua(t,n,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as pa}from"execa";var We=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"];m(`Executing: ${e} ${t.join(" ")}`),await pa(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as ha}from"fs/promises";import{dirname as fa,resolve as ma}from"path";import{execa as ga}from"execa";import{lock as ir,check as Kp}from"proper-lockfile";function or(r){return ma(r,".hvigor",".build-lock")}function ya(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function vi(r){let e=fa(or(r));if(await ha(e,{recursive:!0}),process.platform==="win32")try{await ga("attrib",["+h",e])}catch{}}async function va(r,e){let t=new AbortController,n=ya(e);await vi(r);let i={lockfilePath:or(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await ir(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 ir(r,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function ut(r,e,t){let{release:n,signal:i}=await va(r,t);try{return await e(i)}finally{await n()}}async function wi(r,e){let t=new AbortController;await vi(r);let n={lockfilePath:or(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await ir(r,{...n,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as Se from"fs";import*as xe from"path";import wa from"json5";var sr={HTTP_TIMEOUT_MS:2e4},Ut={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 ar="https://matrix.openharmony.cn",Q={TAGS_API_URL:`${ar}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${ar}/api/registry/skill/skills`,SKILL_API_BASE:`${ar}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},ee={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as pe}from"os";import q from"path";var se="deveco-mcp";var be={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:q.join(pe(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:q.join(process.platform==="win32"?q.join(process.env.APPDATA??q.join(pe(),"AppData","Roaming"),"Trae CN","User"):q.join(pe(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:q.join(pe(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:q.join(pe(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:q.join(process.platform==="win32"?q.join(process.env.APPDATA??q.join(pe(),"AppData","Roaming"),"Qoder","SharedClientCache"):q.join(pe(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:q.join(pe(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:q.join(pe(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Si(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function bi(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function Pi(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function Bt(r,e){return r.format==="opencode"?Si(e):r.format==="claude-code"||r.format==="codex"?bi(e):Pi(e)}var te={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var ba=1e3;function zt(r){m(`[ProjectCheck] Checking sync required at project root: ${r}`);let e=xe.join(r,te.SYNC_OUTPUT_PATH);if(!Se.existsSync(e)){let d={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${d.reason}`),d}let t=Se.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let n=Sa(r);if(n===null){let d={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${d.reason}`),d}let i=xe.join(r,te.OH_PACKAGE_JSON5),o=Vt(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=xe.join(r,te.BUILD_PROFILE_JSON5),a=Vt(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let d of n){let u=xe.join(r,d.srcPath,te.OH_PACKAGE_JSON5),y=Vt(u,t,d.name);if(y.required)return m(`[ProjectCheck] Module '${d.name}' check: ${y.reason}`),y;let k=xe.join(r,d.srcPath,te.BUILD_PROFILE_JSON5),_=Vt(k,t,d.name);if(_.required)return m(`[ProjectCheck] Module '${d.name}' build-profile check: ${_.reason}`),_}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function Vt(r,e,t){if(!Se.existsSync(r))return{required:!1,reason:`${t}: source not found, skip`};let n=Se.statSync(r).mtimeMs;return n-e>ba?{required:!0,reason:`${t}: source mtime (${new Date(n).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Sa(r){let e=xe.join(r,te.BUILD_PROFILE_JSON5);try{let t=Se.readFileSync(e,"utf-8");if(!t.trim())return null;let n=wa.parse(t);if(typeof n!="object"||n===null)return null;let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Ea(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode&&!r.profile.app.buildModeSet.some(n=>n.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function Ca(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 lr(r,e){let t=new Set;for(let n of e){let i=n.indexOf("@"),o=i!==-1?n.substring(0,i):n,s=r.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function pt(r,e){let t=e,n=`${r} failed`;console.error(cr(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 dr(r,e,t,n,i,o){if(zt(o).required){console.log(`
|
|
13
|
-
[1/3] Running ohpm install...`);try{await r.installAll()}catch(a){
|
|
14
|
-
[2/3] Running hvigor sync...`);try{await e.sync(t,n)}catch(a){
|
|
12
|
+
`)}`)}static resolveEmulatorPath(e,t){let n;if(t==="win32")n=E.join(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=E.join(e,"Contents","tools","emulator","Emulator");else throw new Error("Linux is not fully supported yet");if(!R.existsSync(n))throw new Error(`Emulator executable not found at: ${n}`);return n}static verifyTools(e,t,n,i){if(!R.existsSync(e))throw new Error(`Node executable not found at: ${e}`);if(!R.existsSync(t))throw new Error(`ohpm js file not found at: ${t}`);if(!R.existsSync(n))throw new Error(`hvigor js file not found at: ${n}`);if(!R.existsSync(i))throw new Error(`java executable not found at: ${i}`)}static getEmulatorExe(e){let t=z.platform(),n;if(t==="win32")n=gi(e,"tools","emulator","Emulator.exe");else if(t==="darwin")n=gi(e,"Contents","tools","emulator","Emulator");else return;return mi(n)?n:void 0}static isValidApiLevel(e,t){let n=t??23;return Number.isInteger(e)&&e>=17&&e<=n}static parseApiLevelFromFile(e){if(R.existsSync(e))try{let t=R.readFileSync(e,"utf-8"),n=JSON.parse(t),i=n?.apiVersion??n?.data?.apiVersion;if(typeof i!="string"&&typeof i!="number")return;let o=Number(i);return Number.isInteger(o)&&o>=17?o:void 0}catch{return}}static detectFromSdkPkg(e){let t=E.join(e,"default","sdk-pkg.json");return r.parseApiLevelFromFile(t)}static detectFromOhUniPackage(e){let t=[E.join(e,"default","openharmony","toolchains","oh-uni-package.json"),E.join(e,"default","openharmony","native","oh-uni-package.json"),E.join(e,"default","openharmony","previewer","oh-uni-package.json")];for(let n of t){let i=r.parseApiLevelFromFile(n);if(i!==void 0)return i}}getMaxApiLevel(){let e=r.detectFromSdkPkg(this.sdkPath);if(e!==void 0)return e;let t=r.detectFromOhUniPackage(this.sdkPath);return t!==void 0?t:23}detectApiLevel(){return this.getMaxApiLevel()}static findPowerShellPath(){if(r._powerShellPath)return r._powerShellPath;if(z.platform()!=="win32")return r._powerShellPath="",r._powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return mi(e)?(m(`[ToolProvider] Found PowerShell at: ${e}`),r._powerShellPath=e,e):(r._powerShellPath="",r._powerShellPath)}static verifySignature(e){if(!R.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=z.platform();if(r.isExecutableFile(e,t)){if(t==="win32"){if(!r.verifyWindowsSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}else if(t==="darwin"&&!r.verifyMacSignature(e).signed)throw new Error(`The executable is not digitally signed: ${e}`)}}static isExecutableFile(e,t){if(t==="win32")return E.extname(e).toLowerCase()===".exe";if(t==="darwin")try{return R.accessSync(e,R.constants.X_OK),!0}catch{return!1}return!1}static createSignatureScript(){let e=R.mkdtempSync(E.join(z.tmpdir(),"deveco-verify-")),t=E.join(e,"Verify-Signature.ps1");return R.writeFileSync(t,"$env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object { $_ -notmatch 'windowsapps' }) -join ';'; Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf-8"),{tmpDir:e,scriptPath:t}}static verifyWindowsSignature(e){let t=r.findPowerShellPath();if(!t)throw new Error("PowerShell application not found");let{tmpDir:n,scriptPath:i}=r.createSignatureScript();try{let o=ir(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 m(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!0}}finally{try{R.rmSync(n,{recursive:!0,force:!0})}catch{}}}static verifyMacSignature(e){try{return ir("codesign",["-v",e],{encoding:"utf-8",timeout:5e3}),{signed:!0}}catch{return{signed:!1}}}};import{execa as fa}from"execa";import*as Bt from"path";var Oe=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${Bt.dirname(e.javaPath)}${Bt.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];m(`Executing: ${t} ${n.join(" ")}`),await fa(t,n,{cwd:this.projectRoot,env:this.env,stdout:"inherit",stderr:"inherit"})}};import{execa as ma}from"execa";var Be=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"];m(`Executing: ${e} ${t.join(" ")}`),await ma(e,t,{cwd:this.projectRoot,stdout:"inherit",stderr:"inherit"})}};import{mkdir as ga}from"fs/promises";import{dirname as ya,resolve as va}from"path";import{execa as wa}from"execa";import{lock as or,check as Qp}from"proper-lockfile";function sr(r){return va(r,".hvigor",".build-lock")}function ba(r){let e=!1;return()=>{e||(e=!0,r?.())}}async function wi(r){let e=ya(sr(r));if(await ga(e,{recursive:!0}),process.platform==="win32")try{await wa("attrib",["+h",e])}catch{}}async function Sa(r,e){let t=new AbortController,n=ba(e);await wi(r);let i={lockfilePath:sr(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await or(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 or(r,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function ht(r,e,t){let{release:n,signal:i}=await Sa(r,t);try{return await e(i)}finally{await n()}}async function bi(r,e){let t=new AbortController;await wi(r);let n={lockfilePath:sr(r),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await or(r,{...n,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as Se from"fs";import*as Le from"path";import Pa from"json5";var ar={HTTP_TIMEOUT_MS:2e4},Vt={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",Q={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"},ee={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as pe}from"os";import q from"path";var se="deveco-mcp";var be={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:q.join(pe(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:q.join(process.platform==="win32"?q.join(process.env.APPDATA??q.join(pe(),"AppData","Roaming"),"Trae CN","User"):q.join(pe(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:q.join(pe(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:q.join(pe(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:q.join(process.platform==="win32"?q.join(process.env.APPDATA??q.join(pe(),"AppData","Roaming"),"Qoder","SharedClientCache"):q.join(pe(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:q.join(pe(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:q.join(pe(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Pi(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function Si(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"."},enabled:!0}}function Ei(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function zt(r,e){return r.format==="opencode"?Pi(e):r.format==="claude-code"||r.format==="codex"?Si(e):Ei(e)}var te={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Ea=1e3;function Yt(r){m(`[ProjectCheck] Checking sync required at project root: ${r}`);let e=Le.join(r,te.SYNC_OUTPUT_PATH);if(!Se.existsSync(e)){let d={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${d.reason}`),d}let t=Se.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let n=Ca(r);if(n===null){let d={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${d.reason}`),d}let i=Le.join(r,te.OH_PACKAGE_JSON5),o=qt(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=Le.join(r,te.BUILD_PROFILE_JSON5),a=qt(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let d of n){let u=Le.join(r,d.srcPath,te.OH_PACKAGE_JSON5),y=qt(u,t,d.name);if(y.required)return m(`[ProjectCheck] Module '${d.name}' check: ${y.reason}`),y;let k=Le.join(r,d.srcPath,te.BUILD_PROFILE_JSON5),H=qt(k,t,d.name);if(H.required)return m(`[ProjectCheck] Module '${d.name}' build-profile check: ${H.reason}`),H}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function qt(r,e,t){if(!Se.existsSync(r))return{required:!1,reason:`${t}: source not found, skip`};let n=Se.statSync(r).mtimeMs;return n-e>Ea?{required:!0,reason:`${t}: source mtime (${new Date(n).toISOString()}) is newer than sync baseline (${new Date(e).toISOString()})`}:{required:!1,reason:`${t}: up-to-date`}}function Ca(r){let e=Le.join(r,te.BUILD_PROFILE_JSON5);try{let t=Se.readFileSync(e,"utf-8");if(!t.trim())return null;let n=Pa.parse(t);if(typeof n!="object"||n===null)return null;let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}function Ia(r,e){if(e.product&&r.validateProduct(e.product),e.buildMode&&!r.profile.app.buildModeSet.some(n=>n.name===e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found in project build-profile.json5.`)}function Aa(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 dr(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 ft(r,e){let t=e,n=`${r} failed`;console.error(lr(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 ur(r,e,t,n,i,o){if(Yt(o).required){console.log(`
|
|
13
|
+
[1/3] Running ohpm install...`);try{await r.installAll()}catch(a){ft("ohpm install",a)}console.log(`
|
|
14
|
+
[2/3] Running hvigor sync...`);try{await e.sync(t,n)}catch(a){ft("hvigor sync",a)}console.log(`
|
|
15
15
|
[3/3] Running hvigor build...`)}else console.log(`
|
|
16
16
|
[skip] ohpm install & hvigor sync (configurations unchanged)`),console.log(`
|
|
17
|
-
[1/1] Running hvigor build...`);try{i.type==="product"?await e.buildProduct(t,n):await e.buildModules(t,n,i.modulesToBuild,i.moduleTasks)}catch(a){
|
|
18
|
-
`+
|
|
19
|
-
[1/2] Running hvigor clean...`);try{await n.clean()}catch(i){
|
|
20
|
-
[2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(i){
|
|
21
|
-
`+
|
|
17
|
+
[1/1] Running hvigor build...`);try{i.type==="product"?await e.buildProduct(t,n):await e.buildModules(t,n,i.modulesToBuild,i.moduleTasks)}catch(a){ft("hvigor build",a)}}var Ii=new Da("build").description("Build HarmonyOS project").option("--product <product>","Product name defined in build-profile.json5 (default: default)").option("--modules <modules...>","Modules to build (format: module or module@target)").option("--build-mode <mode>","Build mode (buildModeSet in build-profile.json5; e.g. debug, release; default: debug)").action(async r=>{try{let e=process.cwd(),t=xe.discover(e);console.warn(Di("Ensure the project source is trustworthy before proceeding."));let n=await O.new();Ia(t,r);let i=r.product||"default",o=r.buildMode||"debug",s;if(r.product&&!r.modules)s={type:"product"};else{let d=Aa(t,r),u=dr(t,d);s={type:"modules",modulesToBuild:d,moduleTasks:u}}let a=new Be(n,t.rootDir),c=new Oe(n,t.rootDir);await ht(t.rootDir,async()=>ur(a,c,i,o,s,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
|
|
18
|
+
`+Ci("Build completed successfully"))}catch(e){console.error(lr(e.message)),process.exit(1)}});Ii.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let r=process.cwd(),e=xe.discover(r);console.warn(Di("Ensure the project source is trusted before proceeding."));let t=await O.new(),n=new Oe(t,e.rootDir);await ht(e.rootDir,async()=>{console.log(`
|
|
19
|
+
[1/2] Running hvigor clean...`);try{await n.clean()}catch(i){ft("hvigor clean",i)}console.log(`
|
|
20
|
+
[2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(i){ft("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
21
|
+
`+Ci("Clean completed successfully."))}catch(r){console.error(lr(r.message)),process.exit(1)}});var Ai=Ii;import{Command as Ua}from"commander";import{green as Li,red as Ba,yellow as Va}from"colorette";import{randomUUID as _a}from"crypto";import{execa as Wa}from"execa";import{execa as $a}from"execa";import{execFile as ka,spawn as Ta}from"child_process";import{promisify as Ma}from"util";var Ra=Ma(ka);function ki(r,e,t){let i=r.replace(/\r\n/g,`
|
|
22
22
|
`).split(`
|
|
23
|
-
`),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
|
|
24
|
-
`)){let i=n.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];!s||s.startsWith("[Empty]")||t.push({serial:s,status:o.length>=2?o[1]:"device"})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await
|
|
23
|
+
`),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 Ti(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function xa(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??0}}function Oa(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function La(r,e,t,n,i){r.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=ki(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=ki(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,Ti(e.stdoutLineBuffer,"stdout",t),Ti(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=xa(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),n(s)})}async function Mi(r,e=[],t={}){try{let{stdout:n,stderr:i}=await Ra(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 Ri(r,e,t){return await new Promise((n,i)=>{let o=Ta(r,e,{stdio:["inherit","pipe","pipe"]}),s=Oa();La(o,s,t,n,i)})}function xi(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var Na=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],Ha=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Ve(r){return r?Na.some(e=>e.test(r))?"transient":Ha.some(e=>e.test(r))?"fatal":"ok":"ok"}var pr=[800,1500,2500];function ja(r){return new Promise(e=>setTimeout(e,r))}async function Pe(r,e){let t=1+pr.length,n={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){n=await Mi(r,e);let o=n.exitCode===0?n.stdout:n.stderr||n.stdout;if(Ve(o)!=="transient"||i>=t-1)return n;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${pr[i]}ms`),await ja(pr[i])}return n}async function Gt(r,e,t){let n=await Pe(r,["-t",e,"shell","param","get",t]);if(n.exitCode!==0)return;let i=n.stdout.trim();if(!(!i||Ve(i)!=="ok"))return xi(i)}var hr="__DEVECO_PARAM_DELIM__";function Fa(r,e){let t=new Map,n=r.split(hr);for(let i=0;i<e.length;i++){let o=(n[i]??"").trim();if(!o||Ve(o)!=="ok")continue;let s=xi(o);s&&t.set(e[i],s)}return t}async function ze(r,e,t){if(t.length===0)return new Map;if(t.length===1){let s=new Map,a=await Gt(r,e,t[0]);return a&&s.set(t[0],a),s}let n=t.map(s=>`param get ${s}`).join(`; echo ${hr}; `)+`; echo ${hr}`,i=await Pe(r,["-t",e,"shell",n]);if(i.exitCode===0){let s=Fa(i.stdout,t);if(s.size>0)return s}m(`Batched param fetch failed (exit=${i.exitCode}), falling back to individual calls for ${e}`);let o=new Map;for(let s of t){let a=await Gt(r,e,s);a&&o.set(s,a)}return o}function mt(r){return r.startsWith("127.0.0.1:")}var Oi=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],B=class r{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new r(e.hdcPath)}static withHdcPath(e){return new r(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let n=e.trim(),i=t?.trim();if(!n||!i)return n;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return n.replace(o,"").trim()||n}async executeHdc(e){return $a(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
|
|
24
|
+
`)){let i=n.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];!s||s.startsWith("[Empty]")||t.push({serial:s,status:o.length>=2?o[1]:"device"})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await ze(this.hdcPath,e,[...Oi]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let n=e.find(s=>s.serial===t);if(n)return n;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
|
|
25
25
|
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
26
|
-
`)):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
|
|
27
|
-
`))}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
|
|
26
|
+
`)):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 ze(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=mt(e),n,i;try{let o=await ze(this.hdcPath,e,[...Oi]);n=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:i}}};var Jt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;m(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await Wa(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/${_a()}`;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 za(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 qa(r,e){let t=await r.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await r.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
27
|
+
`))}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 Ya(r,e){if(e&&e.length>0)return e;let t=r.profile.modules.filter(n=>{let i=r.getModuleType(n.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let n=t[0].name;return console.log(`Auto-selected module: ${n}`),[n]}throw new Error(`Specify module(s) using --module <name> [<name>...].
|
|
28
28
|
Available runnable modules:
|
|
29
29
|
`+t.map(n=>` - ${n.name}`).join(`
|
|
30
|
-
`))}
|
|
31
|
-
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(
|
|
32
|
-
Application '${t}': ${s}`))}var
|
|
33
|
-
`+
|
|
34
|
-
${r} is already up to date (version ${e}.)`));return}console.log(
|
|
35
|
-
New version found: ${n} (current: ${e})`)),console.log(
|
|
36
|
-
`+
|
|
37
|
-
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:
|
|
38
|
-
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(n=>n.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),n=
|
|
39
|
-
`).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
|
|
40
|
-
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,n=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a
|
|
41
|
-
The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as
|
|
42
|
-
`)}function
|
|
30
|
+
`))}async function Ga(r,e,t,n,i,o){o&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
31
|
+
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(Li(`
|
|
32
|
+
Application '${t}': ${s}`))}var Ja=new Ua("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").action(async r=>{try{await Xa(r)}catch(e){console.error(Ba(e.message)),process.exit(1)}});async function Ka(r,e,t,n,i){let o=new Be(e,r.rootDir),s=new Oe(e,r.rootDir),a=new Set;for(let{moduleName:y,targetName:k}of t)for(let H of r.collectNonHarDependentModuleList(y))a.add(`${H}@${k}`);let c=[...a],d=dr(r,c),u={type:"modules",modulesToBuild:c,moduleTasks:d};await ht(r.rootDir,()=>ur(o,s,n,i,u,r.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
33
|
+
`+Li("Build completed successfully."))}async function Xa(r){let e=xe.discover(process.cwd());console.warn(Va("Ensure the project source is trusted before proceeding."));let t=await O.new(),i=Ya(e,r.module).map(za);for(let{moduleName:Te}of i){let Me=e.getModuleType(Te);if(Me!=="entry"&&Me!=="feature"&&Me!=="shared")throw new Error(`Module '${Te}' '${Me}' is not runnable. Specify an entry or feature module.`)}let o=new Jt(t),s=B.from(t),a=await qa(s,r.device),c=a.includes("127.0.0.1")||a.includes("localhost"),d=r.product||"default";e.validateProduct(d);let u=r.buildMode||"debug";r.skipBuild||await Ka(e,t,i,d,u);let y=new Set;for(let{moduleName:Te,targetName:Me}of i){let da=e.collectNonHarDependentModuleList(Te);for(let ua of da)y.add(e.findArtifactPath(ua,Me,c,d));y.add(e.findArtifactPath(Te,Me,c,d))}let k=[...y],H=e.getBundleName(),J=e.getMainAbility(i[0].moduleName,r.ability);await Ga(o,a,H,k,J,!!r.uninstall)}var Ni=Ja;import{Command as Za}from"commander";import{green as Hi,red as ji,cyan as fr}from"colorette";import{execa as Fi}from"execa";function Qa(){return"@deveco-test/deveco-cli"}function ec(){return"1.2.0-Test.4"}var tc=new Za("update").description("Update deveco-cli to latest").action(async()=>{let r=Qa(),e=ec();console.log(fr("Checking for updates..."));try{let{stdout:t}=await Fi("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(Hi(`
|
|
34
|
+
${r} is already up to date (version ${e}.)`));return}console.log(fr(`
|
|
35
|
+
New version found: ${n} (current: ${e})`)),console.log(fr(`Updating ${r}...`)),await Fi("npm",["install","-g",`${r}@latest`],{stdio:"inherit"}),console.log(`
|
|
36
|
+
`+Hi(`${r} updated successfully to version ${n}.`))}catch(t){let n=t;console.error(ji(`Failed to update ${r}`)),n.message&&console.error(ji(n.message)),process.exit(1)}}),$i=tc;import{Command as Ec}from"commander";import{execa as vr}from"execa";function $(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as nc}from"child_process";var rc=2500;function ic(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 oc(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,rc);r.once("error",u=>c(u.message)),ic(r,d,s,a,c,o)}function _i(r,e,t){return m(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,i)=>{let o=[],s=nc(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)),oc(s,o,n,i)})}import*as qe from"path";function sc(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 ac(r){let e=r.instancePath?.trim();if(e)return qe.dirname(qe.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?qe.dirname(qe.normalize(t)).replace(/\\/g,"/"):""}function cc(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function Wi(r,e){return e?[...r,"-bootmode",e]:r}function lc(r,e,t){let n=[Wi(["-start",r],t)],i=ac(e);if(i)for(let o of cc(e.imageRoot))n.push(Wi(["-hvd",r,"-path",i,...o],t));return sc(n)}async function Ui(r,e,t,n){let i=new Error("No start strategy ran"),o=lc(r,e,n);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function mr(r){return(await B.withHdcPath(r).listDevices()).map(t=>t.serial).filter(mt)}async function gr(r){let e=await mr(r);return e.length===0?[]:(await Promise.all(e.map(n=>Gt(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Bi(r,e){return(await gr(r)).includes(e)}import*as Ge from"path";import{existsSync as dc,statSync as uc}from"fs";function Ye(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function pc(r){let e=Ye(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 hc(r){return Ye(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function fc(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=Ge.dirname(Ge.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=Ge.join(t,n.name);dc(i)&&uc(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function mc(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=hc(t),i=Ye(t,["deviceType","DeviceType","devicetype"]),o=Ye(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:pc(t),path:Ye(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Ye(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function gc(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,i;for(;(i=t.exec(r))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=o.toLowerCase();a==="isrunning"?n.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?n.instancePath=s.trim():a==="path"?n.path=s.trim():a==="imageroot"?n.imageRoot=s.trim():a==="devicetype"?n.deviceType=s.trim():a==="os.osversion"&&(n.osVersion=s.trim())}}return n&&e.push(n),e}function Vi(r){let t=mc(r)??gc(r);return fc(t),t}function yr(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function yc(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function vc(r){if(!yc(r))return null;let e=yr(r,["osVersion","OsVersion","OSVersion"]),t=yr(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=yr(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Kt(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=vc(i);o&&n.push(o)}return n}catch{return[]}}function zi(r){let t=Kt(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var qi=/no images are available/i;function ae(r){return r.normalize("NFKC").trim().toLowerCase()}function wc(r){let e=r.message||"";return qi.test(e)}var Je=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 vr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return _i(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Vi(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set($(n.name),n.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),n=$(e),i=t.find(a=>$(a.name)===n);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await Ui(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
37
|
+
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:Bi(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),n=$(e),i=t.find(a=>$(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 vr(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(!wc(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 zi(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}
|
|
38
|
+
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(n=>n.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),n=Kt(t),i=ae(e.deviceType),o=ae(e.osVersion);return n.filter(s=>ae(s.deviceType)===i&&(ae(s.osVersion)===o||ae(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let n=await this.listEmulatorImages({downloaded:!0}),i=Kt(n),o=ae(t),s=e?.trim()?ae(e):void 0;return i.some(a=>ae(a.osVersion)===o||ae(a.softwareVersion)===o?s===void 0?!0:ae(a.deviceType)===s:!1)}async assertSystemImageAvailable(e){let t=e.osVersion?.trim();if(!t)throw new Error("The system image file cannot be found, download it again.");if(!await this.hasDownloadedSystemImage(e.deviceType,t))throw new Error(`The system image file ${t} cannot be found, download it again.`)}async runUninstallImageChecked(e,t){await this.runEmulatorChecked(["-uninstall","-deviceType",e,"-osVersion",t,"-force"],{printOutputOnSuccess:!0,extraReject:[qi]})}async runEmulatorChecked(e,t){let{stdout:n,stderr:i,exitCode:o}=await vr(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(`
|
|
39
|
+
`).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=$(e),o=n.find(s=>$(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(`
|
|
40
|
+
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,n=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>$(a.name)===e))return!0;await new Promise(a=>setTimeout(a,n))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),n=$(e),i=t.find(s=>$(s.name)===n);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
|
|
41
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as wr,yellow as Gi,gray as Ji}from"colorette";import Cc from"ora";import{red as bc}from"colorette";function Xt(r,e){r?r.fail(e):console.error(bc(e)),process.exit(1)}import{green as Sc}from"colorette";function Yi(r,e){return r+" ".repeat(Math.max(0,e-r.length))}function Pc(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 gt(r,e){let t=Pc(r,e),n=[];n.push(r.map((i,o)=>Yi(i,t[o])).join(" ")),n.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Yi(s??"",t[a])).join(" ").trimEnd();n.push(i.highlight?Sc(o):o)}return n.join(`
|
|
42
|
+
`)}function Dc(r,e){if(e.size!==0)for(let t of r){if(!t.isEmulator||!t.name)continue;let n=e.get($(t.name));n&&(t.deviceType=n)}}var Ic=["Name","Serial","Kind","Device Type"];function Ac(r){return{cells:[r.name??r.serial,r.serial,r.isEmulator?"emulator":"device",r.deviceType??"-"],highlight:!0}}function kc(r,e){return r.isEmulator!==e.isEmulator?r.isEmulator?1:-1:(r.name??r.serial).localeCompare(e.name??e.serial)}function Tc(){console.log(Gi(" No active devices.")),console.log(Ji(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function Mc(r){let t=[...r].sort(kc).map(Ac);console.log(gt(Ic,t))}async function Rc(r,e){if(!r.some(i=>i.isEmulator)||!e.emulatorPath)return;let n=await Je.from(e).getDeviceTypeByName();Dc(r,n)}async function xc(r,e,t){try{let n=await r.getConnectedEntries();await Rc(n,e),t?.stop(),n.length===0?Tc():Mc(n)}catch(n){Xt(t,`Failed to list devices: ${n.message}`)}}async function Oc(r,e){let t=await r.listDevices();if(!(t.length<2)){console.error(wr("Multiple devices connected. Specify a device with:"));for(let n of t){let i=await r.getDeviceName(n.serial);console.error(Ji(` ${e} -t ${n.serial} # ${i}`))}process.exit(1)}}async function Lc(r,e){try{e||await Oc(r,"devecocli device view");let t=await r.listDevices(),n=await r.getDeviceInfo(t,e);n||(console.log(Gi("No connected device found.")),process.exit(1));let i=await r.getDeviceDetail(n.serial),o=await r.getDeviceName(n.serial);console.log(` Serial: ${n.serial}`),console.log(` Device Name: ${o}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}catch(t){console.error(wr(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Ki(){try{let r=await O.new();return{manager:B.from(r),toolProvider:r}}catch(r){console.error(wr(`Failed to initialize device manager: ${r.message}`)),process.exit(1);return}}var br=new Ec("device").description("Manage connected devices");br.command("list").description("List all connected devices").action(async()=>{let{manager:r,toolProvider:e}=await Ki(),t=Cc({text:"Querying connected devices\u2026",color:"cyan"}).start();await xc(r,e,t)});br.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 Lc(e,r.target)});var Xi=br;import{Command as Dr,Option as ho}from"commander";import{green as Qt,cyan as Xe,red as V,yellow as ce,gray as vt}from"colorette";import Qc from"ora";import Nc from"readline/promises";import{execa as Qi}from"execa";import*as Ee from"fs/promises";import*as Pr from"os";import*as Ne from"path";var Sr=`1/4:\r
|
|
43
43
|
---------------------------------------\r
|
|
44
44
|
Statement About HarmonyOS and Privacy\r
|
|
45
45
|
\r
|
|
@@ -1209,58 +1209,58 @@ Part I: Chinese mainland.\r
|
|
|
1209
1209
|
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
|
|
1210
1210
|
\r
|
|
1211
1211
|
Part III: Other countries and regions.\r
|
|
1212
|
-
---------------------------------------\r`;var
|
|
1213
|
-
`),eo
|
|
1214
|
-
`)}function
|
|
1215
|
-
${t}.`);return
|
|
1216
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1212
|
+
---------------------------------------\r`;var Hc=new Set,Zt=new Map,Er="HarmonyOS_Software_Service_Agreement",eo=["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(`
|
|
1213
|
+
`),to=eo,Cr="HarmonyOS_SDK_Agreement";function no(r,e){return`${r}\0${e}`}function jc(){Hc.clear(),Zt.clear()}var Fc=eo,ne=class extends Error{constructor(e=Fc){super(e),this.name="EmulatorLicenseBlockedError"}};function ro(r,e){return[r??"",e??""].join(`
|
|
1214
|
+
`)}function io(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 $c(r){return`Emulator${r.trim()}`}function oo(r){let e=$c(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 Ne.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Ne.join(Pr.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Ne.join(Pr.homedir(),".cache");return Ne.join(t,"Huawei",e,".emu_config")}async function _c(r,e,t){let n=no(r,e),i=Zt.get(n);if(i!==void 0)return i;let o=await Qi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=ro(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new ne(t);return Zt.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 Uc(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 Bc(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 Vc(r){let e={};for(let t of r.split(/\r?\n/)){let n=Bc(t);n&&(e[n.key]=n.entry)}return e}function zc(r){let e=r.trim();if(!e)return{};let t=Uc(e);return t||Vc(r)}function qc(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function so(r,e,t,n){let i=await _c(r,e,n),o=io(i);if(!o)throw new ne(n);let s=oo(o),a;try{a=await Ee.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new ne(n):u}let d=zc(a)[t];if(!d)throw new ne(n);if(d.delimiter==="=")throw new ne(n);if(!qc(d.value))throw new ne(n)}async function ao(r,e){await so(r,e,Er,to)}async function co(r,e){await so(r,e,Cr,to)}async function Yc(r,e){let t=await Qi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=ro(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=no(r,e);return Zt.set(i,n),n}async function Gc(r,e){let t=await Yc(r,e),n=io(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1215
|
+
${t}.`);return oo(n)}function Zi(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Jc(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[Er]="agree",n[Cr]="agree",await Ee.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
1216
|
+
`,"utf8"),!0}catch{}return!1}async function Kc(r,e){let t=Er,n=Cr,i=[{k:t,re:new RegExp(`^\\s*${Zi(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${Zi(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:y}of i)if(y.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 Ee.writeFile(r,s.join(`
|
|
1217
1217
|
`)+(s.length>0?`
|
|
1218
|
-
`:""),"utf8")}async function Jc(r){await Ee.mkdir(Oe.dirname(r),{recursive:!0});let e="";try{e=await Ee.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Yc(r,e,t)||await Gc(r,e)}async function co(r,e){return console.log(br),0}var Kc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function lo(r,e){if(console.log(br),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let n=Oc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(Kc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await qc(r,e);await Jc(s),Nc()}catch(s){return console.error(s.message),1}return 0}var Zc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Qc(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 el(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${r}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function tl(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(ce("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ce("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===n)){console.error(V("--os-version does not match any downloaded image (exact string required).")),console.log(ce("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 nl=["Name","Status","Serial","Device Type","OS Version"];function rl(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-",r.osVersion??"-"],highlight:t}}async function il(r,e){let t=await Promise.all(e.map(async n=>{let i=await Be(r,n,Zc);return[n,i]}));return new Map(t)}async function ol(r){let e=await fr(r),t=await il(r,e);return{serials:e,params:t}}function sl(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 al(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&&sl(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 cl(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=>rl(i.emu,i.serial,i.effectiveRunning))}async function ll(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),ol(e)]);if(n.length===0){t?.stop(),console.log(ce(" No emulator instances found."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=al(i.serials,i.params,o);t?.stop();let c=cl(n,s,a);console.log(ft(nl,c))}catch(n){Jt(t,`Failed to list emulators: ${n.message}`)}}function ho(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(V(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(gt(s.stdout)),s.stderr&&console.error(gt(s.stderr))}return n}var dl=2e3,ul=6e4;async function pl(r,e){let t=j(e);return(await mr(r)).some(i=>j(i)===t)}async function fo(r,e,t,n=ul,i=dl){let o=Date.now()+n;for(;Date.now()<o;){if(await pl(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function hl(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(ce(`Emulator "${t}" is already running.`));return}console.log(Je(`Starting emulator "${t}"...`));let i=await fo(e,t,!0);console.log(i?Xt(`Emulator "${t}" started successfully.`):ce(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function fl(r,e,t){let n=await Promise.allSettled(t.map(o=>hl(r,e,o)));ho(n,t,"start")&&process.exit(1)}async function ml(r,e){let t=e.trim();if(!ht(t))return t;let n=await B.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function gl(r,e,t){let n=await ml(e,t);if(console.log(Je(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(ce(`Emulator "${n}" is already stopped.`));return}let o=await fo(e,n,!1);console.log(o?Xt(`Emulator "${n}" stopped successfully.`):ce(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function yl(r,e,t){let n=await Promise.allSettled(t.map(o=>gl(r,e,o)));ho(n,t,"stop")&&process.exit(1)}async function le(){try{let r=await O.new();return{manager:Ye.from(r),toolProvider:r}}catch(r){console.error(V(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var Ce=new Cr("emulator").description("Manage emulator instances"),vl=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Zt(r){let e=new po("--device-type <type>","Emulator device type").choices([...vl]);return r?e.makeOptionMandatory():e}function Ge(r,e){for(let t of e)if(t in r)return r[t]}function mt(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function uo(r){let e=mt(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var wl=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],bl="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function mo(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function go(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=mt(Ge(i,["osVersion","OsVersion","OSVersion","os_version"])),s=mt(Ge(i,["deviceType","DeviceType","device_type"])),a=uo(Ge(i,["downloaded","Downloaded","isDownloaded"])),c=mt(Ge(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=mt(Ge(i,["releaseType","ReleaseType","release_type"])),u=uo(Ge(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function Sl(r){let e=r.trim();if(!e)return!0;let t=mo(e);return t===null?!1:t.length===0?!0:go(t,!0).length===0}function Pl(r,e){let t=r.trim();if(!t)return"";let n=mo(t);if(!n)return r.trimEnd();let i=go(n,e);return ft(wl,i)}var Qt=new Cr("image").description("HarmonyOS emulator system images (download, list, remove)");Qt.command("download").description("Download system image").addOption(Zt(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let{manager:e,toolProvider:t}=await le();try{await ao(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof ne&&(console.error(V(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(V("Error: missing required option '--device-type <type>'")),process.exit(1)),r.osVersion?.trim()||(console.error(V("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:r.deviceType.trim(),osVersion:r.osVersion.trim(),force:r.force===!0})}catch(n){console.error(V(`Failed to download system image: ${n.message}`)),process.exit(1)}});Qt.command("remove").description("Remove a downloaded system image").addOption(Zt(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await le();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(V(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Qt.command("list").description("List system images").addOption(Zt(!1)).option("--all","List all images (local and remote)").addOption(new po("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await le();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(Sl(n)){console.log(ce(bl));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=Pl(n,r.all===!0);console.log(i)}catch(t){console.error(V(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Ce.addCommand(Qt);var Dr=new Cr("license").description("local emulator license");Dr.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:r}=await le(),e=await co(r.emulatorPath,r.sdkPath);process.exit(e)});Dr.command("accept").description("review and accept agreements").action(async()=>{let{toolProvider:r}=await le(),e=await lo(r.emulatorPath,r.sdkPath);process.exit(e)});Ce.addCommand(Dr);Ce.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await le(),t=Xc({text:"Listing emulators\u2026",color:"cyan"}).start();await ll(r,e.hdcPath,t)});Ce.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await le();try{await so(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof ne&&(console.error(V(n.message)),process.exit(1)),n}r?.length||(console.error(V("Error: missing required argument 'names'")),process.exit(1)),await fl(e,t.hdcPath,r)});Ce.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async r=>{let{manager:e,toolProvider:t}=await le();r?.length||(console.error(V("Error: missing required argument 'names'")),process.exit(1)),await yl(e,t.hdcPath,r)});var yo=Ce.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026; --os-version must match a downloaded image from `emulator image list`.").addOption(Zt(!0)).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`').option("--force","Overwrite if supported");yo.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1219
|
-
${ce("Tip: ")}${
|
|
1220
|
-
${
|
|
1221
|
-
${
|
|
1222
|
-
`)}});
|
|
1223
|
-
${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)}},De=new Ir;var So=["DevEco"];async function en(){let r=await De.get(Q.TAGS_API_URL),t=tn(r,"Tags API").data.skill.filter(n=>n.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(n=>n.id)}async function Il(r){let e=[],t=Q.DEFAULT_PAGE_SIZE,n=1;for(;;){let i=await De.post(Q.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:n,pageSize:t,tagIds:[r]}}),o=tn(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;n++}return e}async function Ar(r){let e=new Map,t=r.map(i=>Il(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!So.includes(o.name)))}async function Al(r,e){let t=await De.post(Q.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Q.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return tn(t,"Skills API").data.list}async function kr(r,e){let t=new Map,n=e.map(o=>Al(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!So.includes(s.name)))}function Po(r){let e=[];for(let[,t]of Object.entries(ee)){let n=bo.join(Dl(),t.path,r);wo.existsSync(n)&&e.push(t.displayName)}return e.sort()}function tn(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=De.parseJson(r);if(t.code!==Q.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Eo(r){let e=`${Q.SKILL_API_BASE}/${r}/checksum`,t=await De.get(e);return tn(t,"Checksum API").data}import kl from"adm-zip";import Tl from"crypto";import Do from"fs";import x from"path";import{fileURLToPath as Ml}from"url";import{homedir as Io}from"os";import{red as Rl}from"colorette";var he=Do.promises;function Tr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function Co(r,e){let t=x.resolve(e),n=x.resolve(r),i=x.relative(n,t);if(i.startsWith("..")||x.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Mr(r){return x.isAbsolute(r)?r:x.resolve(process.cwd(),r)}function xl(r){return Tl.createHash("sha256").update(r).digest("hex")}async function Ol(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=xl(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Ao(r){let e=`${Q.SKILL_API_BASE}/${r}/install?format=zip`,t=await De.getBinary(e),n=await Eo(r);return await Ol(t,n),t}async function Ll(r,e,t){Tr(t);let n=new kl(r),i=n.getEntries();try{await he.stat(e)}catch{await he.mkdir(e,{recursive:!0})}let o=x.join(e,t);Co(e,o);for(let s of i){let a=x.join(o,s.entryName);Co(o,a)}n.extractAllTo(o,!0)}async function Rr(r){let e=ee[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ee).join(", ")}`);let t=x.join(Io(),e.path.replace("/skills",""));try{return await he.access(t),!0}catch{return!1}}function xr(r){let e=ee[r];return x.join(Io(),e.path)}function Nl(r){let e=ee[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ee).join(", ")}`);return e}function Or(r,e){let t=Nl(e),n="projectPath"in t?t.projectPath:x.join("."+e,"skills");return x.join(r,n)}async function Hl(r,e,t){Tr(e);let n=x.join(r,e);try{if(await he.access(n),t)await he.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 Lr(r,e,t){await Ll(r,e,t),console.log(`Skill ${t} installed to ${x.join(e,t)}.`)}async function Nr(r,e,t){let n=x.join(e,t);await he.mkdir(n,{recursive:!0});let i=x.join(n,x.basename(r));await he.copyFile(r,i),console.log(`Skill ${t} installed to ${n}.`)}function ko(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(Rl(`Faild to exute operation for skill "${r}": ${n}`)),{success:!1,error:n}}async function Ke(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 ko(r,i,"Installation failed")}}async function Hr(r,e){try{Tr(r);let t=await e(),n=x.join(t,r);try{await he.access(n)}catch{return console.log(`Skill ${r} not found in ${t}`),{success:!0,skipped:!0}}return await he.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}.`),{success:!0}}catch(t){return ko(r,t,"Removal failed")}}async function To(r,e,t,n=!1){return Ke(r,()=>xr(e),i=>Lr(t,i,r),n)}async function Mo(r,e,t,n=!1){return Ke(r,()=>t,i=>Lr(e,i,r),n)}async function Ro(r,e,t,n,i=!1){return Ke(r,()=>Or(t,n),o=>Lr(e,o,r),i)}async function xo(r,e,t,n=!1){return Ke(r,()=>xr(t),i=>Nr(e,i,r),n)}async function Oo(r,e,t,n,i=!1){return Ke(r,()=>Or(t,n),o=>Nr(e,o,r),i)}async function Lo(r,e,t,n=!1){return Ke(r,()=>t,i=>Nr(e,i,r),n)}async function No(r,e){return Hr(r,()=>xr(e))}async function Ho(r,e){return Hr(r,()=>e)}async function jo(r,e,t){return Hr(r,()=>Or(e,t))}function Fo(){let e=x.dirname(Ml(import.meta.url));for(;;){let t=x.join(e,"SKILL.md");if(Do.existsSync(t))return t;let n=x.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import $o from"fs";import{cyan as jl}from"colorette";async function yt(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await Rr(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function vt(){let r=[];for(let e of Object.keys(ee))await Rr(e)&&r.push(e);return r}function wt(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(jl("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Ie(r,e,t){if(!$o.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!$o.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function bt(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?Mr(r):void 0,resolvedProject:e?Mr(e):void 0}}async function nn(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await yt(r.agent)).map(a=>({project:t,agent:a})):t?i=(await vt()).map(a=>({project:t,agent:a})):r.agent?n=await yt(r.agent):n=await vt(),!o&&n.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:n,projectAgents:i,customPath:o}}async function Wl(r){let e=await en();if(r.all)return(await Ar(e)).map(n=>n.enName);{let n=(await kr(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function Ul(r,e,t,n){let i=[];if(t.customPath){let o=await Mo(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await To(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await Ro(r,e,o,s,n);i.push(a)}return i}function Bl(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}=bt(r.path,r.project,r.agent);return t&&Ie(t,"Project directory",r.force),e&&Ie(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function Vl(r,e,t){let n=await nn(r,e,t);return{skillNames:await Wl(r),targets:n}}async function zl(r,e,t,n){let i=[],o=r.length,s=_l(5),a=r.map(async c=>s(async()=>{try{let d=await Ao(c);return{name:c,buffer:d,success:!0}}catch(d){let u=d instanceof Error?d.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<r.length;c++){let d=r[c],u=o>1?` (${c+1}/${o})`:"";n.start(`Installing ${d}${u}...`);let y=await a[c];if(!y.success){n.fail(),console.log(St(`${d}: Download failed - ${y.error}`)),i.push({success:!1});continue}n.stop();let k=await Ul(d,y.buffer,e,t);i.push(...k)}return i}async function ql(r){let e=new Le;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=Bl(r),{skillNames:i,targets:o}=await Vl(r,t,n),s=await zl(i,o,r.force||!1,e);e.stop(),wt(s)}catch(t){throw e.stop(),t}}function Yl(r){let{resolvedPath:e,resolvedProject:t}=bt(r.path,r.project,r.agent);return t&&Ie(t,"Project directory"),e&&Ie(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Gl(r,e){let t=new Le;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=Yl(e);t.stop();let o=await Jl(e,r,n,i);t.stop(),wt(o)}catch(n){throw t.stop(),n}}function _o(r,e=""){if(r.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function rn(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await No(r,n.agent):await jo(r,n.project,n.agent);t.push(i)}return t}async function Jl(r,e,t,n){if(t)return[await Ho(e,t)];if(n&&r.agent){let a=(await yt(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return rn(e,a)}if(n){let s=await vt();_o(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return rn(e,a)}if(r.agent){let a=(await yt(r.agent)).map(c=>({type:"agent",agent:c}));return rn(e,a)}let i=await vt();_o(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return rn(e,o)}var Pt=new Fl("skills").description("Manage HarmonyOS skills");Pt.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new Le;try{e.start("Fetching skills...");let t=await en(),n=await Ar(t);if(n.length===0){e.stop(),console.log(Uo("No skills available."));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(Wo(i.enName)),console.log(Bo(i.description));let o=Po(i.enName);o.length>0&&console.log($l(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(St(t.message)),process.exit(1)}});Pt.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new Le;try{e.start("Searching skills...");let t=await en(),n=await kr(r,t);if(n.length===0){console.log(Uo(`No skills found matching '${r}'.`)),e.stop();return}e.succeed(`Found ${n.length} skills.`);for(let i of n)console.log(Wo(i.enName)),console.log(Bo(i.description)),console.log()}catch(t){e.stop(),console.error(St(t.message)),process.exit(1)}});Pt.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await ql(r)}catch(e){console.error(St(e.message)),process.exit(1)}});Pt.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async r=>{try{await Gl(r.skill,r)}catch(e){console.error(St(e.message)),process.exit(1)}});var Vo=Pt;import{Command as Xl,InvalidArgumentError as qo}from"commander";import{cyan as on}from"colorette";function Ne(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=Ue(t);return n==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var jr=[800,1500,2500];function Kl(r){return new Promise(e=>setTimeout(e,r))}var sn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}createFollowLineHandler(e){return(t,n)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(n!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1224
|
-
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(
|
|
1218
|
+
`:""),"utf8")}async function Xc(r){await Ee.mkdir(Ne.dirname(r),{recursive:!0});let e="";try{e=await Ee.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Jc(r,e,t)||await Kc(r,e)}async function lo(r,e){return console.log(Sr),0}var Zc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function uo(r,e){if(console.log(Sr),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license accept` requires an interactive terminal."),1;let n=Nc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(Zc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Gc(r,e);await Xc(s),jc()}catch(s){return console.error(s.message),1}return 0}var el=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function tl(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 nl(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid. use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)".'):new Error(`Invalid --os-version "${r}". It must start with "HarmonyOS " (e.g. "HarmonyOS 5.1.1(19)").`)}function rl(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(ce("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ce("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===n)){console.error(V("--os-version does not match any downloaded image (exact string required).")),console.log(ce("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 il=["Name","Status","Serial","Device Type","OS Version"];function ol(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-",r.osVersion??"-"],highlight:t}}async function sl(r,e){let t=await Promise.all(e.map(async n=>{let i=await ze(r,n,el);return[n,i]}));return new Map(t)}async function al(r){let e=await mr(r),t=await sl(r,e);return{serials:e,params:t}}function cl(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 ll(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&&cl(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 dl(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=>ol(i.emu,i.serial,i.effectiveRunning))}async function ul(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),al(e)]);if(n.length===0){t?.stop(),console.log(ce(" No emulator instances found."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=ll(i.serials,i.params,o);t?.stop();let c=dl(n,s,a);console.log(gt(il,c))}catch(n){Xt(t,`Failed to list emulators: ${n.message}`)}}function fo(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(V(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(vt(s.stdout)),s.stderr&&console.error(vt(s.stderr))}return n}var pl=2e3,hl=6e4;async function fl(r,e){let t=$(e);return(await gr(r)).some(i=>$(i)===t)}async function mo(r,e,t,n=hl,i=pl){let o=Date.now()+n;for(;Date.now()<o;){if(await fl(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function ml(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(ce(`Emulator "${t}" is already running.`));return}console.log(Xe(`Starting emulator "${t}"...`));let i=await mo(e,t,!0);console.log(i?Qt(`Emulator "${t}" started successfully.`):ce(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function gl(r,e,t){let n=await Promise.allSettled(t.map(o=>ml(r,e,o)));fo(n,t,"start")&&process.exit(1)}async function yl(r,e){let t=e.trim();if(!mt(t))return t;let n=await B.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function vl(r,e,t){let n=await yl(e,t);if(console.log(Xe(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(ce(`Emulator "${n}" is already stopped.`));return}let o=await mo(e,n,!1);console.log(o?Qt(`Emulator "${n}" stopped successfully.`):ce(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function wl(r,e,t){let n=await Promise.allSettled(t.map(o=>vl(r,e,o)));fo(n,t,"stop")&&process.exit(1)}async function le(){try{let r=await O.new();return{manager:Je.from(r),toolProvider:r}}catch(r){console.error(V(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var Ce=new Dr("emulator").description("Manage emulator instances"),bl=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function en(r){let e=new ho("--device-type <type>","Emulator device type").choices([...bl]);return r?e.makeOptionMandatory():e}function Ke(r,e){for(let t of e)if(t in r)return r[t]}function yt(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function po(r){let e=yt(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Sl=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],Pl="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function go(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function yo(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=yt(Ke(i,["osVersion","OsVersion","OSVersion","os_version"])),s=yt(Ke(i,["deviceType","DeviceType","device_type"])),a=po(Ke(i,["downloaded","Downloaded","isDownloaded"])),c=yt(Ke(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=yt(Ke(i,["releaseType","ReleaseType","release_type"])),u=po(Ke(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function El(r){let e=r.trim();if(!e)return!0;let t=go(e);return t===null?!1:t.length===0?!0:yo(t,!0).length===0}function Cl(r,e){let t=r.trim();if(!t)return"";let n=go(t);if(!n)return r.trimEnd();let i=yo(n,e);return gt(Sl,i)}var tn=new Dr("image").description("HarmonyOS emulator system images (download, list, remove)");tn.command("download").description("Download system image").addOption(en(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let{manager:e,toolProvider:t}=await le();try{await co(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof ne&&(console.error(V(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(V("Error: missing required option '--device-type <type>'")),process.exit(1)),r.osVersion?.trim()||(console.error(V("Error: misssing required option '--os-version <version>'")),process.exit(1));try{await e.installEmulatorImage({deviceType:r.deviceType.trim(),osVersion:r.osVersion.trim(),force:r.force===!0})}catch(n){console.error(V(`Failed to download system image: ${n.message}`)),process.exit(1)}});tn.command("remove").description("Remove a downloaded system image").addOption(en(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await le();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(V(`Failed to remove system image: ${t.message}`)),process.exit(1)}});tn.command("list").description("List system images").addOption(en(!1)).option("--all","List all images (local and remote)").addOption(new ho("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await le();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(El(n)){console.log(ce(Pl));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=Cl(n,r.all===!0);console.log(i)}catch(t){console.error(V(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});Ce.addCommand(tn);var Ir=new Dr("license").description("local emulator license");Ir.command("view").description("Review agreement text(read-only)").action(async()=>{let{toolProvider:r}=await le(),e=await lo(r.emulatorPath,r.sdkPath);process.exit(e)});Ir.command("accept").description("Review and accept agreements").action(async()=>{let{toolProvider:r}=await le(),e=await uo(r.emulatorPath,r.sdkPath);process.exit(e)});Ce.addCommand(Ir);Ce.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await le(),t=Qc({text:"Listing emulators\u2026",color:"cyan"}).start();await ul(r,e.hdcPath,t)});Ce.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await le();try{await ao(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof ne&&(console.error(V(n.message)),process.exit(1)),n}r?.length||(console.error(V("Error: missing required argument 'names'")),process.exit(1)),await gl(e,t.hdcPath,r)});Ce.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async r=>{let{manager:e,toolProvider:t}=await le();r?.length||(console.error(V("Error: missing required argument 'names'")),process.exit(1)),await wl(e,t.hdcPath,r)});var vo=Ce.command("create <name>").description("Create a local emulator by running emulator -create <name> \u2026. --os-version must match a downloaded image from `emulator image list`.").addOption(en(!0)).requiredOption("--os-version <version>",'Downloaded image label. which will be quoted in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or be used in the format --os-version="\u2026";For details, run`devecocli emulator image list`.').option("--force","Overwrite if supported");vo.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1219
|
+
${ce("Tip: ")}${vt("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1220
|
+
${Xe('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1221
|
+
${Xe('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1222
|
+
`)}});vo.action(async(r,e)=>{try{tl(r),nl(e.osVersion);let{manager:t}=await le(),n=await t.listDownloadedImageOsVersions();rl(e.osVersion,n),console.log(Xe(`Creating emulator "${r}"...`)),await t.createVirtualDevice({name:r,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(Qt(`Emulator "${r}" created successfully.`))}catch(t){console.error(V(`${t.message}`)),process.exit(1)}});Ce.command("delete <name>").description("Delete a local emulator instance").action(async r=>{let{manager:e}=await le();console.log(Xe(`Deleting emulator "${r}"...`));try{let t=await e.deleteVirtualDevice(r);console.log(Qt(`Emulator "${t}" deleted successfully.`))}catch(t){let n=t;console.error(V(n.message)),n.stdout&&console.error(vt(n.stdout)),n.stderr&&console.error(vt(n.stderr)),process.exit(1)}});var wo=Ce;import{Command as _l}from"commander";import{green as Wl,red as Et,cyan as Uo,yellow as Bo,dim as Vo}from"colorette";import Ul from"p-limit";import Dl from"ora";var He=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=Dl(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 bo from"fs";import*as So from"path";import{homedir as Al}from"os";import Il from"axios";var Ar=class{client;constructor(){let e={timeout:ar.HTTP_TIMEOUT_MS,headers:{"User-Agent":Vt.USER_AGENT,"accept-language":Vt.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}
|
|
1223
|
+
${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)}},De=new Ar;var Po=["DevEco"];async function nn(){let r=await De.get(Q.TAGS_API_URL),t=rn(r,"Tags API").data.skill.filter(n=>n.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(n=>n.id)}async function kl(r){let e=[],t=Q.DEFAULT_PAGE_SIZE,n=1;for(;;){let i=await De.post(Q.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:n,pageSize:t,tagIds:[r]}}),o=rn(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;n++}return e}async function kr(r){let e=new Map,t=r.map(i=>kl(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Po.includes(o.name)))}async function Tl(r,e){let t=await De.post(Q.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Q.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return rn(t,"Skills API").data.list}async function Tr(r,e){let t=new Map,n=e.map(o=>Tl(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Po.includes(s.name)))}function Eo(r){let e=[];for(let[,t]of Object.entries(ee)){let n=So.join(Al(),t.path,r);bo.existsSync(n)&&e.push(t.displayName)}return e.sort()}function rn(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=De.parseJson(r);if(t.code!==Q.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Co(r){let e=`${Q.SKILL_API_BASE}/${r}/checksum`,t=await De.get(e);return rn(t,"Checksum API").data}import Ml from"adm-zip";import Rl from"crypto";import Io from"fs";import x from"path";import{fileURLToPath as xl}from"url";import{homedir as Ao}from"os";import{red as Ol}from"colorette";var he=Io.promises;function Mr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function Do(r,e){let t=x.resolve(e),n=x.resolve(r),i=x.relative(n,t);if(i.startsWith("..")||x.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Rr(r){return x.isAbsolute(r)?r:x.resolve(process.cwd(),r)}function Ll(r){return Rl.createHash("sha256").update(r).digest("hex")}async function Nl(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=Ll(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function ko(r){let e=`${Q.SKILL_API_BASE}/${r}/install?format=zip`,t=await De.getBinary(e),n=await Co(r);return await Nl(t,n),t}async function Hl(r,e,t){Mr(t);let n=new Ml(r),i=n.getEntries();try{await he.stat(e)}catch{await he.mkdir(e,{recursive:!0})}let o=x.join(e,t);Do(e,o);for(let s of i){let a=x.join(o,s.entryName);Do(o,a)}n.extractAllTo(o,!0)}async function xr(r){let e=ee[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ee).join(", ")}`);let t=x.join(Ao(),e.path.replace("/skills",""));try{return await he.access(t),!0}catch{return!1}}function Or(r){let e=ee[r];return x.join(Ao(),e.path)}function jl(r){let e=ee[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(ee).join(", ")}`);return e}function Lr(r,e){let t=jl(e),n="projectPath"in t?t.projectPath:x.join("."+e,"skills");return x.join(r,n)}async function Fl(r,e,t){Mr(e);let n=x.join(r,e);try{if(await he.access(n),t)await he.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 Nr(r,e,t){await Hl(r,e,t),console.log(`Skill ${t} installed to ${x.join(e,t)}.`)}async function Hr(r,e,t){let n=x.join(e,t);await he.mkdir(n,{recursive:!0});let i=x.join(n,x.basename(r));await he.copyFile(r,i),console.log(`Skill ${t} installed to ${n}.`)}function To(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(Ol(`Faild to exute operation for skill "${r}": ${n}`)),{success:!1,error:n}}async function Ze(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await Fl(i,r,n);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return To(r,i,"Installation failed")}}async function jr(r,e){try{Mr(r);let t=await e(),n=x.join(t,r);try{await he.access(n)}catch{return console.log(`Skill ${r} not found in ${t}`),{success:!0,skipped:!0}}return await he.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}.`),{success:!0}}catch(t){return To(r,t,"Removal failed")}}async function Mo(r,e,t,n=!1){return Ze(r,()=>Or(e),i=>Nr(t,i,r),n)}async function Ro(r,e,t,n=!1){return Ze(r,()=>t,i=>Nr(e,i,r),n)}async function xo(r,e,t,n,i=!1){return Ze(r,()=>Lr(t,n),o=>Nr(e,o,r),i)}async function Oo(r,e,t,n=!1){return Ze(r,()=>Or(t),i=>Hr(e,i,r),n)}async function Lo(r,e,t,n,i=!1){return Ze(r,()=>Lr(t,n),o=>Hr(e,o,r),i)}async function No(r,e,t,n=!1){return Ze(r,()=>t,i=>Hr(e,i,r),n)}async function Ho(r,e){return jr(r,()=>Or(e))}async function jo(r,e){return jr(r,()=>e)}async function Fo(r,e,t){return jr(r,()=>Lr(e,t))}function $o(){let e=x.dirname(xl(import.meta.url));for(;;){let t=x.join(e,"SKILL.md");if(Io.existsSync(t))return t;let n=x.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import _o from"fs";import{cyan as $l}from"colorette";async function wt(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await xr(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function bt(){let r=[];for(let e of Object.keys(ee))await xr(e)&&r.push(e);return r}function St(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($l("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Ie(r,e,t){if(!_o.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!_o.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function Pt(r,e,t){if(r&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:r?Rr(r):void 0,resolvedProject:e?Rr(e):void 0}}async function on(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await wt(r.agent)).map(a=>({project:t,agent:a})):t?i=(await bt()).map(a=>({project:t,agent:a})):r.agent?n=await wt(r.agent):n=await bt(),!o&&n.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:n,projectAgents:i,customPath:o}}async function Bl(r){let e=await nn();if(r.all)return(await kr(e)).map(n=>n.enName);{let n=(await Tr(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 Ro(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await Mo(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await xo(r,e,o,s,n);i.push(a)}return i}function zl(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}=Pt(r.path,r.project,r.agent);return t&&Ie(t,"Project directory",r.force),e&&Ie(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function ql(r,e,t){let n=await on(r,e,t);return{skillNames:await Bl(r),targets:n}}async function Yl(r,e,t,n){let i=[],o=r.length,s=Ul(5),a=r.map(async c=>s(async()=>{try{let d=await ko(c);return{name:c,buffer:d,success:!0}}catch(d){let u=d instanceof Error?d.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<r.length;c++){let d=r[c],u=o>1?` (${c+1}/${o})`:"";n.start(`Installing ${d}${u}...`);let y=await a[c];if(!y.success){n.fail(),console.log(Et(`${d}: Download failed - ${y.error}`)),i.push({success:!1});continue}n.stop();let k=await Vl(d,y.buffer,e,t);i.push(...k)}return i}async function Gl(r){let e=new He;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=zl(r),{skillNames:i,targets:o}=await ql(r,t,n),s=await Yl(i,o,r.force||!1,e);e.stop(),St(s)}catch(t){throw e.stop(),t}}function Jl(r){let{resolvedPath:e,resolvedProject:t}=Pt(r.path,r.project,r.agent);return t&&Ie(t,"Project directory"),e&&Ie(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Kl(r,e){let t=new He;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=Jl(e);t.stop();let o=await Xl(e,r,n,i);t.stop(),St(o)}catch(n){throw t.stop(),n}}function Wo(r,e=""){if(r.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function sn(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await Ho(r,n.agent):await Fo(r,n.project,n.agent);t.push(i)}return t}async function Xl(r,e,t,n){if(t)return[await jo(e,t)];if(n&&r.agent){let a=(await wt(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return sn(e,a)}if(n){let s=await bt();Wo(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return sn(e,a)}if(r.agent){let a=(await wt(r.agent)).map(c=>({type:"agent",agent:c}));return sn(e,a)}let i=await bt();Wo(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return sn(e,o)}var Ct=new _l("skills").description("Manage HarmonyOS skills");Ct.command("list").description("List all available HarmonyOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new He;try{e.start("Fetching skills...");let t=await nn(),n=await kr(t);if(n.length===0){e.stop(),console.log(Bo("No skills available."));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(Uo(i.enName)),console.log(Vo(i.description));let o=Eo(i.enName);o.length>0&&console.log(Wl(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(Et(t.message)),process.exit(1)}});Ct.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new He;try{e.start("Searching skills...");let t=await nn(),n=await Tr(r,t);if(n.length===0){console.log(Bo(`No skills found matching '${r}'.`)),e.stop();return}e.succeed(`Found ${n.length} skills.`);for(let i of n)console.log(Uo(i.enName)),console.log(Vo(i.description)),console.log()}catch(t){e.stop(),console.error(Et(t.message)),process.exit(1)}});Ct.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated; Omit to install to all available agents.").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory for skill installation").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await Gl(r)}catch(e){console.error(Et(e.message)),process.exit(1)}});Ct.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated.Omit to remove from all available agents").option("--project <path>","Project root directory for skill removal").option("--path <path>","Path for skill removal").action(async r=>{try{await Kl(r.skill,r)}catch(e){console.error(Et(e.message)),process.exit(1)}});var zo=Ct;import{Command as Ql,InvalidArgumentError as Yo}from"commander";import{cyan as an}from"colorette";function je(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=Ve(t);return n==="transient"?new Error(`${e}: Device communication channel unavailabel. Retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Fr=[800,1500,2500];function Zl(r){return new Promise(e=>setTimeout(e,r))}var cn=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}createFollowLineHandler(e){return(t,n)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(n!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1224
|
+
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(an(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(an(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(n,e);if(i)return m(an(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(n);throw new Error(`Device '${e}' not found.
|
|
1225
1225
|
Available devices:
|
|
1226
|
-
${o}`)}if(n.length===1){let i=n[0];return m(
|
|
1226
|
+
${o}`)}if(n.length===1){let i=n[0];return m(an(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(n))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,n){m(`Retrieving PID for bundle ${n}`),S.assertBundleName(n);let i=await Pe(e,["-t",t,"shell","pidof",n]),o=je(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${n}: ${a}`),a}return m(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){m(`Setting hilog buffer size to: ${n}`);let i=await Pe(e,["-t",t,"shell","hilog","-G",n]),o=je(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&&(S.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(S.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(S.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(S.assertHilogKeyword(e.keyword),n.push("-e",S.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,i,o){let a=await Ri(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+Fr.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(Ve(d)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Fr[c]}ms`),await Zl(Fr[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 Pe(e,s),c=je(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=S.filterLogsByRelativeWindow(a.stdout||a.stderr,n.fromSeconds,n.toSeconds);d=S.getLastLines(d,n.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,n,i){let[o,s]=this.buildHilogCommand(e,t,n,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,()=>{},y=>{m(`Callback triggered when an error occurs during a single hilog streaming read: ${y.message}`)},()=>{}),c=je(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=S.filterLogsByRelativeWindow(d,n.fromSeconds,n.toSeconds);return u=S.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);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(n),d=>{console.error(d.message)},()=>{}),c=je(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let n=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(n,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(n,e,t.logSize),t.isFollow?await this.runHilogFollow(n,e,t,i||""):await this.getHilogOnce(n,e,t,i||"")}async getCrashLog(e,t){m(`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"];m(`Running command: ${e} ${i.join(" ")}`);let o=await Pe(e,i),s=je(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return m(`Crash logs list output:
|
|
1227
1227
|
${o.stdout}`),o.stdout.split(`
|
|
1228
|
-
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return S.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>n?c.toLowerCase().includes(n.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){m(`Fetching latest crash log file: ${n}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await Pe(e,i),s=Ne(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as Fr,red as Yo}from"colorette";import Zl from"ora";function Ql(r){try{return S.parsePositiveInteger(r,"tail")}catch{throw new qo("`tail` must be a positive integer.")}}function zo(r,e){try{return S.parseDurationToSeconds(r,e)}catch{throw new qo(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function ed(r){if(r.to&&r.follow)throw new Error("`--to` cannot be used with `--follow`.");S.assertRelativeTimeRange(r.from,r.to)}async function td(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 nd(r,e,t,n){let i=S.filterLogsByRelativeWindow(r,t,n);return e.tail?S.getLastLines(i,e.tail):i}var rd=new Xl("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(Yo(r))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",Ql).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>zo(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>zo(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await id(r)});async function id(r){let e=Zl({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),ed(r);let n=r.from,i=r.to,o=await O.new(),s=new sn(o),a=await s.selectDevice(r.device);a||(t(),process.exit(1)),m(Fr(`deviceId: ${a}`)),m(Fr(`type: ${r.crash?"Crash logs":"Common logs"}`)),m(Fr("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await td(s,a,r,n,i);t(),r.crash&&c&&(c=nd(c,r,n,i)),c&&console.log(c)}catch(n){t(),console.error(Yo(n.message)),process.exit(1)}}var Go=rd;import Ct from"path";import fe from"fs";import _r from"process";import ns from"os";import{Command as gd}from"commander";import{green as Zo,red as $r,cyan as yd,yellow as Qo}from"colorette";import F from"fs-extra";import T from"path";import*as Jo from"os";import{fileURLToPath as od}from"url";var sd={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"}},ad=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function cd(){let r=import.meta.url,e=od(r);if(e.includes("dist")){let o=T.dirname(e),s=T.dirname(o);return T.join(s,"templates","application")}let t=T.dirname(e),n=T.dirname(t),i=T.dirname(n);return T.join(i,"templates","application")}function Ko(r,e){F.mkdirSync(e,{recursive:!0});for(let t of F.readdirSync(r,{withFileTypes:!0})){let n=T.join(r,t.name),i=T.join(e,t.name);if(t.isDirectory()){Ko(n,i);continue}F.existsSync(i)||(F.mkdirSync(T.dirname(i),{recursive:!0}),F.copyFileSync(n,i))}}function Et(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 ld(r,e){if(e===22)return;let t=sd[e];t&&(Et(T.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Et(T.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Et(T.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function dd(r){return ad.filter(t=>!F.existsSync(T.join(r,t))).length===0}function ud(){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 pd(r){return Jo.platform()==="darwin"?T.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):T.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function hd(r,e){let t=pd(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=T.join(t,i),a=T.join(r,o);F.existsSync(s)&&(F.mkdirSync(T.dirname(a),{recursive:!0}),F.copyFileSync(s,a))}return!0}function fd(r){let e=ud(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let i=T.join(r,n);F.mkdirSync(T.dirname(i),{recursive:!0}),F.writeFileSync(i,e)}}function md(r,e){e&&hd(r,e)||fd(r)}function Xo(r,e,t,n,i){let o=cd();if(!F.existsSync(o))throw new Error(`Template directory not found: ${o}`);F.mkdirSync(r,{recursive:!0}),Ko(o,r),md(r,i),Et(T.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Et(T.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),ld(r,n);let s=dd(r);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function vd(r){if(r.length<1||r.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function wd(r){if(r.length<7||r.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${r.length}`);if(r.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=r.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let n=0;n<e.length;n++){let i=e[n];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(n===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}function rs(r){if(ns.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function es(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=ns.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=rs(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 bd(r){let e=r,t=Ct.parse(r).root;for(;e!==t;){if(fe.existsSync(e))return e;e=Ct.dirname(e)}return fe.existsSync(t)?t:null}function ts(r){let e=bd(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{fe.accessSync(e,fe.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Ct.join(e,`.deveco_write_test_${Date.now()}`);try{fe.writeFileSync(t,"test"),fe.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function Sd(r){return`com.example.${r.toLowerCase()}`}function Pd(r,e){if(e){let i=rs(e),o=Ct.resolve(i);if(fe.existsSync(o)){if(fe.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else ts(o);return o}let t=_r.cwd(),n=Ct.join(t,r);if(fe.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return ts(n),n}function Ed(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let i=Number(r.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${r.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${r.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>n)throw new Error(`Invalid API version ${r.apiLevel}. Without DevEco Studio, supported range is API version 17-${n}`);return i}return t!==void 0?t:23}async function Cd(){try{return await O.new()}catch(r){console.error(Qo(`DevEco Studio not found: ${r.message}`)),console.log(Qo("Use placeholder API level instead."));return}}var Dd=new gd("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($r("Error: --app-name is required")),_r.exit(1));let e=r.appName;vd(e);let t=r.bundleName||Sd(e);wd(t),r.projectPath&&es(r.projectPath);let n=Pd(e,r.projectPath);es(n),console.log(yd("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await Cd(),o=Ed(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Xo(n,e,t,o,s);console.log(`
|
|
1229
|
-
`+
|
|
1230
|
-
Failed to create project.`)),console.error($r(t.message)),_r.exit(1)}}),is=Dd;import{Command as xd}from"commander";import{red as Od,cyan as us}from"colorette";import Id from"fs";import an from"path";import{cyan as Ad}from"colorette";import*as cn from"smol-toml";var Xe=Id.promises;async function kd(r){try{let e=await Xe.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${r}: ${e.message}`,{cause:e})}}async function Td(r){try{let e=await Xe.readFile(r,"utf8");return e.trim()===""?{}:cn.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function Md(r,e){let t=an.dirname(r);await Xe.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Xe.writeFile(r,n,"utf8")}async function Rd(r,e){let t=an.dirname(r);await Xe.mkdir(t,{recursive:!0});let n=cn.stringify(e);await Xe.writeFile(r,n,"utf8")}function os(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function ss(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 as(r,e){return r.format==="codex"?Td(e):kd(e)}async function cs(r,e,t){return r.format==="codex"?Rd(e,t):Md(e,t)}async function ls(r,e,t=!1){let n=be[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(be).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await as(n,n.globalConfigPath);if(os(i,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${n.globalConfigPath}.`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=Bt(n,void 0);return ss(i,n.mcpServersKey,se,o,t),await cs(n,n.globalConfigPath,i),console.log(`MCP server ${se} configured in ${n.globalConfigPath}.`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}async function Wr(r,e,t=!1){let n=be[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(be).join(", ")}`};let i=an.isAbsolute(n.projectConfigPath)?n.projectConfigPath:an.join(e,n.projectConfigPath);try{let o=await as(n,i);if(os(o,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=Bt(n,e);return ss(o,n.mcpServersKey,se,s,t),await cs(n,i,o),console.log(`MCP server ${se} configured in ${i}.`),{success:!0,configPath:i,agentName:r,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}function ds(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(Ad("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}var Ur="deveco-cli";async function Ld(r,e,t){if(r.customPath)return[await Lo(Ur,e,r.customPath,t.force)];let n=[...r.projectAgents.map(({project:s,agent:a})=>()=>Oo(Ur,e,s,a,t.force)),...r.agents.map(s=>()=>xo(Ur,e,s,t.force))],i=5,o=[];for(let s=0;s<n.length;s+=i){let a=n.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function Nd(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Wr(o,i,t);n.push(s)}for(let i of r.agents){let o=await Wr(i,e,t);n.push(o)}return n}async function Hd(r,e){let t=[];for(let n of r){if(!be[n])continue;let o=await ls(n,process.cwd(),e);t.push(o)}return t}async function jd(r,e,t){if(t.agent&&t.agent.split(",").map(d=>d.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let n=t.force??!1,i=r.projectAgents.filter(c=>c.agent!=="qoder"),o=r.agents.filter(c=>c!=="qoder"),s={...r,projectAgents:i,agents:o},a=e?await Nd(s,e,n):await Hd(s.agents,n);a.length>0&&(console.log(us("MCP Configuration:")),ds(a))}async function Fd(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}=bt(r.path,r.project,r.agent);t&&Ie(t,"Project directory",r.force),e&&Ie(e,"Directory",r.force);let n=await nn(r,e,t);if(r.mcp){await jd(n,t,r);return}let i=Fo(),o=await Ld(n,i,r);console.log(),o.length>0&&(console.log(us("Skill Installation:")),wt(o))}var $d=new xd("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async r=>{try{await Fd(r)}catch(e){console.error(Od(e.message)),process.exit(1)}}),ps=$d;import{Command as ep}from"commander";import{McpServer as Xu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Zu}from"@modelcontextprotocol/sdk/server/stdio.js";import*as dt from"path";import{z as ai}from"zod";var ln=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 Br(){return new ln}import*as we from"fs";import*as ie from"path";import{z as ii}from"zod";import C from"fs";import*as dn from"os";import*as P from"path";import _d from"json5";var Vr="Huawei";var Wd=3,gs=3,hs="DevEco Studio",ys={DevEcoStudio:"deveco_studio"};function zr(r){if(!C.existsSync(r)||!C.statSync(r).isDirectory())return!1;let e=C.existsSync(P.join(r,"build-profile.json5")),t=C.existsSync(P.join(r,"hvigorfile.js"))||C.existsSync(P.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=C.readFileSync(P.join(r,"build-profile.json5"),"utf-8");return _d.parse(n).app!==void 0}catch{return!1}}function vs(r,e,t){if(e>=t)return null;let n=Ud(r),i=Bd(n);if(i)return i;for(let o of n){let s=vs(o,e+1,t);if(s)return s}return null}function Ud(r){try{let e=C.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(P.join(r,n.name));return t}catch{return[]}}function Bd(r){for(let e of r)if(zr(e))return e;return null}function me(r){if(!r||r.trim()==="")return null;let e=P.resolve(r),t;try{t=C.realpathSync(e)}catch{t=e}if(!C.existsSync(t))return null;if(zr(t))return t;let n=t;for(let i=1;i<=3;i++){let o=P.dirname(n);if(o===n)break;if(zr(o))return o;n=o}if(C.statSync(t).isDirectory()){let i=vs(t,0,Wd);if(i)return i}return null}function ws(r){if(process.platform==="linux")return null;let e=r??He();if(!e)return null;let t;if(process.platform==="win32")t=P.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=P.join(e,"contents","plugins","openharmony");else return null;let n=P.join(t,"ace-server","out","index.js");return C.existsSync(n)?t:null}var Vd=["sdk","default","openharmony","native","llvm","bin","clangd"],qr=[".idea",".deveco","cxx","compile_commands.json"];function zd(r){return process.platform==="darwin"&&r.endsWith(".app")?P.join(r,"Contents"):r}function fs(r){let e=new Set,t=[r,zd(r)];for(let n of t){let i=P.join(n,...Vd);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function bs(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of fs(t.trim()))if(e.push(i),C.existsSync(i))return i}let n=r??He();if(n){for(let i of fs(n))if(e.push(i),C.existsSync(i))return i}return null}function un(r){return P.join(r,...qr)}function He(){if(process.platform==="win32"){let r=[P.join("C:\\Program Files",Vr,hs),P.join("C:\\Program Files (x86)",Vr,hs)];return ms(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",P.join(process.env.HOME??"","Applications","DevEco Studio.app")];return ms(r)}return null}function ms(r){for(let e of r)if(C.existsSync(e))return e;return null}function de(r){return process.platform==="darwin"?P.join(r,"Contents"):r}function qd(r){if(!r||!C.existsSync(r)||!Ss(r))return!1;let e=de(r);return[P.join(e,"plugins","openharmony"),P.join(e,"sdk"),P.join(e,"tools")].some(n=>C.existsSync(n))}function Ss(r){try{return C.statSync(r).isDirectory()}catch{return!1}}function Yr(r,e){return!r||!C.existsSync(r)?!1:e===ys.DevEcoStudio?qd(r):!1}function pn(r,e=ys.DevEcoStudio){if(!r)return"";if(Yr(r,e))return r;let t=Yd(r,e);if(t)return t;let n=Gd(r,e);return n||r}function Yd(r,e){let t=r;for(let n=0;n<gs;n++){let i=P.dirname(t);if(!i||i===t)break;if(Yr(i,e))return i;t=i}return null}function Gd(r,e){if(!C.existsSync(r)||!Ss(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=gs)continue;let o=Jd(n,i,e,t);if(o)return o}return null}function Jd(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=P.join(r,o.name);if(Yr(s,t))return s;n.push({p:s,depth:e+1})}return null}function Ps(r){return new Promise(e=>setTimeout(e,r))}var Kd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function hn(r){let e=P.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&Kd.has(e)}function Es(r){return P.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ue(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Gr(r){return ue(r)}function je(r){let e=Gr(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Dt(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),je(t)}}catch{}return r}function Cs(r){let e=[],t=r.lastIndexOf("file:/");if(t>=0){let n=r.slice(t).replace(/^file:\/+/,"");if(n){let i=n.startsWith("/")?`file://${n}`:`file:///${n}`,o=Dt(i);o!==r&&o!==Dt(r)&&e.push(o)}}return e}function fn(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??P.join(dn.homedir(),"AppData","Local");return P.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?P.join(dn.homedir(),"Library","Logs","devecocli-mcp-server"):P.join(dn.homedir(),".local","share","devecocli-mcp-server","logs")}function Ds(r,e){let t=Xd(e),n=Zd(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=Qd(t,r,s);return eu(e,a),i}function Xd(r){let e;try{e=C.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Zd(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 Qd(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 eu(r,e){try{C.mkdirSync(P.dirname(r),{recursive:!0})}catch{}try{C.writeFileSync(r,e.join(`
|
|
1228
|
+
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return S.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>n?c.toLowerCase().includes(n.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){m(`Fetching latest crash log file: ${n}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await Pe(e,i),s=je(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as $r,red as Go}from"colorette";import ed from"ora";function td(r){try{return S.parsePositiveInteger(r,"tail")}catch{throw new Yo("`tail` must be a positive integer.")}}function qo(r,e){try{return S.parseDurationToSeconds(r,e)}catch{throw new Yo(`${e} must be a valid duration string (e.g.,30s, 5m or 2.5m).Supported units: s and m.when specified in seconds(with \`s\` or as a raw number), the value must be an integer.`)}}function nd(r){if(r.to&&r.follow)throw new Error("`--to` cannot be used with `--follow`.");S.assertRelativeTimeRange(r.from,r.to)}async function rd(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 id(r,e,t,n){let i=S.filterLogsByRelativeWindow(r,t,n);return e.tail?S.getLastLines(i,e.tail):i}var od=new Ql("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(Go(r))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain crash logs").option("--level <level>","Log level filter: D, I, W, E, F").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",td).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120.",r=>qo(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120.",r=>qo(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await sd(r)});async function sd(r){let e=ed({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),nd(r);let n=r.from,i=r.to,o=await O.new(),s=new cn(o),a=await s.selectDevice(r.device);a||(t(),process.exit(1)),m($r(`deviceId: ${a}`)),m($r(`type: ${r.crash?"Crash logs":"Common logs"}`)),m($r("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await rd(s,a,r,n,i);t(),r.crash&&c&&(c=id(c,r,n,i)),c&&console.log(c)}catch(n){t(),console.error(Go(n.message)),process.exit(1)}}var Jo=od;import It from"path";import fe from"fs";import Wr from"process";import rs from"os";import{Command as wd}from"commander";import{green as Qo,red as _r,cyan as bd,yellow as es}from"colorette";import L from"fs-extra";import T from"path";import*as Ko from"os";import{fileURLToPath as ad}from"url";var cd={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"}},ld=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function dd(){let r=import.meta.url,e=ad(r);if(e.includes("dist")){let o=T.dirname(e),s=T.dirname(o);return T.join(s,"templates","application")}let t=T.dirname(e),n=T.dirname(t),i=T.dirname(n);return T.join(i,"templates","application")}function Xo(r,e){L.mkdirSync(e,{recursive:!0});for(let t of L.readdirSync(r,{withFileTypes:!0})){let n=T.join(r,t.name),i=T.join(e,t.name);if(t.isDirectory()){Xo(n,i);continue}L.existsSync(i)||(L.mkdirSync(T.dirname(i),{recursive:!0}),L.copyFileSync(n,i))}}function Dt(r,e){let t=L.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&L.writeFileSync(r,n,"utf-8")}function ud(r,e){if(e===22)return;let t=cd[e];t&&(Dt(T.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),Dt(T.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),Dt(T.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function pd(r){return ld.filter(t=>!L.existsSync(T.join(r,t))).length===0}function hd(){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 fd(r){return Ko.platform()==="darwin"?T.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):T.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function md(r,e){let t=fd(e);if(!L.existsSync(t))return!1;let n=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of n){let s=T.join(t,i),a=T.join(r,o);L.existsSync(s)&&(L.mkdirSync(T.dirname(a),{recursive:!0}),L.copyFileSync(s,a))}return!0}function gd(r){let e=hd(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let i=T.join(r,n);L.mkdirSync(T.dirname(i),{recursive:!0}),L.writeFileSync(i,e)}}function yd(r,e){e&&md(r,e)||gd(r)}function vd(r){let e=[T.join(r,"gitignore.txt"),T.join(r,"entry","gitignore.txt")];for(let t of e)L.existsSync(t)&&L.renameSync(t,t.replace(/\/gitignore\.txt$/,"/.gitignore"))}function Zo(r,e,t,n,i){let o=dd();if(!L.existsSync(o))throw new Error(`Template directory not found: ${o}`);L.mkdirSync(r,{recursive:!0}),Xo(o,r),vd(r),yd(r,i),Dt(T.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),Dt(T.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),ud(r,n);let s=pd(r);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function Sd(r){if(r.length<1||r.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error("Application name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Pd(r){if(r.length<7||r.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${r.length}`);if(r.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=r.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let n=0;n<e.length;n++){let i=e[n];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(n===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}function is(r){if(rs.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function ts(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=rs.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=is(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 Ed(r){let e=r,t=It.parse(r).root;for(;e!==t;){if(fe.existsSync(e))return e;e=It.dirname(e)}return fe.existsSync(t)?t:null}function ns(r){let e=Ed(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{fe.accessSync(e,fe.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=It.join(e,`.deveco_write_test_${Date.now()}`);try{fe.writeFileSync(t,"test"),fe.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function Cd(r){return`com.example.${r.toLowerCase()}`}function Dd(r,e){if(e){let i=is(e),o=It.resolve(i);if(fe.existsSync(o)){if(fe.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else ns(o);return o}let t=Wr.cwd(),n=It.join(t,r);if(fe.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return ns(n),n}function Id(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let i=Number(r.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${r.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${r.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>n)throw new Error(`Invalid API version ${r.apiLevel}. Without DevEco Studio, supported range is API version 17-${n}`);return i}return t!==void 0?t:23}async function Ad(){try{return await O.new()}catch(r){console.error(es(`DevEco Studio not found: ${r.message}`)),console.log(es("Use placeholder API level instead."));return}}var kd=new wd("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(_r("Error: --app-name is required")),Wr.exit(1));let e=r.appName;Sd(e);let t=r.bundleName||Cd(e);Pd(t),r.projectPath&&ts(r.projectPath);let n=Dd(e,r.projectPath);ts(n),console.log(bd("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await Ad(),o=Id(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Zo(n,e,t,o,s);console.log(`
|
|
1229
|
+
`+Qo("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(Qo("Template integrity check passed."))}catch(e){let t=e;console.error(_r(`
|
|
1230
|
+
Failed to create project.`)),console.error(_r(t.message)),Wr.exit(1)}}),os=kd;import{Command as Nd}from"commander";import{red as Hd,cyan as ps}from"colorette";import Td from"fs";import ln from"path";import{cyan as Md}from"colorette";import*as dn from"smol-toml";var Qe=Td.promises;async function Rd(r){try{let e=await Qe.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${r}: ${e.message}`,{cause:e})}}async function xd(r){try{let e=await Qe.readFile(r,"utf8");return e.trim()===""?{}:dn.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${r}: ${e.message}`,{cause:e})}}async function Od(r,e){let t=ln.dirname(r);await Qe.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Qe.writeFile(r,n,"utf8")}async function Ld(r,e){let t=ln.dirname(r);await Qe.mkdir(t,{recursive:!0});let n=dn.stringify(e);await Qe.writeFile(r,n,"utf8")}function ss(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function as(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 cs(r,e){return r.format==="codex"?xd(e):Rd(e)}async function ls(r,e,t){return r.format==="codex"?Ld(e,t):Od(e,t)}async function ds(r,e,t=!1){let n=be[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(be).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await cs(n,n.globalConfigPath);if(ss(i,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${n.globalConfigPath}.`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=zt(n,void 0);return as(i,n.mcpServersKey,se,o,t),await ls(n,n.globalConfigPath,i),console.log(`MCP server ${se} configured in ${n.globalConfigPath}.`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}async function Ur(r,e,t=!1){let n=be[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(be).join(", ")}`};let i=ln.isAbsolute(n.projectConfigPath)?n.projectConfigPath:ln.join(e,n.projectConfigPath);try{let o=await cs(n,i);if(ss(o,n.mcpServersKey,se)&&!t)return console.log(`MCP server ${se} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=zt(n,e);return as(o,n.mcpServersKey,se,s,t),await ls(n,i,o),console.log(`MCP server ${se} configured in ${i}.`),{success:!0,configPath:i,agentName:r,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}function us(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(Md("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}var Br="deveco-cli";async function jd(r,e,t){if(r.customPath)return[await No(Br,e,r.customPath,t.force)];let n=[...r.projectAgents.map(({project:s,agent:a})=>()=>Lo(Br,e,s,a,t.force)),...r.agents.map(s=>()=>Oo(Br,e,s,t.force))],i=5,o=[];for(let s=0;s<n.length;s+=i){let a=n.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function Fd(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Ur(o,i,t);n.push(s)}for(let i of r.agents){let o=await Ur(i,e,t);n.push(o)}return n}async function $d(r,e){let t=[];for(let n of r){if(!be[n])continue;let o=await ds(n,process.cwd(),e);t.push(o)}return t}async function _d(r,e,t){if(t.agent&&t.agent.split(",").map(d=>d.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let n=t.force??!1,i=r.projectAgents.filter(c=>c.agent!=="qoder"),o=r.agents.filter(c=>c!=="qoder"),s={...r,projectAgents:i,agents:o},a=e?await Fd(s,e,n):await $d(s.agents,n);a.length>0&&(console.log(ps("MCP Configuration:")),us(a))}async function Wd(r){if(r.skill&&r.mcp)throw new Error("Cannot use `--skill` and `--mcp` together. Use `--skill` for skill installation only, or `--mcp` for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=Pt(r.path,r.project,r.agent);t&&Ie(t,"Project directory",r.force),e&&Ie(e,"Directory",r.force);let n=await on(r,e,t);if(r.mcp){await _d(n,t,r);return}let i=$o(),o=await jd(n,i,r);console.log(),o.length>0&&(console.log(ps("Skill Installation:")),St(o))}var Ud=new Nd("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated; installs to all available agents if omitted").option("--project <path>","Project root directory for skill or MCP configuration").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite existing skill/MCP configuration").action(async r=>{try{await Wd(r)}catch(e){console.error(Hd(e.message)),process.exit(1)}}),hs=Ud;import{Command as rp}from"commander";import{McpServer as ep}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as tp}from"@modelcontextprotocol/sdk/server/stdio.js";import*as pt from"path";import{z as ci}from"zod";var un=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 Vr(){return new un}import*as we from"fs";import*as ie from"path";import{z as oi}from"zod";import C from"fs";import*as pn from"os";import*as P from"path";import Bd from"json5";var zr="Huawei";var Vd=3,ys=3,fs="DevEco Studio",vs={DevEcoStudio:"deveco_studio"};function qr(r){if(!C.existsSync(r)||!C.statSync(r).isDirectory())return!1;let e=C.existsSync(P.join(r,"build-profile.json5")),t=C.existsSync(P.join(r,"hvigorfile.js"))||C.existsSync(P.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=C.readFileSync(P.join(r,"build-profile.json5"),"utf-8");return Bd.parse(n).app!==void 0}catch{return!1}}function ws(r,e,t){if(e>=t)return null;let n=zd(r),i=qd(n);if(i)return i;for(let o of n){let s=ws(o,e+1,t);if(s)return s}return null}function zd(r){try{let e=C.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(P.join(r,n.name));return t}catch{return[]}}function qd(r){for(let e of r)if(qr(e))return e;return null}function me(r){if(!r||r.trim()==="")return null;let e=P.resolve(r),t;try{t=C.realpathSync(e)}catch{t=e}if(!C.existsSync(t))return null;if(qr(t))return t;let n=t;for(let i=1;i<=3;i++){let o=P.dirname(n);if(o===n)break;if(qr(o))return o;n=o}if(C.statSync(t).isDirectory()){let i=ws(t,0,Vd);if(i)return i}return null}function bs(r){if(process.platform==="linux")return null;let e=r??Fe();if(!e)return null;let t;if(process.platform==="win32")t=P.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=P.join(e,"contents","plugins","openharmony");else return null;let n=P.join(t,"ace-server","out","index.js");return C.existsSync(n)?t:null}var Yd=["sdk","default","openharmony","native","llvm","bin","clangd"],Yr=[".idea",".deveco","cxx","compile_commands.json"];function Gd(r){return process.platform==="darwin"&&r.endsWith(".app")?P.join(r,"Contents"):r}function ms(r){let e=new Set,t=[r,Gd(r)];for(let n of t){let i=P.join(n,...Yd);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function Ss(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of ms(t.trim()))if(e.push(i),C.existsSync(i))return i}let n=r??Fe();if(n){for(let i of ms(n))if(e.push(i),C.existsSync(i))return i}return null}function hn(r){return P.join(r,...Yr)}function Fe(){if(process.platform==="win32"){let r=[P.join("C:\\Program Files",zr,fs),P.join("C:\\Program Files (x86)",zr,fs)];return gs(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",P.join(process.env.HOME??"","Applications","DevEco Studio.app")];return gs(r)}return null}function gs(r){for(let e of r)if(C.existsSync(e))return e;return null}function de(r){return process.platform==="darwin"?P.join(r,"Contents"):r}function Jd(r){if(!r||!C.existsSync(r)||!Ps(r))return!1;let e=de(r);return[P.join(e,"plugins","openharmony"),P.join(e,"sdk"),P.join(e,"tools")].some(n=>C.existsSync(n))}function Ps(r){try{return C.statSync(r).isDirectory()}catch{return!1}}function Gr(r,e){return!r||!C.existsSync(r)?!1:e===vs.DevEcoStudio?Jd(r):!1}function fn(r,e=vs.DevEcoStudio){if(!r)return"";if(Gr(r,e))return r;let t=Kd(r,e);if(t)return t;let n=Xd(r,e);return n||r}function Kd(r,e){let t=r;for(let n=0;n<ys;n++){let i=P.dirname(t);if(!i||i===t)break;if(Gr(i,e))return i;t=i}return null}function Xd(r,e){if(!C.existsSync(r)||!Ps(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=ys)continue;let o=Zd(n,i,e,t);if(o)return o}return null}function Zd(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=P.join(r,o.name);if(Gr(s,t))return s;n.push({p:s,depth:e+1})}return null}function Es(r){return new Promise(e=>setTimeout(e,r))}var Qd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function mn(r){let e=P.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&Qd.has(e)}function Cs(r){return P.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ue(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Jr(r){return ue(r)}function $e(r){let e=Jr(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function At(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)),$e(t)}}catch{}return r}function Ds(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=At(i);o!==r&&o!==At(r)&&e.push(o)}}return e}function gn(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??P.join(pn.homedir(),"AppData","Local");return P.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?P.join(pn.homedir(),"Library","Logs","devecocli-mcp-server"):P.join(pn.homedir(),".local","share","devecocli-mcp-server","logs")}function Is(r,e){let t=eu(e),n=tu(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=nu(t,r,s);return ru(e,a),i}function eu(r){let e;try{e=C.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function tu(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 nu(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 ru(r,e){try{C.mkdirSync(P.dirname(r),{recursive:!0})}catch{}try{C.writeFileSync(r,e.join(`
|
|
1231
1231
|
`)+`
|
|
1232
|
-
`,"utf8")}catch{}}function
|
|
1233
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);I.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{I.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},K=null;function
|
|
1232
|
+
`,"utf8")}catch{}}function Kr(r,e,t="[Cleanup]"){try{let n=P.dirname(r);if(!C.existsSync(n))return;let i=Date.now();for(let o of C.readdirSync(n,{withFileTypes:!0}))o.isDirectory()&&iu(P.join(n,o.name),i,e,t)}catch{}}function iu(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}`)}}function yn(r){let e=r.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",n=P.join(e,"node",t);return C.existsSync(n)||process.platform!=="win32"&&(n=P.join(e,"node","bin","node"),C.existsSync(n))?n:process.execPath??"node"}import*as I from"fs";import*as wn from"path";var As="mcp-server.log",ou="mcp-server",su={maxSize:10*1024*1024,maxFiles:4},Xr=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...su,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=gn(),this.currentLogFile=wn.join(this.logDir,As),I.existsSync(this.logDir)||I.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 wn.join(this.logDir,`${ou}-${e}.log.${t}`)}fileExists(e){try{return I.accessSync(e,I.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=I.readdirSync(this.logDir),t=[];for(let i of e)if(i===As||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=wn.join(this.logDir,i),s=I.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{I.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)&&I.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)&&I.renameSync(o,s)}let n=this.getRotatedFileName(e,1);I.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=I.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=I.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{I.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
|
|
1233
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);I.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{I.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},K=null;function Zr(r=!1){K&&K.dispose(),K=new Xr(r)}function ks(){K&&(K.dispose(),K=null)}function Ts(){K&&K.flush()}function Ms(){return K?.getLogFilePath()??null}function Rs(){return K?.getLogDirectory()??null}function vn(){return K||Zr(!1),K}var f={debug:(r,...e)=>vn().debug(r,...e),info:(r,...e)=>vn().info(r,...e),warn:(r,...e)=>vn().warn(r,...e),error:(r,...e)=>vn().error(r,...e)};function xs(r){return"method"in r&&!("id"in r)}import{spawn as lu}from"child_process";import{EventEmitter as du}from"events";import*as tt from"fs";import*as Ws from"path";import*as Os from"util";var Qr="";function Ls(r){if(!r||r==="auto"||r==="stdout"||r==="none"){Qr="";return}Qr=r}function Ns(){return Qr||(Rs()??"")}function bn(r,...e){if(e.length===0)return r;try{return Os.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var l={info(r,...e){f.info(`[lsp] ${bn(r,...e)}`)},warn(r,...e){f.warn(`[lsp] ${bn(r,...e)}`)},error(r,...e){f.error(`[lsp] ${bn(r,...e)}`)},debug(r,...e){f.debug(`[lsp] ${bn(r,...e)}`)}};import*as Tt from"fs";import*as Mt from"os";import*as et from"path";import cu from"json5";var au={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"},w={...au,...Sn},M="2.0",X={EXIT:"exit",INITIALIZED:"initialized",EMPTY:"empty",ON_DID_CHANGE_PACKAGE_DEPENDENCIES:"onDidChangePackageDependencies",ON_ASYNC_DID_OPEN:"onAsyncDidOpen",ON_ASYNC_DID_CHANGE:"onAsyncDidChange",DID_CLOSE:"didClose",ON_ASYNC_HOVER:"onAsyncHover",ON_ASYNC_DEFINITION:"onAsyncDefinition",ON_ASYNC_FIND_USAGES:"onAsyncFindUsages"};var Hs=8192,ei=100,js=.03,Fs=.7,kt=900*1e3;function Y(r){if(!Tt.existsSync(r))return null;try{let e=Tt.readFileSync(r,"utf-8");return e.trim()?cu.parse(e):null}catch{return null}}function $s(r,e){let t=Math.floor(Mt.totalmem()/1048576),n=Math.floor(t*Fs),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Hs,r>ei&&(i+=(r-ei)*js*1024),o=`formula(moduleCount=${r})`);let s=n>0&&i>n;s&&(i=n);let a=Math.round(i);return l.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${n}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function ge(r){try{let e=et.resolve(r),t=new URL(`file://${e}`).toString();if(Mt.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 Pn(r){return r&&r.replace(/\\/g,"/")}function _(r){let e=et.normalize(r).replace(/\\/g,"/");if(Mt.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function _s(r){return et.join(r,"build-profile.json5")}var En=class extends du{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Ws.join(this.config.logPath,"lspLog");return tt.existsSync(t)||tt.mkdirSync(t,{recursive:!0}),tt.existsSync(this.config.indexingDataLocation)||tt.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let n=this.ensureDirectories();l.info(`[LspClient] serverMaxSize=${t}MB`);let i=_(n),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];l.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";l.info(`[LspClient] nodePath: ${s}`),this.process=lu(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
|
|
1234
1234
|
\r
|
|
1235
1235
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
|
|
1236
1236
|
\r
|
|
1237
|
-
`);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 Pn=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 En=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 ei(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)}},ei=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var Cn=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 g(r){return typeof r=="object"&&r!==null}function ti(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}function cu(r){if(!g(r))return!1;let e=r.textDocument;return g(e)&&typeof e.uri=="string"}function lu(r){return g(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}function du(r){return g(r)&&typeof r.moduleName=="string"&&typeof r.current=="number"&&typeof r.total=="number"?`indexing module '${r.moduleName}', ${r.current} of total ${r.total} modules`:`params=${JSON.stringify(r??null)}`}var Dn=class r{client;isInitialized=!1;stopOnce=null;callbacks=new Cn;requestCallbacks=new Pn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new Sn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{l.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.EXIT,params:{}}),X.EXIT),l.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),l.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(w.BROADCAST),this.callbacks.register(w.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(w.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(w.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(w.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.INITIALIZED,params:{editors:e}}),X.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:M,id:0,result:{}}),X.EMPTY)}sendAsyncRequest(e,t,n,i){if(!g(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!cu(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=ge(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;l.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(l.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!lu(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),w.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!g(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){l.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;l.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),X.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=ge(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new En(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,wn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),X.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=ge(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,wn.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),X.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=ge(e);l.info(`[LSP] didClose, uri: ${n}`);let i=this.diagnosticMap.get(n);if(!t&&(!i||i.isFromEditor)){l.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.DID_CLOSE,params:{textDocument:{uri:n}}}),X.DID_CLOSE)}getDiagnosticMessage(e){let t=ge(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,w.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:M,method:w.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case w.MODULE_INIT_FINISH:return l.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(w.MODULE_INIT_FINISH),this.callbacks.unregister(w.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case w.INDEXING_PROGRESS_UPDATE:return l.info(`[LSP] onIndexingProgressUpdate: ${du(t.params)}`),this.callbacks.invoke(w.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case w.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case w.ON_PACKAGE_CHANGE_FINISH:l.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case w.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case w.ON_ASYNC_HOVER:this.handleAsyncResponse(t,w.HOVER);return;case w.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,w.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case w.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,w.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;g(t)&&g(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){l.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:M,method:w.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(!g(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,w.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,w.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 qn from"path";import*as xn from"path";var In=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var An=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var kn=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Tn=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Mn=class{typeSetting=new kn;parameterNames=new Tn};var Rn=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=$(xn.dirname(t)),this.indexingDataLocation=$(i),this.loggerPath=$(xn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new In;gutterIconsSetting=new An;inlayHintsSetting=new Mn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Ws from"path";var Tt=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($(Ws.join(e,"src","main","resources")))}};var uu="OS",et=class{deviceType=[5];aceLoaderPath;modulePath;jsComponentType="declarative";sdkJsPath;compatibleSdkVersion;compatibleSdkLevel;compileSdkLevel;compileSdkVersion="6.0.1.112";compileSdkType="Release";syscap={NDeviceSysCaps:[],addedSysCaps:[]};apiType="stageMode";hosSdkPath;runtimeOs=`Harmony${uu}`;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 Tt(e)):this.buildProfileParam=new Tt}toString(){return JSON.stringify(this)}};var tt=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Z from"path";import*as it from"fs";var On=class{modulePath;dependencies={};dynamicDependencies={}};var Fe=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var nt=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as ye from"path";import*as Ln from"fs";var rt=class{name="";version="";storePath="";dependencyPath="";path=""};var D={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:te.OH_PACKAGE_JSON5},Mt=`${D.HVIGOR_CACHE}/${D.DEPENDENCY}`,$e=`${D.DEPENDENCY}${D.JSON5}`,$v=te.SYNC_OUTPUT_PATH;var Rt=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=ye.join(this.dependencyPath,D.OH_PACKAGE_JSON5),n=Y(t);n&&(this.dependencies=this.getDependencyList(n,D.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,D.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,D.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!g(e))return n;let i=e[t];if(!g(i))return n;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){l.error(`${o} package dependency value is not String ${t}`);continue}let a=new rt;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,i){if(!(!e||!t))try{let o=ye.normalize(ye.join(this.modulePath,D.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)),ye.isAbsolute(s)){n.dependencyPath=o;return}if(!i){let a=ye.resolve(this.modulePath,s);o=S.ensurePathWithinRoot(this.projectPath,a)}Ln.existsSync(o)&&Ln.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as xt from"fs";import*as Ot from"path";import pu from"json5";var Nn=class r{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let n=this.validateLockFile(t);return n.valid?(this.lockFileCache={modules:n.modules,storePathMap:this.parseStorePathMap(n.packages)},!0):!1}getLockFilePath(){return Ot.join(this.projectPath,D.OH_MODULES_PATH,D.OHPM_PATH,D.LOCK_JSON5_FILE)}readLockFile(e){if(!xt.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=xt.readFileSync(e,"utf8"),n=pu.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(!g(e))return l.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return l.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(l.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,D.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,D.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,D.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!g(e))return t;for(let[n,i]of Object.entries(e)){if(!g(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(!g(e))return[];for(let[i,o]of Object.entries(e))if(g(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(!g(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!g(s))return[];for(let[a,c]of Object.entries(s)){if(!g(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",y=new rt;y.name=a,y.version=u.startsWith(r.FILE_DEPENDENCY_PREFIX)?u.substring(r.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(y,n,a,d,u);let k=`${a}@${u}`;this.storePathMap.has(k)&&(y.storePath=this.storePathMap.get(k)||""),o.push(y)}return o}parseDependencyPath(e,t,n,i,o){let s=S.resolvePathWithinRoot(this.projectPath,Ot.join(t,D.OH_MODULES_PATH,n));try{let a=o.startsWith(r.FILE_DEPENDENCY_PREFIX)?o.substring(r.FILE_DEPENDENCY_PREFIX.length):o,c=Ot.isAbsolute(a)?S.ensurePathWithinRoot(this.projectPath,a):S.resolvePathWithinRoot(this.projectPath,a);xt.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){l.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var _e=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=$s(this.projectRoot);try{let t=Y(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Us(r){return g(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Lt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new _e(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,n=Z.join(t,Mt),i=Z.join(n,$e);if(!it.existsSync(n)||!it.existsSync(i)){let c="Dependency map or JSON not found";return l.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return l.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let d=s[c];Us(d)&&(this.parseSingleModule(d,n,o,e),(c+1)%100===0&&l.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return l.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=Z.join(n,Mt),o=Z.join(i,$e);if(!it.existsSync(i)||!it.existsSync(o))return l.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(d=>d.trim()).filter(Boolean)):null,a=new nt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return l.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let d of c){if(!Us(d))continue;let u=d.name;if(s&&!s.has(u))continue;let y=S.resolvePathWithinRoot(this.projectPath,d.srcPath),k=Z.join(i,u),_=$(y),J=this.buildModuleDependencies(u,_,k,a);J.moduleName=u,t.push(J)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=S.resolvePathWithinRoot(this.projectPath,e.srcPath),a=Z.join(t,o),c=$(s),d=new et(c),u=this.buildModuleDependencies(o,c,a,n);this.parseModuleJson5(c,d);let y=this.parseMainPages(c);this.parseSdkJson(d),this.parseCompatibleSdkVersion(d),d.moduleName=o,d.moduleType=o,d.packageName=o,d.moduleDependencies=u,d.moduleJsonParam=new tt(y),i.push(d)}buildModuleDependencies(e,t,n,i){let o=new nt(this.projectPath,e,t);Rt.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 On;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 Fe(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Fe(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=Z.join(e,D.OH_PACKAGE_JSON5);if(!it.existsSync(n))return;Rt.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new Nn(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let n=Z.join(e,"src","main","module.json5"),i=Y(n);if(!g(i)||!g(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(g(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)g(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=Z.join(e,"src","main","resources","base","profile","main_pages.json"),n=Y(t);return!g(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();!g(t)||!g(t.data)||(typeof t.data.apiVersion=="string"&&(e.compileSdkLevel=t.data.apiVersion),typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version))}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=Z.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Y(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!g(t)||!g(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let n=t.app.products[0];if(!g(n)||typeof n.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(n.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Z.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Y(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!g(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 Hn=class{constructor(e=[]){this.valueSet=e}valueSet};var ot=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Bs=(v=>(v[v.File=1]="File",v[v.Module=2]="Module",v[v.Namespace=3]="Namespace",v[v.Package=4]="Package",v[v.Class=5]="Class",v[v.Method=6]="Method",v[v.Property=7]="Property",v[v.Field=8]="Field",v[v.Constructor=9]="Constructor",v[v.Enum=10]="Enum",v[v.Interface=11]="Interface",v[v.Function=12]="Function",v[v.Variable=13]="Variable",v[v.Constant=14]="Constant",v[v.String=15]="String",v[v.Number=16]="Number",v[v.Boolean=17]="Boolean",v[v.Array=18]="Array",v[v.Object=19]="Object",v[v.Key=20]="Key",v[v.Null=21]="Null",v[v.EnumMember=22]="EnumMember",v[v.Struct=23]="Struct",v[v.Event=24]="Event",v[v.Operator=25]="Operator",v[v.TypeParameter=26]="TypeParameter",v))(Bs||{}),Vs=()=>Object.values(Bs).filter(r=>typeof r=="number");var jn=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Fn=class{applyEdit=!0;workspaceEdit=new jn;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Hn(Vs());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new ot;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var $n=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var _n=class{constructor(e=[]){this.valueSet=e}valueSet};var Wn=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var zs=(b=>(b[b.Text=1]="Text",b[b.Method=2]="Method",b[b.Function=3]="Function",b[b.Constructor=4]="Constructor",b[b.Field=5]="Field",b[b.Variable=6]="Variable",b[b.Class=7]="Class",b[b.Interface=8]="Interface",b[b.Module=9]="Module",b[b.Property=10]="Property",b[b.Unit=11]="Unit",b[b.Value=12]="Value",b[b.Enum=13]="Enum",b[b.Keyword=14]="Keyword",b[b.Snippet=15]="Snippet",b[b.Color=16]="Color",b[b.File=17]="File",b[b.Reference=18]="Reference",b[b.Folder=19]="Folder",b[b.EnumMember=20]="EnumMember",b[b.Constant=21]="Constant",b[b.Struct=22]="Struct",b[b.Event=23]="Event",b[b.Operator=24]="Operator",b[b.TypeParameter=25]="TypeParameter",b))(zs||{}),qs=()=>Object.values(zs).filter(r=>typeof r=="number");var Un=class{completionItemKind=new _n(qs());completionItem=new Wn;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Bn=class{synchronization=new $n;completion=new Un;hover={contentFormat:{},dynamicRegistration:{}};signatureHelp={signatureInformation:{},contextSupport:{},dynamicRegistration:{}};references={dynamicRegistration:{}};documentHighlight={dynamicRegistration:!0};documentSymbol=null;formatting={dynamicRegistration:{}};rangeFormatting={dynamicRegistration:{}};onTypeFormatting={dynamicRegistration:{}};declaration={};definition={linkSupport:{},dynamicRegistration:{}};codeLens=null;documentLink={tooltipSupport:{},dynamicRegistration:{}};colorProvider=null;rename={prepareSupport:!0,prepareSupportDefaultBehavior:null,honorsChangeAnnotations:null,dynamicRegistrationSupport:null};publishDiagnostics=null;foldingRage=null;typeHierarchy=null;callHierarchy={dynamicRegistration:{}};selectionRange=null;semanticTokens=new ot;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Vn=class{workspace=new Fn;textDocument=new Bn;notebookDocument=null;window=null;general=null;experimental=null};var zn=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function st(r){return g(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function Ys(r){return g(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function Gs(r){if(!g(r)||typeof r.text!="string")return!1;let e=r.range;return g(e)?st(e.start)&&st(e.end):!1}var Yn=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=qn.resolve(t,"ace-server","out","index.js"),this.logPath=Ls(),this.indexLogPath=i||this.logPath,this.messageHandle=new Dn({serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath}),this.messageHandle.setBroadcastToClients(s=>this.onLspMessage(s))}sdkPath;rootUri;nodeMaxOldSpaceSize;messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let n=!1;try{l.info(`serverPath: ${this.serverPath}`),l.info(`rootUri: ${this.rootUri}`),l.info(`sdkPath: ${this.sdkPath}`),l.info(`logPath: ${this.logPath}`);let i=ge(this.rootUri),o=new Rn(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Lt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let d=Fs(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new zn(i,o,new Vn),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:M,method:w.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,y)=>{this.messageHandle.onIndexingProgressUpdate(y),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",It),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=ge(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=g(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:M,method:n,params:{uri:typeof o.uri=="string"?o.uri:t,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(a=>typeof a=="string"):[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(n,i)=>{l.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${n}`);let o={jsonrpc:M,id:e,result:g(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Lt(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,y)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,y)}),this.markAddAndDeleteInDeps(a,d,(u,y)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,y)})}}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 Fe({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new et(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new tt([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let i=new Map(n.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=bn(qn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=bn(qn.join(t,"default/openharmony/ets/api")),o=bn(qn.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case w.HOVER:this.handleHoverRequest(e);break;case w.DEFINITION:this.handleDefinitionRequest(e);break;case w.REFERENCES:this.handleReferencesRequest(e);break;default:l.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!g(n)||typeof n.uri!="string"||!st(i)){l.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof o!="number"){l.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(w.ON_ASYNC_HOVER,t,o,X.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!g(n)||typeof n.uri!="string"||!st(i)){l.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(w.ON_ASYNC_DEFINITION,t,o,X.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!g(n)||typeof n.uri!="string"||!st(i)){l.error("Invalid client textDocument/references, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(w.ON_ASYNC_FIND_USAGES,t,o,X.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!Rs(e)){l.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case w.DID_OPEN:this.handleDidOpenNotification(e);break;case w.DID_CHANGE:this.handleDidChangeNotification(e);break;case w.DID_CLOSE:this.handleDidCloseNotification(e);break;case w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case w.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:l.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!Ys(n)||!ti(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(!g(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!g(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(Gs)){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(!g(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!g(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(!g(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(!g(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 ve from"fs";import*as Ae from"path";import{createHash as hu}from"crypto";import{EventEmitter as fu}from"events";var Gn=class extends fu{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),n=new Set(this.watchers.keys());for(let i of t)n.has(i)||this.watchFile(i);for(let i of n)t.has(i)||(this.unwatchFile(i),l.info(`[ConfigFileWatcher] Stopped watching: ${i}`));l.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!ve.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=ve.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=S.resolvePathWithinRoot(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=S.resolvePathWithinRoot(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=S.resolvePathWithinRoot(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=S.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){l.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,l.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=Ae.join(this.projectRoot,D.OH_PACKAGE_JSON5);ve.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=S.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Ae.join(s,D.OH_PACKAGE_JSON5);ve.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Ae.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=ve.readFileSync(t,"utf-8");return hu("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=ve.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:Ae.basename(t),relativePath:Ae.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 ke from"fs";import*as re from"path";import{createHash as mu}from"crypto";import{EventEmitter as gu}from"events";var Jn=class extends gu{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=re.join(t,Mt)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!ke.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=ke.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 $(re.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===D.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===$e)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=re.join(this.depMapDir,n);ke.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=re.join(this.depMapDir,D.OH_PACKAGE_JSON5),n=re.join(this.depMapDir,$e),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:re.join(this.depMapDir,s.name,D.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!ke.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=re.join(this.depMapDir,$e);try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of n)i.add(o.info.newName);return i}emitIncrementalReload(t,n,i,o,s){l.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(l.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){l.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(n,i,o,s,a);for(let d of o)s.delete(d);if(o.size===0&&s.size===0&&a.length===0){l.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return $(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=re.join(this.depMapDir,a.name,D.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=re.join(this.depMapDir,o,D.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=ke.readFileSync(t,"utf-8");return mu("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as yu}from"child_process";import*as Zn from"path";import*as Xn from"fs";var vu=600*1e3;function wu(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function bu(r){let e=[],t=[];return r.stdout?.on("data",n=>{e.push(n.toString())}),r.stderr?.on("data",n=>{t.push(n.toString())}),{stdout:e,stderr:t}}function Kn(r){return r.join("")}function Su(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1237
|
+
`);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 Cn=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 Dn=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 ti(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)}},ti=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var In=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 g(r){return typeof r=="object"&&r!==null}function ni(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}function uu(r){if(!g(r))return!1;let e=r.textDocument;return g(e)&&typeof e.uri=="string"}function pu(r){return g(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}function hu(r){return g(r)&&typeof r.moduleName=="string"&&typeof r.current=="number"&&typeof r.total=="number"?`indexing module '${r.moduleName}', ${r.current} of total ${r.total} modules`:`params=${JSON.stringify(r??null)}`}var An=class r{client;isInitialized=!1;stopOnce=null;callbacks=new In;requestCallbacks=new Cn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new En(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{l.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.EXIT,params:{}}),X.EXIT),l.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),l.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(w.BROADCAST),this.callbacks.register(w.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(w.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(w.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(w.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.INITIALIZED,params:{editors:e}}),X.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:M,id:0,result:{}}),X.EMPTY)}sendAsyncRequest(e,t,n,i){if(!g(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!uu(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=ge(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;l.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(l.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!pu(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),w.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!g(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){l.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;l.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),X.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=ge(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Dn(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,Sn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),X.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=ge(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:M,method:w.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),X.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=ge(e);l.info(`[LSP] didClose, uri: ${n}`);let i=this.diagnosticMap.get(n);if(!t&&(!i||i.isFromEditor)){l.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:w.DID_CLOSE,params:{textDocument:{uri:n}}}),X.DID_CLOSE)}getDiagnosticMessage(e){let t=ge(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,w.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:M,method:w.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case w.MODULE_INIT_FINISH:return l.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(w.MODULE_INIT_FINISH),this.callbacks.unregister(w.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case w.INDEXING_PROGRESS_UPDATE:return l.info(`[LSP] onIndexingProgressUpdate: ${hu(t.params)}`),this.callbacks.invoke(w.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case w.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case w.ON_PACKAGE_CHANGE_FINISH:l.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case w.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case w.ON_ASYNC_HOVER:this.handleAsyncResponse(t,w.HOVER);return;case w.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,w.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case w.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,w.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;g(t)&&g(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){l.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:M,method:w.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(!g(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,w.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,w.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 Gn from"path";import*as Ln from"path";var kn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Tn=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Mn=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Rn=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var xn=class{typeSetting=new Mn;parameterNames=new Rn};var On=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=_(Ln.dirname(t)),this.indexingDataLocation=_(i),this.loggerPath=_(Ln.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new kn;gutterIconsSetting=new Tn;inlayHintsSetting=new xn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Us from"path";var Rt=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(_(Us.join(e,"src","main","resources")))}};var fu="OS",nt=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${fu}`;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 Rt(e)):this.buildProfileParam=new Rt}toString(){return JSON.stringify(this)}};var rt=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Z from"path";import*as st from"fs";var Nn=class{modulePath;dependencies={};dynamicDependencies={}};var _e=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 it=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 ye from"path";import*as Hn from"fs";var ot=class{name="";version="";storePath="";dependencyPath="";path=""};var D={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:te.OH_PACKAGE_JSON5},xt=`${D.HVIGOR_CACHE}/${D.DEPENDENCY}`,We=`${D.DEPENDENCY}${D.JSON5}`,Uv=te.SYNC_OUTPUT_PATH;var Ot=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=ye.join(this.dependencyPath,D.OH_PACKAGE_JSON5),n=Y(t);n&&(this.dependencies=this.getDependencyList(n,D.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,D.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,D.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!g(e))return n;let i=e[t];if(!g(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 ot;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=ye.normalize(ye.join(this.modulePath,D.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)),ye.isAbsolute(s)){n.dependencyPath=o;return}if(!i){let a=ye.resolve(this.modulePath,s);o=S.ensurePathWithinRoot(this.projectPath,a)}Hn.existsSync(o)&&Hn.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as Lt from"fs";import*as Nt from"path";import mu from"json5";var jn=class r{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let n=this.validateLockFile(t);return n.valid?(this.lockFileCache={modules:n.modules,storePathMap:this.parseStorePathMap(n.packages)},!0):!1}getLockFilePath(){return Nt.join(this.projectPath,D.OH_MODULES_PATH,D.OHPM_PATH,D.LOCK_JSON5_FILE)}readLockFile(e){if(!Lt.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Lt.readFileSync(e,"utf8"),n=mu.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(!g(e))return l.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return l.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(l.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,D.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,D.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,D.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!g(e))return t;for(let[n,i]of Object.entries(e)){if(!g(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(!g(e))return[];for(let[i,o]of Object.entries(e))if(g(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(!g(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!g(s))return[];for(let[a,c]of Object.entries(s)){if(!g(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",y=new ot;y.name=a,y.version=u.startsWith(r.FILE_DEPENDENCY_PREFIX)?u.substring(r.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(y,n,a,d,u);let k=`${a}@${u}`;this.storePathMap.has(k)&&(y.storePath=this.storePathMap.get(k)||""),o.push(y)}return o}parseDependencyPath(e,t,n,i,o){let s=S.resolvePathWithinRoot(this.projectPath,Nt.join(t,D.OH_MODULES_PATH,n));try{let a=o.startsWith(r.FILE_DEPENDENCY_PREFIX)?o.substring(r.FILE_DEPENDENCY_PREFIX.length):o,c=Nt.isAbsolute(a)?S.ensurePathWithinRoot(this.projectPath,a):S.resolvePathWithinRoot(this.projectPath,a);Lt.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){l.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var Ue=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=_s(this.projectRoot);try{let t=Y(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Bs(r){return g(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Ht=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Ue(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,n=Z.join(t,xt),i=Z.join(n,We);if(!st.existsSync(n)||!st.existsSync(i)){let c="Dependency map or JSON not found";return l.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new it(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return l.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let d=s[c];Bs(d)&&(this.parseSingleModule(d,n,o,e),(c+1)%100===0&&l.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return l.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=Z.join(n,xt),o=Z.join(i,We);if(!st.existsSync(i)||!st.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 it(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(!Bs(d))continue;let u=d.name;if(s&&!s.has(u))continue;let y=S.resolvePathWithinRoot(this.projectPath,d.srcPath),k=Z.join(i,u),H=_(y),J=this.buildModuleDependencies(u,H,k,a);J.moduleName=u,t.push(J)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=S.resolvePathWithinRoot(this.projectPath,e.srcPath),a=Z.join(t,o),c=_(s),d=new nt(c),u=this.buildModuleDependencies(o,c,a,n);this.parseModuleJson5(c,d);let y=this.parseMainPages(c);this.parseSdkJson(d),this.parseCompatibleSdkVersion(d),d.moduleName=o,d.moduleType=o,d.packageName=o,d.moduleDependencies=u,d.moduleJsonParam=new rt(y),i.push(d)}buildModuleDependencies(e,t,n,i){let o=new it(this.projectPath,e,t);Ot.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 Nn;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 _e(o);for(let o of e.finalDynamicDependencies)i[o.name]=new _e(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=Z.join(e,D.OH_PACKAGE_JSON5);if(!st.existsSync(n))return;Ot.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=this.getLockJson5Parser();t.parseDependencies(e.moduleName)?(e.finalDependencies=t.finalDependencies,e.finalDevDependencies=t.finalDevDependencies,e.finalDynamicDependencies=t.finalDynamicDependencies):(e.finalDependencies=e.dependencies,e.finalDevDependencies=e.devDependencies,e.finalDynamicDependencies=e.dynamicDependencies)}getLockJson5Parser(){return this.lockJson5Parser||(this.lockJson5Parser=new jn(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let n=Z.join(e,"src","main","module.json5"),i=Y(n);if(!g(i)||!g(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(g(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)g(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=Z.join(e,"src","main","resources","base","profile","main_pages.json"),n=Y(t);return!g(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();!g(t)||!g(t.data)||(typeof t.data.apiVersion=="string"&&(e.compileSdkLevel=t.data.apiVersion),typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version))}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=Z.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Y(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!g(t)||!g(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let n=t.app.products[0];if(!g(n)||typeof n.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(n.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Z.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Y(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!g(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 Fn=class{constructor(e=[]){this.valueSet=e}valueSet};var at=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Vs=(v=>(v[v.File=1]="File",v[v.Module=2]="Module",v[v.Namespace=3]="Namespace",v[v.Package=4]="Package",v[v.Class=5]="Class",v[v.Method=6]="Method",v[v.Property=7]="Property",v[v.Field=8]="Field",v[v.Constructor=9]="Constructor",v[v.Enum=10]="Enum",v[v.Interface=11]="Interface",v[v.Function=12]="Function",v[v.Variable=13]="Variable",v[v.Constant=14]="Constant",v[v.String=15]="String",v[v.Number=16]="Number",v[v.Boolean=17]="Boolean",v[v.Array=18]="Array",v[v.Object=19]="Object",v[v.Key=20]="Key",v[v.Null=21]="Null",v[v.EnumMember=22]="EnumMember",v[v.Struct=23]="Struct",v[v.Event=24]="Event",v[v.Operator=25]="Operator",v[v.TypeParameter=26]="TypeParameter",v))(Vs||{}),zs=()=>Object.values(Vs).filter(r=>typeof r=="number");var $n=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var _n=class{applyEdit=!0;workspaceEdit=new $n;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Fn(zs());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new at;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Wn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Un=class{constructor(e=[]){this.valueSet=e}valueSet};var Bn=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var qs=(b=>(b[b.Text=1]="Text",b[b.Method=2]="Method",b[b.Function=3]="Function",b[b.Constructor=4]="Constructor",b[b.Field=5]="Field",b[b.Variable=6]="Variable",b[b.Class=7]="Class",b[b.Interface=8]="Interface",b[b.Module=9]="Module",b[b.Property=10]="Property",b[b.Unit=11]="Unit",b[b.Value=12]="Value",b[b.Enum=13]="Enum",b[b.Keyword=14]="Keyword",b[b.Snippet=15]="Snippet",b[b.Color=16]="Color",b[b.File=17]="File",b[b.Reference=18]="Reference",b[b.Folder=19]="Folder",b[b.EnumMember=20]="EnumMember",b[b.Constant=21]="Constant",b[b.Struct=22]="Struct",b[b.Event=23]="Event",b[b.Operator=24]="Operator",b[b.TypeParameter=25]="TypeParameter",b))(qs||{}),Ys=()=>Object.values(qs).filter(r=>typeof r=="number");var Vn=class{completionItemKind=new Un(Ys());completionItem=new Bn;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var zn=class{synchronization=new Wn;completion=new Vn;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 at;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var qn=class{workspace=new _n;textDocument=new zn;notebookDocument=null;window=null;general=null;experimental=null};var Yn=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function ct(r){return g(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function Gs(r){return g(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function Js(r){if(!g(r)||typeof r.text!="string")return!1;let e=r.range;return g(e)?ct(e.start)&&ct(e.end):!1}var Jn=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=Gn.resolve(t,"ace-server","out","index.js"),this.logPath=Ns(),this.indexLogPath=i||this.logPath,this.messageHandle=new An({serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath}),this.messageHandle.setBroadcastToClients(s=>this.onLspMessage(s))}sdkPath;rootUri;nodeMaxOldSpaceSize;messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let n=!1;try{l.info(`serverPath: ${this.serverPath}`),l.info(`rootUri: ${this.rootUri}`),l.info(`sdkPath: ${this.sdkPath}`),l.info(`logPath: ${this.logPath}`);let i=ge(this.rootUri),o=new On(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Ht(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let d=$s(s.length,this.nodeMaxOldSpaceSize);await this.messageHandle.start(d),this.currentParams=new Yn(i,o,new qn),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:M,method:w.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((u,y)=>{this.messageHandle.onIndexingProgressUpdate(y),this.messageHandle.onInitializationCompleted(u)},"LSP initialization",kt),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=ge(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=g(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:M,method:n,params:{uri:typeof o.uri=="string"?o.uri:t,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(a=>typeof a=="string"):[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(n,i)=>{l.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${n}`);let o={jsonrpc:M,id:e,result:g(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Ht(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,y)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,y)}),this.markAddAndDeleteInDeps(a,d,(u,y)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,y)})}}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 _e({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new nt(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new rt([]),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=Pn(Gn.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=Pn(Gn.join(t,"default/openharmony/ets/api")),o=Pn(Gn.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case w.HOVER:this.handleHoverRequest(e);break;case w.DEFINITION:this.handleDefinitionRequest(e);break;case w.REFERENCES:this.handleReferencesRequest(e);break;default:l.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!g(n)||typeof n.uri!="string"||!ct(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(w.ON_ASYNC_HOVER,t,o,X.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!g(n)||typeof n.uri!="string"||!ct(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(w.ON_ASYNC_DEFINITION,t,o,X.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!g(n)||typeof n.uri!="string"||!ct(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(w.ON_ASYNC_FIND_USAGES,t,o,X.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!xs(e)){l.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case w.DID_OPEN:this.handleDidOpenNotification(e);break;case w.DID_CHANGE:this.handleDidChangeNotification(e);break;case w.DID_CLOSE:this.handleDidCloseNotification(e);break;case w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case w.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:l.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!g(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!Gs(n)||!ni(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(!g(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!g(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(Js)){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(!g(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!g(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(!g(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(!g(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 ve from"fs";import*as Ae from"path";import{createHash as gu}from"crypto";import{EventEmitter as yu}from"events";var Kn=class extends yu{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),n=new Set(this.watchers.keys());for(let i of t)n.has(i)||this.watchFile(i);for(let i of n)t.has(i)||(this.unwatchFile(i),l.info(`[ConfigFileWatcher] Stopped watching: ${i}`));l.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!ve.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=ve.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=S.resolvePathWithinRoot(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=S.resolvePathWithinRoot(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=S.resolvePathWithinRoot(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=S.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){l.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,l.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=Ae.join(this.projectRoot,D.OH_PACKAGE_JSON5);ve.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=S.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Ae.join(s,D.OH_PACKAGE_JSON5);ve.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Ae.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=ve.readFileSync(t,"utf-8");return gu("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=ve.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:Ae.basename(t),relativePath:Ae.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 ke from"fs";import*as re from"path";import{createHash as vu}from"crypto";import{EventEmitter as wu}from"events";var Xn=class extends wu{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=re.join(t,xt)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!ke.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=ke.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 _(re.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===D.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===We)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=re.join(this.depMapDir,n);ke.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=re.join(this.depMapDir,D.OH_PACKAGE_JSON5),n=re.join(this.depMapDir,We),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:re.join(this.depMapDir,s.name,D.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!ke.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=re.join(this.depMapDir,We);try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of n)i.add(o.info.newName);return i}emitIncrementalReload(t,n,i,o,s){l.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(l.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){l.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(n,i,o,s,a);for(let d of o)s.delete(d);if(o.size===0&&s.size===0&&a.length===0){l.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return _(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=re.join(this.depMapDir,a.name,D.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=re.join(this.depMapDir,o,D.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=ke.readFileSync(t,"utf-8");return vu("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as bu}from"child_process";import*as er from"path";import*as Qn from"fs";var Su=600*1e3;function Pu(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function Eu(r){let e=[],t=[];return r.stdout?.on("data",n=>{e.push(n.toString())}),r.stderr?.on("data",n=>{t.push(n.toString())}),{stdout:e,stderr:t}}function Zn(r){return r.join("")}function Cu(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1238
1238
|
Output so far:
|
|
1239
|
-
`+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function
|
|
1239
|
+
`+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function Du(r,e,t){return new Promise(n=>{let i=bu(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=Eu(i),a=setTimeout(()=>{i.kill();let c=[Zn(o),Zn(s)].filter(Boolean).join(`
|
|
1240
1240
|
`).trim();n({success:!1,output:`Build process timeout after 10 minutes.
|
|
1241
1241
|
Output so far:
|
|
1242
|
-
`+c,exitCode:-1})},
|
|
1243
|
-
`).trim()||"";n(
|
|
1242
|
+
`+c,exitCode:-1})},Su);i.on("close",(c,d)=>{clearTimeout(a);let u=[Zn(o),Zn(s)].filter(Boolean).join(`
|
|
1243
|
+
`).trim()||"";n(Cu(c,d,u))}),i.on("error",c=>{clearTimeout(a),n({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function ri(r,e,t,n,i){let o={...process.env,DEVECO_SDK_HOME:n},s=Pu(e,t,i);return await Du(s,r,o)}function Iu(r){let e=er.join(er.dirname(r),"tools","hvigor","bin","hvigorw.js");return{node_path:yn(r),hvigor_path:e,sdk_path:r}}function Au(r){return!r.node_path||!Qn.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!Qn.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!Qn.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var ku="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Ks(r,e){try{let t=Iu(e),n=Au(t);return n!=null?(l.info(`Config validation failed: ${n}`),!1):(await ri(r,t.node_path,t.hvigor_path,e,ku)).success}catch(t){return l.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as Tu}from"child_process";import*as ii from"fs";import*as jt from"path";var Mu=["install","--all"];function Ru(r){let e=r.replace(/sdk\/?$/i,"tools"),t=jt.join(e,"ohpm","bin","pm-cli.js");if(ii.existsSync(t))return t;let n=r.toLowerCase().endsWith("sdk")?jt.dirname(r):r;return t=jt.join(n,"ohpm","bin","pm-cli.js"),ii.existsSync(t)?t:null}async function xu(r,e,t,n){return new Promise(i=>{let o=Tu(r,[e,...Mu],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let d=[s,a].filter(Boolean).join(`
|
|
1244
1244
|
`);i({exitCode:c??-1,output:d})}),o.on("error",c=>{let d=[s,a].filter(Boolean).join(`
|
|
1245
1245
|
`);i({exitCode:-1,output:d+`
|
|
1246
|
-
`+c.message})})})}function
|
|
1247
|
-
`):"\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=ie.isAbsolute(o)?o:ie.join(n,o);if(!we.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!we.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
|
|
1246
|
+
`+c.message})})})}function Ou(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>l.info("[ohpm] %s",e))}async function Xs(r,e){try{let t=yn(e);if(!t)return l.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let n=Ru(e);if(!n)return l.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await xu(t,n,r,e);return Ou(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 Zs={UNINITIALIZED:-32099,UNKNOWN:-32e3},Ft=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,Zs.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,Zs.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var lt=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t){if(l.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return l.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let n=await bi(e,async()=>await Xs(e,t)?await Ks(e,t)?(l.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(l.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(l.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return n.acquired?n.result:(l.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){l.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Jn(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)l.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:M,method:w.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();l.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?Ft.uninitialized(t):Ft.unknown();this.onMessage({jsonrpc:M,method:w.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(l.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:M,method:w.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Kn(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:M,method:w.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:n}}),this.onMessage({jsonrpc:M,method:w.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){l.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var Lu=120*1e3,Nu=10080*60*1e3,Hu=7200*60*1e3,dt=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;constructor(e,t,n){this.projectPath=e,this.devecoPath=t??"",this.nodeMaxOldSpaceSize=n}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:oi.object({files:oi.array(oi.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=ue(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Kr(s,Nu,"[ArkTS-Check]"),Kr(o,Hu,"[ArkTS-Check]")}),Ls(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;f.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let d=ie.join(de(t),"sdk");f.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${de(t)}, sdkPath: ${d}`),this.manager=new lt({sdkPath:d,arktsLangServerPath:n,workspaceRoot:_(i),indexLogPath:s,nodeMaxOldSpaceSize:c}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((u,y)=>{this.initResolve=u,this.initReject=y,this.armInitTimer(kt),this.manager.start([]).catch(k=>{let H=k instanceof Error?k:new Error(String(k));this.failInit(H)})})}resolveProjectAndDeveco(){let e=me(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Fe();if(f.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=bs(t);if(!n)throw new Error("arkts-lang-server path not found");return{harmonyRoot:e,devecoPath:t,arktsLangServerPath:n}}armInitTimer(e){this.initDeadlineTimer&&clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=setTimeout(()=>{let t=this.initReject;this.clearInitHandlers(),t?.(new Error("LSP initialize timeout"))},e)}clearInitHandlers(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async checkFile(e){this.initialized||await this.initialize();let t=At($e(e)),n=Jr(e),i=await we.promises.readFile(e,"utf8"),s=`deveco.apptool.${ie.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((d,u)=>{let y=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},Lu);this.diagnosticWaiters.set(t,{resolve:d,reject:u,timer:y})}),c={textDocument:{uri:n,text:i,languageId:s,version:i.length},editorFiles:[n],isFromEditor:!1};f.debug(`textDocument/didOpen uri=${n} content_len=${i.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],n=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1247
|
+
`):"\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=ie.isAbsolute(o)?o:ie.join(n,o);if(!we.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!we.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 Es(500);try{let o=await this.checkFile(i);n.push(ju(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(`
|
|
1248
1248
|
`)),t.length>0&&n.push(t.join(`
|
|
1249
1249
|
`));let i=n.join(`
|
|
1250
|
-
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(
|
|
1250
|
+
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(kt),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";f.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let n=this.resolveDiagnosticWaiter(t);if(!n)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),n.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;f.debug(`diagnostics received uri=${t} count=${o}`),n.resolve(Array.isArray(i)?i:[])}resolveDiagnosticWaiter(e){let t=At(e),n=this.popDiagnosticWaiter(t);if(n)return n;for(let i of Ds(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=ie.join(gn(),"ArkTSCheck"),n=ie.join(t,"mapping-config.properties"),i=Is(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=ie.join(t,"lsp-log",String(i),o),a=ie.join(t,"lsp-index",String(i));return we.mkdirSync(s,{recursive:!0}),we.mkdirSync(a,{recursive:!0}),{logPath:ue(s),indexPath:ue(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function ju(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 Fu}from"child_process";import*as A from"fs";import*as N from"path";import{z as si}from"zod";var Qs=60*1e3,$u=30*1e3,_u=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),Wu=1e3,ai=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let n=ue(this.projectPath),i=$e(n),o=N.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"1.2.0-Test.4"},rootPath:n,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,Qs),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=Qs,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(n=>setTimeout(n,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=A.realpathSync(e)}catch{t=e}let n=$e(t),i=Cs(t),o=await A.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(n)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},$u);this.diagnosticWaiters.set(n,{resolve:a,reject:c,timer:d})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,languageId:i,version:1,text:o}})}catch(a){let c=this.diagnosticWaiters.get(n);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(n)),a}try{return await s}finally{await this.closeFile(n).catch(a=>{f.warn(`[CppCheck] didClose failed for ${n}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(n);return}_u.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
|
|
1251
1251
|
\r
|
|
1252
1252
|
`,"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
|
|
1253
1253
|
\r
|
|
1254
|
-
`);if(t<0)return;let n=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(n);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){f.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,n=t.uri;if(!n)return;let i
|
|
1254
|
+
`);if(t<0)return;let n=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(n);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){f.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,n=t.uri;if(!n)return;let i=Uu(n),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];f.info(`[CppCheck] Received C++ diagnostics for ${i} (${s.length} entries)`),o.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(n=>{t=n}),await e,t}};function Uu(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)),$e(t)}}catch{}return r}function Bu(r){let e=N.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Vu(r,e){let t=N.join(r,e.name);return e.isDirectory()?e.name===".cxx"||ea(t):Bu(t)}function ea(r){if(!A.existsSync(r))return!1;try{return A.readdirSync(r,{withFileTypes:!0}).some(t=>Vu(r,t))}catch{}return!1}function ta(r){let t=new Ue(r).getAllModuleInfo(),n=[];for(let i of t){let o=S.resolvePathWithinRoot(r,i.srcPath);ea(o)&&n.push(i)}return n}function zu(r){let e=[],n=new Ue(r).getAllModuleInfo();for(let i of n){let o=S.resolvePathWithinRoot(r,i.srcPath),s=N.join(o,".cxx");A.existsSync(s)&&na(s,e)}return e}function na(r,e){try{let t=A.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=N.join(r,n.name);n.isDirectory()?na(i,e):n.name==="compile_commands.json"&&e.push(i)}}catch{}}function qu(r){let e=[];for(let t of r)try{let n=A.readFileSync(t,"utf8"),i=JSON.parse(n);e.push(...i)}catch{}return e}function Yu(r,e){let t=N.join(r,...Yr.slice(0,-1));A.mkdirSync(t,{recursive:!0});let n=N.join(t,"compile_commands.json");A.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function Gu(r){let e=zu(r);if(e.length>0){let t=qu(e);Yu(r,t),f.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else f.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function Ju(r){let e=new Set;for(let t of r)if(t.file)try{e.add(A.realpathSync(t.file))}catch{e.add(t.file)}return e}function Ku(r,e){try{let t=A.realpathSync(r);if(!e.has(t))return f.info(`[CppCheck] File not covered by compile_commands.json: ${r}`),!1}catch{}return!0}function Xu(r,e){if(!A.existsSync(r))return!1;try{let t=A.readFileSync(r,"utf8"),n=JSON.parse(t),i=Ju(n);for(let o of e)if(!Ku(o,i))return!1;return!0}catch(t){return f.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}async function Zu(r,e,t){let n=N.join(de(e),"sdk"),i=process.execPath||"node",o=N.join(de(e),"tools");f.info(`CppCheck devecoPath: ${e}, contentRoot: ${de(e)}, sdkPath: ${n}, toolsDir: ${o}`);let s=N.join(o,"hvigor","bin","hvigorw.js");for(let a of t){let c=["--mode","module","-p",`module=${a.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");f.info(`[CppCheck] Running compileNative for module: ${a.name}`);let d=await ri(r,i,s,n,c);d.success?f.info(`[CppCheck] compileNative ${a.name} \u6210\u529F`):f.warn(`[CppCheck] compileNative ${a.name} \u5931\u8D25: ${d.output}`)}}async function Qu(r,e){let t=ta(r);if(t.length===0){f.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}f.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(n=>n.name).join(", ")}`),await Zu(r,e,t),Gu(r)}var ut=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=fn(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:si.object({files:si.array(si.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(`
|
|
1255
1255
|
`):"\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(`
|
|
1256
1256
|
`)}],isError:!0}}return await this.runDiagnosticsForFiles(o,i,t,n)&&this.shutdown().catch(a=>{f.warn(`[CppCheck] shutdown after diagnostic failure: ${a}`)}),this.formatCallResult(t,n)}async runDiagnosticsForFiles(e,t,n,i){let o=!1;for(let s of t)try{let a=await e.checkFile(s);a.length===0?i.push(`${s} => \u65E0\u8BCA\u65AD`):i.push(`${s} => Diagnostic: ${JSON.stringify(a)}`)}catch(a){o=!0,n.push(`${s} => \u83B7\u53D6\u8BCA\u65AD\u5931\u8D25: ${a.message}`)}return o}formatCallResult(e,t){let n=e.length>0;return!n&&t.length===0&&t.push("\u6CA1\u6709\u8FD4\u56DE\u4EFB\u4F55\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:[t.join(`
|
|
1257
1257
|
`),e.join(`
|
|
1258
1258
|
`)].filter(o=>o.trim().length>0).join(`
|
|
1259
|
-
`).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=ue(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??
|
|
1260
|
-
`)}],isError:!0}:null}let n=e.filter(i=>
|
|
1261
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(y=>typeof y=="string"):[];if(t.length===0)return f.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let n=this.validateContainment(t);if(n)return n;let{etsFiles:i,cppFiles:o,unsupported:s}=
|
|
1259
|
+
`).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=ue(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(f.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??Fe();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,await Qu(t,i)}else if(this.client&&this.initializedProjectPath){let i=ue(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let n=hn(e);return A.existsSync(n)?ta(e).length===0?(f.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Xu(n,t)?(f.info("[CppCheck] All files covered, no initialization needed"),!1):(f.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(f.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new ai,await this.client.initialize(e),this.initializedProjectPath=e,f.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=me(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);return this.projectPath=e,ue(e)}startPollingForClangd(e){let t=hn(e);if(A.existsSync(t)){f.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(n=>{f.error(`[CppCheck] Immediate clangd spawn failed: ${n}`)});return}f.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}A.existsSync(t)&&(this.stopPolling(),f.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(n=>{f.error(`[CppCheck] Clangd spawn from poll failed: ${n}`)}))},Wu)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:n}=this.resolveClangdPaths(e);f.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let i=this.spawnClangd(t,e,n);this.clangdProcess=i;try{await this.client.connectClangdProcess(i.stdin,i.stdout),this.backendReady=!0,f.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(f.error(`[CppCheck] Failed to connect clangd: ${o}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw o}}resolveClangdPaths(e){let t=this.devecoPath??Fe();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=Ss(t);if(!n)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=hn(e),o=N.dirname(i);return{clangdPath:n,compileCommandsDir:o}}spawnClangd(e,t,n){let i=Fu(e,[`--compile-commands-dir=${n}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Failed to start clangd: stdio not available");return i.stderr.on("data",o=>{let s=o.toString("utf8").trimEnd();s&&f.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{f.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{f.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=N.isAbsolute(o)?o:N.join(n,o);if(!A.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!A.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!mn(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(A.realpathSync(s))}catch{i.push(s)}}return i}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(n){f.warn(`[CppCheck] client.close() failed: ${n}`)}if(t&&!t.killed)try{t.kill()}catch(n){f.warn(`[CppCheck] failed to kill clangd: ${n}`)}}};function ra(r){let e=Yt(r);return l.info(`[SyncGuard] ${e.reason}`),e}var oa=(s=>(s[s.IDLE=0]="IDLE",s[s.DISCOVERING=1]="DISCOVERING",s[s.SYNCING=2]="SYNCING",s[s.INITIALIZING=3]="INITIALIZING",s[s.READY=4]="READY",s[s.ERROR=5]="ERROR",s))(oa||{}),li=3,ia=600*1e3,tr=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;constructor(e={}){this.config=e,Zr(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),f.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",f.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,f.info(`Constructor: using configured path as startPath: '${t}'`));let i=me(t);f.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new ep({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Vr(),this.registerTools()}registerTools(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:ci.object({files:ci.array(ci.string()).min(1).describe("List of source file paths to check, relative to the project root. Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=S.isPathContainedWithSymlink(o,t);s.contained||(f.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
|
|
1260
|
+
`)}],isError:!0}:null}let n=e.filter(i=>pt.isAbsolute(i));return n.length>0?(f.warn(`Absolute paths rejected (no project root): ${n.join(", ")}`),{content:[{type:"text",text:n.map(i=>`Absolute path is not allowed: ${i}`).join(`
|
|
1261
|
+
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(y=>typeof y=="string"):[];if(t.length===0)return f.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};let n=this.validateContainment(t);if(n)return n;let{etsFiles:i,cppFiles:o,unsupported:s}=np(t);s.length>0&&f.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(y=>`Unsupported file type: ${y} (only .ets and C/C++ source/header files are supported)`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let d=a.length>0;return{content:[{type:"text",text:[c.join(`
|
|
1262
1262
|
`),a.join(`
|
|
1263
1263
|
`)].filter(y=>y.trim().length>0).join(`
|
|
1264
|
-
`).trim()||"No diagnostics collected"}],isError:d}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${
|
|
1265
|
-
`);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Zu;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Ts();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let n=me(t);n?(f.info(`Detected project path from client root: ${n}`),this.config.projectPath=n,this.sdkPath=this.computeSdkPath()):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}catch(t){f.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{f.error("shutdown failed:",n),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new lt(e,this.config.devecoPath??null),f.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{f.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?me(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=me(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new ct(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=na(e);return t.required?(f.info(`Sync required: ${t.reason}`),this.runSync(e)):(f.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,f.info("Starting project sync...");let t=await at.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let n=Date.now()-this.syncSkipStartedAt,i=Math.round(n/1e3);return n>=ra?(f.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${ra/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=pn(this.config.devecoPath??""),t=de(e);return dt.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),ks(),As()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function Qu(r){let e=[],t=[],n=[];for(let i of r)dt.extname(i).toLowerCase()===".ets"?e.push(i):hn(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function li(r={}){return new Qn(r)}async function tp(){let r=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await O.new(),o=r,s=e??i.devecoStudioPath,a=li({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 oa=new ep("serve").description("Host bundled auxiliary protocol servers");oa.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await tp()});var sa=oa;import{Command as dp,InvalidArgumentError as pi}from"commander";import{red as $t,dim as up}from"colorette";import*as G from"path";import*as oe from"fs";import{homedir as np}from"os";import{execa as rp}from"execa";import{rgPath as ip}from"@vscode/ripgrep";import op from"adm-zip";import{fileURLToPath as sp}from"url";import ap from"ora";var jt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Ft={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var cp="deveco-cli",lp="docs",di=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=G.join(np(),".local","share",cp,lp),this.versionFile=G.join(this.docsDir,".version")}getDocsDir(){return this.docsDir}async ensureInitialized(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.extractDocsIfNeeded(),await this.initPromise,this.initialized=!0}}async extractDocsIfNeeded(){let e=this.getCurrentVersion();await this.getExistingVersion()!==e&&await this.extractDocs(e)}getCurrentVersion(){return"1.2.0-Test.3"}async getExistingVersion(){try{return(await oe.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=ap({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=G.dirname(this.docsDir);await oe.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await oe.promises.mkdir(this.docsDir,{recursive:!0}),new op(t).extractAllTo(this.docsDir,!0),await oe.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=sp(e),n=G.dirname(t),i=[G.join(n,"..","docs.zip")];for(let o of i)if(oe.existsSync(o))return o;return null}async cleanOldDocs(){try{await oe.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?G.join(this.docsDir,Ft[t]):this.docsDir,i=await this.searchFiles(e,n),o=await this.enrichWithTitleRelevance(i,e),s=this.selectByTiers(o,e.length);return(await Promise.all(s.map(async c=>{let d=this.parseFilePath(c.filePath);if(!d||!c.metadata)return null;let u=await this.readContentPreview(c.filePath);return{title:c.metadata.title,documentId:d,content:u}}))).filter(c=>c!==null)}selectByTiers(e,t){let n=(a,c)=>c.totalMatches-a.totalMatches,i=e.filter(a=>a.titleKeywordCount===t).sort(n),o=e.filter(a=>a.keywordCount===t&&a.titleKeywordCount<t).sort(n),s=e.filter(a=>a.keywordCount<t&&a.titleKeywordCount<t).sort(n);return[...i,...o,...s]}async enrichWithTitleRelevance(e,t){return Promise.all(Array.from(e.entries()).map(async([n,i])=>{let o=await this.readMetadata(n),s=o?t.filter(a=>o.title.toLowerCase().includes(a.toLowerCase())).length:0;return{filePath:n,keywordCount:i.keywordCount,totalMatches:i.totalMatches,titleKeywordCount:s,metadata:o}}))}async searchSingleKeyword(e,t){let i=await rp(ip,["--type","md","--json","--no-messages","-i","-e",e,t],{reject:!1});if(i.exitCode===1)return new Map;if(i.exitCode!==0)throw new Error(i.stderr?.trim()||`Search failed with exit code ${i.exitCode}`);return this.parseSearchResults(i.stdout)}async searchFiles(e,t){let n=await Promise.all(e.map(o=>this.searchSingleKeyword(o,t))),i=new Map;for(let o of n)for(let[s,a]of o){let c=i.get(s);c?(c.keywordCount+=1,c.totalMatches+=a):i.set(s,{keywordCount:1,totalMatches:a})}return i}parseSearchResults(e){let t=e.split(`
|
|
1266
|
-
`),n=new Map;for(let i of t){if(!i)continue;let o=this.parseSearchResultLine(i);o&&n.set(o.filePath,o.count)}return n}parseSearchResultLine(e){try{let t=JSON.parse(e);if(t.type==="end"&&t.data?.path?.text){let n=t.data.stats?.matches??0;if(n>0)return{filePath:t.data.path.text,count:n}}}catch{}return null}async readDocument(e){await this.ensureInitialized();let n=[e,`${e}.md`].filter(i=>S.isPathContainedWithSymlink(i,this.docsDir).contained).map(i=>G.join(this.docsDir,i));for(let i of n)try{return await oe.promises.readFile(i,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=G.relative(this.docsDir,e);if(!t||t.startsWith("..")||G.isAbsolute(t))return null;let n=t.split(/[/\\]/);if(n.length<2)return null;let i=n[n.length-1];return n[n.length-1]=i.replace(/\.md$/,""),n.join("/")}async readMetadata(e){let t=e.replace(/\.md$/,".json");try{let n=await oe.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await oe.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""}}},
|
|
1264
|
+
`).trim()||"No diagnostics collected"}],isError:d}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return f.warn(`ArkTS check rejected: project is ${oa[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return f.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e})}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),f.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(f.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(f.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=li?(f.error(`Init retry limit reached (${this.initRetryCount}/${li}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(f.info(`Error check: auto-retrying (${this.initRetryCount}/${li})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return f.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,n){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1265
|
+
`);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{f.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,f.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{f.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new tp;if(await this.server.connect(e),f.info("devecocli-mcp-server started"),!this.config.debug){let t=Ms();t&&f.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let n=me(t);n?(f.info(`Detected project path from client root: ${n}`),this.config.projectPath=n,this.sdkPath=this.computeSdkPath()):f.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?f.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):f.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{f.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return f.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return f.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}catch(t){f.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,f.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{f.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{f.error("shutdown failed:",n),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){f.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new ut(e,this.config.devecoPath??null),f.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{f.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?me(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=me(this.originalProjectPath),t&&f.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new dt(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{f.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,f.info("Project fully initialized, check tool is available")}catch(e){f.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=ra(e);return t.required?(f.info(`Sync required: ${t.reason}`),this.runSync(e)):(f.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,f.info("Starting project sync...");let t=await lt.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let n=Date.now()-this.syncSkipStartedAt,i=Math.round(n/1e3);return n>=ia?(f.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(f.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${ia/1e3}s)`),this.projectState=0,!1)}case"failed":return f.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=fn(this.config.devecoPath??""),t=de(e);return pt.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){f.warn("Failed to close MCP server connection:",e)}f.info("devecocli-mcp-server stopped"),Ts(),ks()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function np(r){let e=[],t=[],n=[];for(let i of r)pt.extname(i).toLowerCase()===".ets"?e.push(i):mn(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function di(r={}){return new tr(r)}async function ip(){let r=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,n=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await O.new(),o=r,s=e??i.devecoStudioPath,a=di({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 sa=new rp("serve").description("Host bundled auxiliary protocol servers");sa.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await ip()});var aa=sa;import{Command as hp,InvalidArgumentError as hi}from"commander";import{red as Wt,dim as fp}from"colorette";import*as G from"path";import*as oe from"fs";import{homedir as op}from"os";import{execa as sp}from"execa";import{rgPath as ap}from"@vscode/ripgrep";import cp from"adm-zip";import{fileURLToPath as lp}from"url";import dp from"ora";var $t=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],_t={"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 up="deveco-cli",pp="docs",ui=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=G.join(op(),".local","share",up,pp),this.versionFile=G.join(this.docsDir,".version")}getDocsDir(){return this.docsDir}async ensureInitialized(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.extractDocsIfNeeded(),await this.initPromise,this.initialized=!0}}async extractDocsIfNeeded(){let e=this.getCurrentVersion();await this.getExistingVersion()!==e&&await this.extractDocs(e)}getCurrentVersion(){return"1.2.0-Test.4"}async getExistingVersion(){try{return(await oe.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=dp({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=G.dirname(this.docsDir);await oe.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await oe.promises.mkdir(this.docsDir,{recursive:!0}),new cp(t).extractAllTo(this.docsDir,!0),await oe.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=lp(e),n=G.dirname(t),i=[G.join(n,"..","docs.zip")];for(let o of i)if(oe.existsSync(o))return o;return null}async cleanOldDocs(){try{await oe.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?G.join(this.docsDir,_t[t]):this.docsDir,i=await this.searchFiles(e,n),o=await this.enrichWithTitleRelevance(i,e),s=this.selectByTiers(o,e.length);return(await Promise.all(s.map(async c=>{let d=this.parseFilePath(c.filePath);if(!d||!c.metadata)return null;let u=await this.readContentPreview(c.filePath);return{title:c.metadata.title,documentId:d,content:u}}))).filter(c=>c!==null)}selectByTiers(e,t){let n=(a,c)=>c.totalMatches-a.totalMatches,i=e.filter(a=>a.titleKeywordCount===t).sort(n),o=e.filter(a=>a.keywordCount===t&&a.titleKeywordCount<t).sort(n),s=e.filter(a=>a.keywordCount<t&&a.titleKeywordCount<t).sort(n);return[...i,...o,...s]}async enrichWithTitleRelevance(e,t){return Promise.all(Array.from(e.entries()).map(async([n,i])=>{let o=await this.readMetadata(n),s=o?t.filter(a=>o.title.toLowerCase().includes(a.toLowerCase())).length:0;return{filePath:n,keywordCount:i.keywordCount,totalMatches:i.totalMatches,titleKeywordCount:s,metadata:o}}))}async searchSingleKeyword(e,t){let i=await sp(ap,["--type","md","--json","--no-messages","-i","-e",e,t],{reject:!1});if(i.exitCode===1)return new Map;if(i.exitCode!==0)throw new Error(i.stderr?.trim()||`Search failed with exit code ${i.exitCode}`);return this.parseSearchResults(i.stdout)}async searchFiles(e,t){let n=await Promise.all(e.map(o=>this.searchSingleKeyword(o,t))),i=new Map;for(let o of n)for(let[s,a]of o){let c=i.get(s);c?(c.keywordCount+=1,c.totalMatches+=a):i.set(s,{keywordCount:1,totalMatches:a})}return i}parseSearchResults(e){let t=e.split(`
|
|
1266
|
+
`),n=new Map;for(let i of t){if(!i)continue;let o=this.parseSearchResultLine(i);o&&n.set(o.filePath,o.count)}return n}parseSearchResultLine(e){try{let t=JSON.parse(e);if(t.type==="end"&&t.data?.path?.text){let n=t.data.stats?.matches??0;if(n>0)return{filePath:t.data.path.text,count:n}}}catch{}return null}async readDocument(e){await this.ensureInitialized();let n=[e,`${e}.md`].filter(i=>S.isPathContainedWithSymlink(i,this.docsDir).contained).map(i=>G.join(this.docsDir,i));for(let i of n)try{return await oe.promises.readFile(i,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=G.relative(this.docsDir,e);if(!t||t.startsWith("..")||G.isAbsolute(t))return null;let n=t.split(/[/\\]/);if(n.length<2)return null;let i=n[n.length-1];return n[n.length-1]=i.replace(/\.md$/,""),n.join("/")}async readMetadata(e){let t=e.replace(/\.md$/,".json");try{let n=await oe.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await oe.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""}}},pi=new ui;function ca(...r){return e=>{if(!r.includes(e))throw new hi(`Allowed values: ${r.join(", ")}`);return e}}function mp(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new hi("Must be a positive integer.");return e}var gp=ca("json","default"),yp=ca("json","default"),nr=new hp("docs").description("Search and read HarmonyOS documentation from local docs directory");nr.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all : all catalogs)",vp,"all").option("--format <fmt>","Output format (default, json)",gp,"default").option("--limit <n>","Max number of results",mp,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error(Wt("Keywords cannot be empty.")),process.exit(1)),t.length>10&&(console.error(Wt("Keywords cannot exceed 10.")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await pi.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):wp(o)}catch(t){console.error(Wt(t.message)),process.exit(1)}});nr.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error(Wt("Document ID cannot be empty.")),process.exit(1));let t=await pi.readDocument(e);console.log(t)}catch(e){console.error(Wt(e.message)),process.exit(1)}});nr.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (options: default,json)",yp,"default").action(r=>{if(r.format==="json"){let e=$t.map(t=>({name:t,title:_t[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of $t)console.log(` ${e.padEnd(20)} ${fp(_t[e])}`)});function vp(r){if(r==="all")return"all";if(!$t.includes(r))throw new hi(`Invalid catalog "${r}". Allowed: all, ${$t.join(", ")}`);return r}function wp(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 la=nr;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";bp();U.name("devecocli").description("HarmonyOS application development command line tool").version("1.2.0-Test.4");U.addCommand(Ai);U.addCommand(Ni);U.addCommand($i);U.addCommand(Xi);U.addCommand(wo);U.addCommand(zo);U.addCommand(Jo);U.addCommand(os);U.addCommand(hs);U.addCommand(aa);U.addCommand(la);var fi=process.argv.slice(2);fi.length>=2&&fi[fi.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Pp=new Set(["update"]);U.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==U;)t=t.parent;Pp.has(t.name())||await O.checkVersion()});U.parseAsync(process.argv).catch(r=>{let e=r instanceof Error?r.message:String(r??"Unknown error");console.error(Sp(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});
|